Python小游戏
一、游戏核心逻辑
通过方向键控制小蛇移动,吃掉随机生成的食物后身体变长,撞到边界或自己的身体则游戏结束,实时显示得分。
二、前置准备
- 安装 Pygame 库(终端执行):
bash
运行
pip install pygame
- 环境要求:Python 3.7 及以上版本,Windows/macOS/Linux 均兼容。
三、完整可运行代码
python
运行
import pygame
import random
import sys
# 初始化Pygame
pygame.init()
# 游戏参数设置(新手可直接修改数值调整难度)
WIDTH, HEIGHT = 800, 600 # 窗口尺寸
BLOCK_SIZE = 20 # 蛇和食物的方块大小
SPEED = 10 # 移动速度
# 颜色定义(RGB格式)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0) # 食物颜色
GREEN = (0, 255, 0) # 蛇身颜色
BLUE = (0, 0, 255) # 蛇头颜色
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python贪吃蛇小游戏")
# 时钟(控制帧率)
clock = pygame.time.Clock()
# 字体(显示得分)
font = pygame.font.SysFont(None, 55)
# 显示得分函数
def show_score(score):
text = font.render(f"得分: {score}", True, WHITE)
screen.blit(text, [10, 10])
# 绘制蛇的函数
def draw_snake(snake_list):
# 绘制蛇头(蓝色)
pygame.draw.rect(screen, BLUE, [snake_list[0][0], snake_list[0][1], BLOCK_SIZE, BLOCK_SIZE])
# 绘制蛇身(绿色)
for x, y in snake_list[1:]:
pygame.draw.rect(screen, GREEN, [x, y, BLOCK_SIZE, BLOCK_SIZE])
# 游戏结束提示函数
def game_over():
text = font.render("游戏结束!按Q退出/按C重新开始", True, RED)
screen.blit(text, [WIDTH//6, HEIGHT//2])
pygame.display.update()
# 主游戏函数
def main_game():
game_over_flag = False
game_close = False
# 蛇头初始位置
x, y = WIDTH//2, HEIGHT//2
# 移动偏移量
x_change, y_change = 0, 0
# 蛇身列表(存储每个方块的坐标)
snake_list = []
snake_length = 1
# 食物随机位置
food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
while not game_over_flag:
# 游戏结束后的操作
while game_close:
screen.fill(BLACK)
game_over()
show_score(snake_length - 1)
pygame.display.update()
# 监听按键(退出/重新开始)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q: # 按Q退出
game_over_flag = True
game_close = False
if event.key == pygame.K_c: # 按C重新开始
main_game()
if event.type == pygame.QUIT: # 点击关闭窗口
game_over_flag = True
game_close = False
# 监听游戏中按键(控制方向)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and x_change == 0: # 左移(避免反向)
x_change = -BLOCK_SIZE
y_change = 0
elif event.key == pygame.K_RIGHT and x_change == 0: # 右移
x_change = BLOCK_SIZE
y_change = 0
elif event.key == pygame.K_UP and y_change == 0: # 上移
y_change = -BLOCK_SIZE
x_change = 0
elif event.key == pygame.K_DOWN and y_change == 0: # 下移
y_change = BLOCK_SIZE
x_change = 0
# 边界检测(撞墙游戏结束)
if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
game_close = True
# 更新蛇头位置
x += x_change
y += y_change
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
# 更新蛇身
snake_head = [x, y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 撞自己身体检测
for segment in snake_list[:-1]:
if segment == snake_head:
game_close = True
# 绘制蛇和得分
draw_snake(snake_list)
show_score(snake_length - 1)
# 刷新屏幕
pygame.display.update()
# 吃到食物逻辑
if x == food_x and y == food_y:
# 重新生成食物
food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
snake_length += 1 # 蛇身变长
# 控制游戏帧率
clock.tick(SPEED)
# 退出游戏
pygame.quit()
sys.exit()
# 启动游戏
if __name__ == "__main__":
main_game()
四、代码关键部分解释
- Pygame 核心初始化:
pygame.init():初始化 Pygame 所有模块,是使用 Pygame 的第一步;pygame.display.set_mode():创建游戏窗口,指定宽高;clock.tick(SPEED):控制游戏帧率,避免蛇移动过快。
- 蛇的移动逻辑:
- 通过
x_change/y_change控制方向偏移,每次移动一个方块大小; - 限制反向移动(比如向左走时不能直接向右),符合贪吃蛇常规规则。
- 通过
- 碰撞检测:
- 边界检测:蛇头坐标超出窗口范围则游戏结束;
- 自撞检测:遍历蛇身列表,若蛇头与身体重合则游戏结束。
- 食物生成与得分:
- 食物坐标按方块大小取整,确保和蛇身对齐;
- 吃到食物后蛇身长度 + 1,得分同步增加。
五、运行步骤
- 打开 Python 编辑器(PyCharm/VS Code/IDLE 均可);
- 新建.py 文件,复制上述代码粘贴;
- 终端执行
pip install pygame安装依赖; - 运行代码,用方向键控制蛇移动,吃到红色食物得分,撞墙 / 撞自己则游戏结束(按 C 重玩,按 Q 退出)。
六、新手扩展方向
- 调整难度:修改
SPEED数值(越大越快)、BLOCK_SIZE(越小越难); - 增加音效:添加吃食物、游戏结束的音效(Pygame.mixer 模块);
- 自定义皮肤:修改蛇头 / 蛇身 / 食物的颜色;
- 最高分记录:将最高分保存到 txt 文件,每次游戏结束对比更新。
总结
- 这款贪吃蛇游戏核心用到 Python 的 Pygame 库、列表(存储蛇身)、循环(游戏主循环)、条件判断(碰撞检测),是新手练手的经典案例;
- 代码结构清晰,分函数封装功能(显示得分、绘制蛇、游戏结束提示),符合 Python 编程规范;
- 运行后通过键盘交互,逻辑贴近经典贪吃蛇,新手能快速理解 “移动 - 碰撞 - 得分” 的核心流程。

浙公网安备 33010602011771号