写一段贪吃蛇的程序代码
时间: 2023-12-26 15:47:11 浏览: 108
这是一个用 Python 语言编写的简单的贪吃蛇游戏代码示例:
```
import turtle
import time
# 设置窗口大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪吃蛇")
# 隐藏海龟图形
turtle.hideturtle()
# 设置速度
turtle.speed(10)
# 画游戏界面的边界
turtle.pensize(5)
turtle.penup()
turtle.goto(-290, 290)
turtle.pendown()
for i in range(4):
turtle.forward(580)
turtle.right(90)
# 设置食物的位置
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
# 设置蛇头
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("green")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 设置蛇身
segments = []
# 设置方向
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# 按键处理函数
def change_direction(key):
if key == "Up":
head.direction = "up"
if key == "Down":
head.direction = "down"
if key == "Left":
head.direction = "left"
if key == "Right":
head.direction = "right"
# 监听键盘事件
turtle.listen()
turtle.onkeypress(change_direction, "Up")
turtle.onkeypress(change_direction, "Down")
turtle.onkeypress(change_direction, "Left")
turtle.onkeypress(change_direction, "Right")
# 游戏主循环
while True:
turtle.update()
time.sleep(0.1)
move()
# 判断蛇头是否吃
阅读全文