平平爱恰糖糖
平平爱恰糖糖
发布于 2025-06-14 / 498 阅读
21
0

经典贪吃蛇游戏:Python实现与扩展思考

贪吃蛇是一款深受喜爱的经典街机游戏,本文将介绍如何使用Python的turtle模块实现一个基础版本,并探讨几种可能的扩展方向。

学习目标:通过本项目,您将掌握Python游戏开发的基本概念,包括游戏循环、碰撞检测和用户输入处理。

游戏基础实现

这个贪吃蛇游戏使用了Python的turtle图形库和辅助的freegames模块来简化绘图操作。下面是核心代码解析:

温馨提示:运行此游戏前需要安装freegames模块,安装命令为:pip install freegames

初始化游戏

from random import randrange
from turtle import *
from freegames import square, vector

# 初始化食物和蛇
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)

游戏使用向量(vector)来表示位置和方向,蛇身由一个向量列表表示,食物则是单个向量。

方向控制

def change(x, y):
    """改变蛇的方向"""
    aim.x = x
    aim.y = y

通过键盘方向键控制蛇的移动方向:

listen()
onkey(lambda: change(10, 0), 'Right')
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')

游戏主逻辑

move()函数处理游戏的核心逻辑:

def move():
    """移动蛇身"""
    head = snake[-1].copy()
    head.move(aim)
    
    # 检测碰撞
    if not inside(head) or head in snake:
        square(head.x, head.y, 9, 'red')  # 碰撞显示红色
        update()
        return
    
    snake.append(head)
    
    # 吃到食物
    if head == food:
        print('Snake:', len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10
    else:
        snake.pop(0)
    
    # 重绘画面
    clear()
    for body in snake:
        square(body.x, body.y, 9, 'black')
    square(food.x, food.y, 9, 'green')
    
    update()
    ontimer(move, 100)  # 100毫秒后再次移动

扩展思考

原代码注释中提出了几个有趣的扩展方向:

1.调整蛇的移动速度

当前速度由ontimer(move, 100)中的100毫秒间隔控制。要改变速度:

  • 加快:减小这个数值(如50)

  • 减慢:增大这个数值(如200)

2. 实现边缘穿越

当前游戏在蛇碰到边界时结束。要实现"穿墙"效果,可以修改inside函数和移动逻辑:

def inside(head):
    """允许穿越边界"""
    if head.x > 190:
        head.x = -200
    elif head.x < -200:
        head.x = 190
    if head.y > 190:
        head.y = -200
    elif head.y < -200:
        head.y = 190
    return True

3. 移动食物

要实现随时间移动的食物,可以:

  1. 为食物添加移动向量

  2. 定期更新食物位置

  3. 确保食物不会出现在蛇身上

4. 鼠标控制

将键盘控制改为鼠标点击控制:

def change_click(x, y):
    """根据点击位置改变方向"""
    head = snake[-1]
    aim.x = x - head.x
    aim.y = y - head.y

onscreenclick(change_click)  # 替换原来的键盘监听

完整游戏代码

"""Snake, classic arcade game.

Exercises

1. How do you make the snake faster or slower?
2. How can you make the snake go around the edges?
3. How would you move the food?
4. Change the snake to respond to mouse clicks.
"""

from random import randrange
from turtle import *

from freegames import square, vector

food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)


def change(x, y):
    """Change snake direction."""
    aim.x = x
    aim.y = y


def inside(head):
    """Return True if head inside boundaries."""
    return -200 < head.x < 190 and -200 < head.y < 190


def move():
    """Move snake forward one segment."""
    head = snake[-1].copy()
    head.move(aim)

    if not inside(head) or head in snake:
        square(head.x, head.y, 9, 'red')
        update()
        return

    snake.append(head)

    if head == food:
        print('Snake:', len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10
    else:
        snake.pop(0)

    clear()

    for body in snake:
        square(body.x, body.y, 9, 'black')

    square(food.x, food.y, 9, 'green')
    update()
    ontimer(move, 100)


setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: change(10, 0), 'Right')
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')
move()
done()

提示:复制上面的代码到Python文件中运行即可体验游戏!

总结

这个贪吃蛇实现虽然简单,但包含了游戏开发的基本元素:状态管理、用户输入、碰撞检测和画面渲染。通过不同的扩展,可以探索游戏开发的更多可能性,是学习Python游戏编程的优秀起点。

下一步学习建议:

  • 尝试实现所有扩展功能

  • 添加计分系统

  • 为游戏添加音效

  • 探索其他Python游戏库如Pygame

    官方群聊:703681056


评论