freegames/snack.py
sairate 51fdda69f7 feat: 添加贪吃蛇游戏- 新增贪吃蛇游戏的 Python 代码
- 添加用于安装 freegames 库的说明到 README.md
- 创建多个 .idea配置文件以设置 IDE 项目环境
- 配置 .gitignore 文件以忽略不必要的 IDE 文件
2025-06-07 14:13:53 +08:00

83 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Snake经典街机游戏。
练习:
1. 如何让蛇变快或变慢?
2. 如何让蛇可以从一边穿越到另一边?
3. 如何让食物移动?
4. 修改为点击鼠标控制蛇移动。
"""
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):
"""改变蛇的移动方向。"""
aim.x = x
aim.y = y
def inside(head):
"""判断蛇头是否在边界内。"""
return -200 < head.x < 190 and -200 < head.y < 190
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('蛇长:', 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毫秒调用一次 move实现动画
# 初始化窗口
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()