书写一个贪吃蛇游戏程序
时间: 2023-06-02 10:06:29 浏览: 53
好的,我可以帮您写一个贪吃蛇游戏程序。以下是一份 Python 代码示例:
```python
import turtle
import random
# 设置游戏界面
win = turtle.Screen()
win.title("贪吃蛇")
win.bgcolor("black")
win.setup(width=600, height=600)
# 创建蛇头和食物
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
# 初始化蛇的位置和长度
head.goto(0, 0)
head.direction = "stop"
segments = []
# 定义蛇的移动函数
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
elif head.direction == "down":
y = head.ycor()
head.sety(y - 20)
elif head.direction == "left":
x = head.xcor()
head.setx(x - 20)
elif head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# 定义蛇头改变方向的函数
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
# 监听键盘事件
win.listen()
win.onkeypress(go_up, "Up")
win.onkeypress(go_down, "Down")
win.onkeypress(go_left, "Left")
win.onkeypress(go_right, "Right")
# 游戏循环
while True:
win.update()
# 判断蛇头是否与食物相遇
if head.distance(food) < 20:
x = random.randint(-280, 280)
y = random.randint(-280, 280)
food.goto(x, y)
# 创建新的身体段并加入蛇的身体列表中
segment = turtle.Turtle()
segment.shape("square")
segment.color("grey")
segment.penup()
segments.append(segment)
# 将蛇的身体段依次移动
for i in range(len(segments)-1, 0, -1):
x = segments[i-1].xcor()
y = segments[i-1].ycor()
segments[i].goto(x, y)
# 将第一个身体段移到蛇头的位置
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
# 移动蛇头
move()
# 判断蛇头是否与边界相撞
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
break
# 判断蛇头是否与身体相撞
for segment in segments:
if segment.distance(head) < 20:
break
# 游戏结束
head.color("red")
turtle.penup()
turtle.goto(0, 0)
turtle.write("GAME OVER", align="center", font=("Courier", 24, "bold"))
turtle.hideturtle()
win.mainloop()
```
这是一个简单的贪吃蛇游戏程序,您可以根据需要进行修改优化。