使用Python实现经典贪吃蛇游戏教程
运行效果图如下,完整代码在文末
一、环境准备
- 安装Python 3.x
- 安装pygame库:
pip install pygame
二、游戏功能说明
-
基本游戏机制
- 方向控制:↑ ↓ ← → 键控制蛇移动方向
- 得分规则:每吃1个食物得1分
- 碰撞检测:撞墙或自碰游戏结束
- 自动生成:食物随机生成且不与蛇体重叠
-
特色功能
- 分数实时显示
- 游戏结束后2秒自动重置
- 不同颜色区分蛇头和身体
- 方向输入缓冲机制(防止180°急转)
三、代码结构解析
1. 游戏初始化
pygame.init() # 初始化引擎
screen = pygame.display.set_mode((WIDTH, HEIGHT)) # 创建窗口
2. Snake类核心方法
reset()
: 重置游戏状态move()
: 处理蛇的移动逻辑check_food()
: 检测是否吃到食物generate_food()
: 生成新食物位置check_collision()
: 碰撞检测
3. 游戏主循环
while running:
# 事件处理
# 游戏逻辑更新
# 画面绘制
# 刷新显示
4. 图形绘制
- 使用
pygame.draw.rect
绘制方形元素 - 蛇头使用绿色,身体使用白色
- 食物使用红色方块
四、关键算法解析
1. 方向控制机制
# 方向有效性检查:不能直接反向
if (当前方向和新方向不相反):
更新方向
2. 食物生成算法
def generate_food(self):
while True:
生成随机位置
if 位置不在蛇身上:
return 该位置
3. 碰撞检测
# 边界检测
if 蛇头坐标超出窗口范围:
return True
# 自碰检测
for 每个身体段:
if 蛇头坐标 == 身体段坐标:
return True
五、运行与调试
- 直接运行python文件
- 常见问题解决:
- 如果出现导入错误:确认pygame是否安装成功
- 窗口无响应:检查事件循环是否正常退出
- 食物生成位置异常:检查CELL_SIZE是否为20的倍数
六、扩展建议
- 难度分级:通过速度分级增加可玩性
- 音效添加:吃食物和碰撞时添加音效
- 排行榜功能:记录历史最高分
- 界面美化:使用图片替代纯色方块
七、完整代码
import pygame
import random
import time
# 初始化Pygame
pygame.init()
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 游戏窗口设置
WIDTH = 800
HEIGHT = 600
CELL_SIZE = 20
SPEED = 15
# 初始化窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.reset()
def reset(self):
self.body = [[WIDTH//2, HEIGHT//2]]
self.direction = "RIGHT"
self.new_direction = "RIGHT"
self.score = 0
def move(self):
# 方向有效性检查
if (self.direction == "UP" and self.new_direction != "DOWN") or \
(self.direction == "DOWN" and self.new_direction != "UP") or \
(self.direction == "LEFT" and self.new_direction != "RIGHT") or \
(self.direction == "RIGHT" and self.new_direction != "LEFT"):
self.direction = self.new_direction
head = self.body[0].copy()
if self.direction == "UP":
head[1] -= CELL_SIZE
elif self.direction == "DOWN":
head[1] += CELL_SIZE
elif self.direction == "LEFT":
head[0] -= CELL_SIZE
elif self.direction == "RIGHT":
head[0] += CELL_SIZE
self.body.insert(0, head)
if not self.check_food():
self.body.pop()
def check_food(self):
global food_pos
if self.body[0] == food_pos:
self.score += 1
food_pos = self.generate_food()
return True
return False
def generate_food(self):
while True:
new_food = [
random.randrange(1, (WIDTH//CELL_SIZE)-1) * CELL_SIZE,
random.randrange(1, (HEIGHT//CELL_SIZE)-1) * CELL_SIZE
]
if new_food not in self.body:
return new_food
def check_collision(self):
# 边界检测
if (self.body[0][0] < 0 or self.body[0][0] >= WIDTH or
self.body[0][1] < 0 or self.body[0][1] >= HEIGHT):
return True
# 自碰检测
for segment in self.body[1:]:
if self.body[0] == segment:
return True
return False
def show_score(score):
font = pygame.font.SysFont(None, 35)
text = font.render(f"分数: {score}", True, BLUE)
screen.blit(text, (10, 10))
def game_over():
font = pygame.font.SysFont(None, 72)
text = font.render("游戏结束!", True, RED)
screen.blit(text, (WIDTH//2-120, HEIGHT//2-40))
pygame.display.flip()
time.sleep(2)
# 初始化蛇和食物
snake = Snake()
food_pos = snake.generate_food()
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.new_direction = "UP"
elif event.key == pygame.K_DOWN:
snake.new_direction = "DOWN"
elif event.key == pygame.K_LEFT:
snake.new_direction = "LEFT"
elif event.key == pygame.K_RIGHT:
snake.new_direction = "RIGHT"
snake.move()
if snake.check_collision():
game_over()
snake.reset()
food_pos = snake.generate_food()
# 绘制画面
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, RED, (food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
# 绘制蛇
for idx, segment in enumerate(snake.body):
color = GREEN if idx == 0 else WHITE
pygame.draw.rect(screen, color, (segment[0], segment[1], CELL_SIZE, CELL_SIZE))
show_score(snake.score)
pygame.display.update()
clock.tick(SPEED)
pygame.quit()
运行效果:
- 窗口尺寸:800x600
- 蛇身初始长度:1节
- 移动速度:15帧/秒
- 分数显示在窗口左上角
赶紧复制代码体验自己实现的经典游戏吧!后续可以基于这个基础版本进行更多个性化修改和功能扩展。