帮我写一个贪吃蛇游戏的代码
时间: 2023-03-15 19:55:45 浏览: 47
好的,下面是一份用 Python 编写的贪吃蛇游戏代码:
```
import turtle
import time
# 设置窗口大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪吃蛇")
# 设置画笔
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.goto(0,0)
# 设置食物
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)
# 定义贪吃蛇的移动方向
direction = "stop"
# 定义贪吃蛇的身体列表
segments = []
# 定义计分
score = 0
# 定义速度
delay = 0.1
# 定义控制方向的函数
def go_up():
global direction
direction = "up"
def go_down():
global direction
direction = "down"
def go_left():
global direction
direction = "left"
def go_right():
global direction
direction = "right"
# 绑定控制方向的键盘事件
turtle.listen()
turtle.onkeypress(go_up, "Up")
turtle.onkeypress(go_down, "Down")
turtle.onkeypress(go_left, "Left")
turtle.onkeypress(go_right, "Right")
# 游戏主循环
while True:
# 控制贪吃蛇的移动
if direction == "up":
y = pen.ycor()
pen.sety(y + 20)
if direction == "down":
y = pen.ycor()
pen.sety(y - 20)
if direction == "left":
x = pen.xcor()
pen.setx(x - 20)
if direction == "right":
x = pen.xcor()
pen.setx(x + 20)
# 检查是否吃到食物
if pen.distance(food) < 20:
x = turtle.random.randint(-290, 290)
y = turtle.random.randint(-290, 290)
food.goto(x, y)
# 增加贪吃蛇的长度
new_segment = turtle.Turtle()