以下是一个简单的贪吃蛇程序示例:
import pygame
import random
# 屏幕尺寸
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
# 小方格大小
GRID_SIZE = 20
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# 初始化 pygame
pygame.init()
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 蛇的初始位置和速度
snake_pos = [200, 100]
snake_speed = [0, 0]
# 蛇的身体坐标列表
snake_body = [[snake_pos[0], snake_pos[1]]]
# 食物位置
food_pos = [random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE]
# 游戏结束标志
game_over = False
# 时钟
clock = pygame.time.Clock()
# 绘制蛇
def draw_snake(snake_body):
for pos in snake_body:
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
# 绘制食物
def draw_food(food_pos):
pygame.draw.rect(screen, WHITE, [food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE])
# 游戏主循环
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_speed[1]!= GRID_SIZE:
snake_speed = [0, -GRID_SIZE]
elif event.key == pygame.K_DOWN and snake_speed[1]!= -GRID_SIZE:
snake_speed = [0, GRID_SIZE]
elif event.key == pygame.K_LEFT and snake_speed[0]!= GRID_SIZE:
snake_speed = [-GRID_SIZE, 0]
elif event.key == pygame.K_RIGHT and snake_speed[0]!= -GRID_SIZE:
snake_speed = [GRID_SIZE, 0]
# 根据速度移动蛇头
snake_pos[0] += snake_speed[0]
snake_pos[1] += snake_speed[1]
# 判断蛇是否吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_pos = [random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE]
else:
# 移除蛇尾
del snake_body[0]
# 添加蛇头到身体列表
snake_body.append([snake_pos[0], snake_pos[1]])
# 判断蛇是否撞到自己或边界
for block in snake_body[:-1]:
if block == snake_pos:
game_over = True
if snake_pos[0] < 0 or snake_pos[0] >= SCREEN_WIDTH or snake_pos[1] < 0 or snake_pos[1] >= SCREEN_HEIGHT:
game_over = True
# 清空屏幕
screen.fill(BLACK)
# 绘制蛇和食物
draw_snake(snake_body)
draw_food(food_pos)
# 更新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(10)
# 退出程序
pygame.quit()
代码解释:
• 首先定义了一些常量,如屏幕尺寸、小方格大小和各种颜色。
• 初始化 pygame 并创建屏幕。
• 定义了蛇的初始位置、速度和身体坐标列表,以及食物的位置。
• 定义了一些函数来绘制蛇和食物。
• 在主循环中,处理事件,根据按键改变蛇的速度,移动蛇头,判断是否吃到食物并进行相应处理,判断蛇是否撞到自己或边界。然后清空屏幕,绘制蛇和食物,更新屏幕,并控制帧率。
• 最后如果游戏结束则退出程序。