编写一个小游戏可以使用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)
这是一个简单的游戏,玩家控制一个方块躲避从上方下落的敌人方块。玩家可以使用左右方向键移动自己的方块,如果敌人方块碰到玩家方块则游戏结束。您可以根据自己的需求对游戏进行更多的定制和扩展。