import pygame
import random
初始化 Pygame
pygame.init()
游戏窗口设置
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
clock = pygame.time.Clock()
颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
基础参数
CELL_SIZE = 20 # 蛇身、食物的尺寸
snake = [(WIDTH//2, HEIGHT//2)] # 蛇初始位置(列表存坐标,首元素为蛇头)
direction = (0, 0) # 初始静止,(dx, dy) 控制移动方向
food = (
random.randint(0, (WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
random.randint(0, (HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
) # 随机生成食物位置
score = 0
game_over = False
游戏主循环
while not game_over:
# 1. 事件处理(退出、按键控制)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
# 防止 180° 调头(比如向上时不能直接向下)
if event.key == pygame.K_UP and direction != (0, CELL_SIZE):
direction = (0, -CELL_SIZE)
elif event.key == pygame.K_DOWN and direction != (0, -CELL_SIZE):
direction = (0, CELL_SIZE)
elif event.key == pygame.K_LEFT and direction != (CELL_SIZE, 0):
direction = (-CELL_SIZE, 0)
elif event.key == pygame.K_RIGHT and direction != (-CELL_SIZE, 0):
direction = (CELL_SIZE, 0)
# 2. 蛇移动逻辑(方向非静止时更新)
if direction != (0, 0):
head_x, head_y = snake[0]
new_head = (head_x + direction[0], head_y + direction[1])
snake.insert(0, new_head) # 头部新增位置
# 3. 碰撞检测(边界、自身)
if (
new_head[0] < 0
or new_head[0] >= WIDTH
or new_head[1] < 0
or new_head[1] >= HEIGHT
or new_head in snake[1:] # 蛇头与身体其他部分碰撞
):
game_over = True
else:
# 4. 吃食物判断
if new_head == food:
score += 10 # 加分
# 生成新食物(避开蛇身)
while True:
food = (
random.randint(0, (WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
random.randint(0, (HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
)
if food not in snake:
break
else:
snake.pop() # 没吃到食物,尾部移除(保持长度)
# 5. 画面渲染
screen.fill(BLACK) # 填充背景
# 绘制食物
pygame.draw.rect(screen, RED, (*food, CELL_SIZE, CELL_SIZE))
# 绘制蛇身
for segment in snake:
pygame.draw.rect(screen, GREEN, (*segment, CELL_SIZE, CELL_SIZE))
# 显示分数
font = pygame.font.SysFont("simhei", 24)
score_text = font.render(f"分数: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
pygame.display.update() # 更新画面
clock.tick(10) # 控制帧率(数值越大速度越快)
游戏结束,退出 Pygame
pygame.quit()
浙公网安备 33010602011771号