編寫一個小游戲可以使用Python的Pygame模塊來實現。以下是一個簡單的示例代碼來創建一個小游戲:
import pygame
import sys
import random
# 初始化pygame
pygame.init()
# 設置游戲窗口大小
WIDTH, HEIGHT = 800, 600
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("小游戲")
# 設置顏色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 設置游戲變量
player_size = 50
player_pos = [WIDTH//2, HEIGHT-2*player_size]
enemy_size = 50
enemy_pos = [random.randint(0, WIDTH-enemy_size), 0]
enemy_list = [enemy_pos]
SPEED = 10
# 設置游戲循環
game_over = False
clock = pygame.time.Clock()
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 游戲邏輯
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_pos[0] > 0:
player_pos[0] -= SPEED
if keys[pygame.K_RIGHT] and player_pos[0] < WIDTH-player_size:
player_pos[0] += SPEED
# 移動敵人
for idx, enemy in enumerate(enemy_list):
if enemy[1] >= 0 and enemy[1] < HEIGHT:
enemy[1] += SPEED
else:
enemy_list.pop(idx)
if random.random() < 0.02:
enemy_list.append([random.randint(0, WIDTH-enemy_size), 0])
# 碰撞檢測
for enemy in enemy_list:
if enemy_pos[1] >= player_pos[1] and enemy_pos[1] <= player_pos[1]+player_size:
if enemy_pos[0] >= player_pos[0] and enemy_pos[0] <= player_pos[0]+player_size:
game_over = True
# 渲染游戲場景
win.fill(WHITE)
# 渲染玩家
pygame.draw.rect(win, RED, (player_pos[0], player_pos[1], player_size, player_size))
# 渲染敵人
for enemy in enemy_list:
pygame.draw.rect(win, RED, (enemy[0], enemy[1], enemy_size, enemy_size))
pygame.display.update()
clock.tick(30)
這是一個簡單的游戲,玩家控制一個方塊躲避從上方下落的敵人方塊。玩家可以使用左右方向鍵移動自己的方塊,如果敵人方塊碰到玩家方塊則游戲結束。您可以根據自己的需求對游戲進行更多的定制和擴展。