用python turtle库写一个贪吃蛇代码
时间: 2023-05-20 22:01:48 浏览: 117
好的,以下是一个简单的贪吃蛇代码,使用了Python的turtle库:
```python
import turtle
import random
# 设置窗口大小和背景颜色
turtle.setup(500, 500)
turtle.bgcolor("black")
# 创建蛇头
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
# 创建食物
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(random.randint(-200, 200), random.randint(-200, 200))
# 定义蛇的移动函数
def move():
head.forward(20)
if head.distance(food) < 15:
food.goto(random.randint(-200, 200), random.randint(-200, 200))
# 检查是否撞墙
if head.xcor() > 250 or head.xcor() < -250 or head.ycor() > 250 or head.ycor() < -250:
print("Game Over!")
turtle.bye()
# 检查是否撞到自己
for segment in segments:
if segment.distance(head) < 20:
print("Game Over!")
turtle.bye()
# 移动蛇的身体
segments = []
segments.append(head.clone())
for i in range(len(segments) - 1, 0, -1):
x = segments[i - 1].xcor()
y = segments[i - 1].ycor()
segments[i].goto(x, y)
head.color("white")
head.shape("square")
head.stamp()
head.color("green")
# 设置定时器
turtle.ontimer(move, 100)
# 开始游戏
move()
turtle.done()
```
希望这个代码能够帮助你!
阅读全文