当前位置: 代码网 > it编程>前端脚本>Python > Python版贪吃蛇保姆级教程(附完整代码有详细注释)

Python版贪吃蛇保姆级教程(附完整代码有详细注释)

2025年06月06日 Python 我要评论
python版贪吃蛇(最后附上完整代码并有详细注释):从零开始用pygame实现经典游戏一、前言:童年经典游戏重生贪吃蛇作为一款经典游戏,承载着无数人的童年回忆。今天我们将用python+pygame

python版贪吃蛇(最后附上完整代码并有详细注释):从零开始用pygame实现经典游戏

一、前言:童年经典游戏重生

贪吃蛇作为一款经典游戏,承载着无数人的童年回忆。今天我们将用python+pygame从零开始实现这个经典游戏!通过本教程,你不仅能掌握游戏开发的基本流程,还能学习到实用的编程技巧。先来看看最终效果:

二、开发准备

环境要求

  • python 3.9

  • pygame==2.6.1库(pip install pygame==2.6.1)

三、核心代码解析

3.1 游戏初始化

# 初始化pygame引擎
pygame.init()

# 创建游戏窗口
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("贪吃蛇大作战")

3.2 游戏常量配置

window_width = 800   # 窗口宽度
window_height = 600  # 窗口高度
cell_size = 20       # 蛇身和食物的单位尺寸
colors = {           # 颜色字典
    "black": (0,0,0),
    "white": (255,255,255),
    "red": (255,0,0),
    # ...其他颜色
}

3.3 蛇的移动控制

# 方向向量控制:通过元组存储方向
current_dir = (1, 0)  # 初始向右

# 键盘事件处理(防止180度转向)
if event.key == pygame.k_up:
    new_dir = (0, -1)
# 判断新方向是否合法(非相反方向)
if (current_dir[0] + new_dir[0] != 0) or ...:
    current_dir = new_dir

四、关键技术实现

4.1 蛇身绘制技巧

# 渐变颜色区分头身
for i, (x, y) in enumerate(snake):
    color = colors["snake_head"] if i==0 else colors["snake_body"]
    # 圆角矩形提升美观度
    pygame.draw.rect(screen, color, (x,y,cell_size-1,cell_size-1), border_radius=4)

4.2 智能食物生成

def generate_food():
    while true:
        # 随机生成坐标
        x = random.randint(0, (width-cell_size)//cell_size) * cell_size
        y = ... 
        # 确保不在蛇身上
        if (x,y) not in snake:
            return (x,y)

4.3 碰撞检测系统

# 边界检测
new_head[0] < 0 or new_head[0] >= width...

# 自碰检测
new_head in snake

# 食物碰撞检测
new_head == food_pos

五、特色功能实现

5.1 速度切换系统

# 按住方向键加速
accelerate = any(keys[k] for k in (pygame.k_up, ...))
# 动态调整帧率
clock().tick(accelerate_fps if accelerate else base_fps)

5.2 高分记录系统

def load_highscore():
    try:
        with open('highscore.txt') as f:
            return int(f.read())
    except:
        return 0

def save_highscore():
    with open('highscore.txt', 'w') as f:
        f.write(str(high_score))

六、游戏逻辑流程图

graph td
    a[游戏初始化] --> b[主循环]
    b --> c{事件处理}
    c -->|按键| d[更新方向]
    c -->|退出| e[结束游戏]
    b --> f[移动蛇头]
    f --> g{碰撞检测}
    g -->|碰墙/自身| h[游戏结束]
    g -->|吃到食物| i[增长蛇身]
    g -->|正常移动| j[更新位置]
    b --> k[重绘画面]

扩展方向

  • 增加不同难度级别

  • 添加多种特殊食物(加速、减速等)

  • 实现多人对战模式

  • 加入背景音乐和音效

七、总结

通过本教程,我们完整实现了:

  • 游戏窗口创建与绘制

  • 蛇的移动与控制逻辑

  • 智能食物生成系统

  • 完善的碰撞检测

  • 高分记录功能

  • 动态速度调节

八、完整代码

# -*- coding: utf-8 -*-
import pygame
import random
import sys

# 初始化pygame(必须的步骤,用于初始化所有pygame模块)
pygame.init()

# === 游戏常量配置 ===
window_width = 800  # 游戏窗口宽度(单位:像素)
window_height = 600  # 游戏窗口高度(单位:像素)
cell_size = 20  # 网格单元格大小(单位:像素)
base_fps = 5  # 基础游戏帧率(控制蛇的正常移动速度)
accelerate_fps = 14  # 加速时的游戏帧率

# 颜色定义(rgb格式)
colors = {
    "black": (0, 0, 0),
    "white": (255, 255, 255),
    "red": (255, 0, 0),
    "green": (0, 255, 0),
    "blue": (0, 100, 200),
    "grid": (40, 40, 40),  # 网格线颜色
    "snake_head": (0, 255, 0),  # 蛇头颜色
    "snake_body": (0, 200, 0)  # 蛇身颜色
}

# === 游戏状态初始化 ===
snake = []  # 用列表存储蛇身体的坐标(每个元素是一个元组)
current_dir = (1, 0)  # 当前移动方向(使用向量表示,初始向右)
food_pos = (0, 0)  # 食物位置坐标
is_playing = true  # 游戏是否进行中的状态
score = 0  # 当前游戏分数
high_score = 0  # 历史最高分记录

# 初始化游戏窗口
screen = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇大作战")  # 窗口标题


def draw_grid():
    """绘制网格线背景,帮助玩家更好地观察位置"""
    # 绘制垂直网格线
    for x in range(0, window_width, cell_size):
        pygame.draw.line(screen, colors["grid"], (x, 0), (x, window_height))
    # 绘制水平网格线
    for y in range(0, window_height, cell_size):
        pygame.draw.line(screen, colors["grid"], (0, y), (window_width, y))


def generate_food():
    """生成食物坐标,确保不在蛇身体上"""
    while true:
        # 计算网格坐标(确保在窗口范围内)
        x = random.randint(0, (window_width - cell_size) // cell_size) * cell_size
        y = random.randint(0, (window_height - cell_size) // cell_size) * cell_size
        # 检查生成位置是否与蛇身体重叠
        if (x, y) not in snake:
            return (x, y)


def reset_game():
    """重置游戏所有状态到初始值"""
    global snake, current_dir, food_pos, is_playing, score
    snake = [(window_width // 2, window_height // 2)]  # 蛇初始位置在窗口中心
    current_dir = (1, 0)  # 初始方向向右
    food_pos = generate_food()  # 生成第一个食物
    is_playing = true  # 游戏状态设置为进行中
    score = 0  # 重置当前分数


def show_text(content, size, color, position):
    """在指定位置显示文字的工具函数"""
    font = pygame.font.sysfont('simhei', size)  # 使用黑体字
    text_surface = font.render(content, true, color)
    screen.blit(text_surface, position)


def load_highscore():
    """从文件读取历史最高分"""
    try:
        with open('highscore.txt', 'r') as f:
            return int(f.read())
    except filenotfounderror:
        return 0  # 文件不存在时返回0分


def save_highscore():
    """保存最高分到文件"""
    with open('highscore.txt', 'w') as f:
        f.write(str(high_score))


# 初始化游戏
high_score = load_highscore()
reset_game()

# === 主游戏循环 ===
while true:
    # 处理事件队列(包括按键、窗口关闭等)
    for event in pygame.event.get():
        if event.type == pygame.quit:  # 点击窗口关闭按钮
            pygame.quit()
            sys.exit()
        elif event.type == pygame.keydown:
            if event.key == pygame.k_q:  # q键退出
                pygame.quit()
                sys.exit()
            if event.key == pygame.k_r and not is_playing:  # r键重启游戏
                reset_game()
            # 方向键控制(已解决反向问题)
            if is_playing:
                new_dir = current_dir  # 默认保持当前方向
                if event.key == pygame.k_up:
                    new_dir = (0, -1)
                elif event.key == pygame.k_down:
                    new_dir = (0, 1)
                elif event.key == pygame.k_left:
                    new_dir = (-1, 0)
                elif event.key == pygame.k_right:
                    new_dir = (1, 0)
                # 禁止直接反向(只有当新方向不相反时更新)
                if (current_dir[0] + new_dir[0] != 0) or (current_dir[1] + new_dir[1] != 0):
                    current_dir = new_dir

    # 获取当前按键状态实现加速功能
    keys = pygame.key.get_pressed()
    # 检查是否有方向键被按住(使用位运算优化判断)
    accelerate = any(keys[k] for k in (pygame.k_up, pygame.k_down, pygame.k_left, pygame.k_right))

    # 游戏进行中的逻辑处理
    if is_playing:
        # 计算新蛇头位置
        head_x, head_y = snake[0]
        dir_x, dir_y = current_dir
        new_head = (head_x + dir_x * cell_size, head_y + dir_y * cell_size)

        # 碰撞检测(边界和自身)
        if (new_head in snake or
                new_head[0] < 0 or
                new_head[0] >= window_width or
                new_head[1] < 0 or
                new_head[1] >= window_height):
            is_playing = false
            # 更新最高分记录
            if score > high_score:
                high_score = score
                save_highscore()

        # 更新蛇的位置
        snake.insert(0, new_head)
        if new_head == food_pos:  # 吃到食物
            score += 10
            food_pos = generate_food()
        else:  # 没吃到食物时移除尾部
            snake.pop()

    # === 绘制游戏画面 ===
    screen.fill(colors["black"])  # 填充背景色
    draw_grid()  # 绘制网格线

    # 绘制蛇的身体(使用渐变颜色)
    for i, (x, y) in enumerate(snake):
        # 根据部位设置颜色(头部更亮)
        color = colors["snake_head"] if i == 0 else colors["snake_body"]
        # 绘制带圆角的蛇身
        pygame.draw.rect(screen, color, (x, y, cell_size - 1, cell_size - 1), border_radius=4)

    # 绘制食物(使用圆形)
    center = (food_pos[0] + cell_size // 2, food_pos[1] + cell_size // 2)
    pygame.draw.circle(screen, colors["red"], center, cell_size // 2 - 2)

    # 显示分数信息
    show_text(f"分数: {score}  最高分: {high_score}", 24, colors["white"], (10, 10))

    # 游戏结束显示提示
    if not is_playing:
        text_width = 400  # 根据文字长度估算居中位置
        show_text("游戏结束!按 r 重新开始", 48, colors["white"],
                  (window_width // 2 - text_width // 2, window_height // 2 - 30))

    # 更新画面并控制游戏速度
    pygame.display.update()
    # 根据加速状态动态调整帧率
    pygame.time.clock().tick(accelerate_fps if accelerate else base_fps)

总结 

到此这篇关于python版贪吃蛇保姆级教程的文章就介绍到这了,更多相关python贪吃蛇保姆级内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com