用 Pygame 开发贪吃蛇完整教程

📅 2026-07-20 👁️ 128 阅读 🏷️ Python / Pygame

1. 环境准备

首先安装 Python 3.8+,然后通过 pip 安装 Pygame:
pip install pygame

2. 游戏初始化

创建窗口并设置基础参数:
import pygame
import random

pygame.init()
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇 Pro")
clock = pygame.time.Clock()

3. 核心逻辑

蛇的移动、食物生成、碰撞检测逻辑完整实现,代码已上传 GitHub,欢迎 Star 交流。
# 蛇身数组
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True

direction = 'RIGHT'
change_to = direction

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction != 'DOWN':
                change_to = 'UP'
            if event.key == pygame.K_DOWN and direction != 'UP':
                change_to = 'DOWN'
            if event.key == pygame.K_LEFT and direction != 'RIGHT':
                change_to = 'LEFT'
            if event.key == pygame.K_RIGHT and direction != 'LEFT':
                change_to = 'RIGHT'

    # 验证逻辑...
    # 更新显示...
    pygame.display.flip()
    clock.tick(15)