python、turtle贪吃蛇重生代码
时间: 2023-07-23 14:35:03 浏览: 88
python贪吃蛇游戏代码
5星 · 资源好评率100%
以下是Python中使用turtle库实现贪吃蛇游戏的示例代码:
```python
import turtle
import random
import time
# 设置游戏窗口
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()
head.goto(0, 0)
head.direction = "stop"
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(random.randint(-290, 290), random.randint(-290, 290))
# 定义蛇的身体列表
body = []
# 定义蛇移动的函数
def move():
# 移动蛇的身体
for i in range(len(body) - 1, 0, -1):
body[i].goto(body[i - 1].xcor(), body[i - 1].ycor())
# 移动蛇头
if head.direction == "up":
head.sety(head.ycor() + 20)
elif head.direction == "down":
head.sety(head.ycor() - 20)
elif head.direction == "left":
head.setx(head.xcor() - 20)
elif head.direction == "right":
head.setx(head.xcor() + 20)
# 检测蛇头是否与食物碰撞
if head.distance(food) < 20:
# 食物移动到随机位置
food.goto(random.randint(-290, 290), random.randint(-290, 290))
# 添加一个新的身体方块
new_body = turtle.Turtle()
new_body.shape("square")
new_body.color("green")
new_body.penup()
body.append(new_body)
# 检测蛇头是否与边界碰撞
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# 移除蛇的身体方块
for b in body:
b.goto(1000, 1000)
body.clear()
# 检测蛇头是否与身体碰撞
for b in body:
if head.distance(b) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# 移除蛇的身体方块
for b in body:
b.goto(1000, 1000)
body.clear()
# 延迟移动蛇
time.sleep(0.1)
# 循环调用移动函数
win.ontimer(move, 100)
# 定义蛇头移动的函数
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")
# 循环调用移动函数
move()
# 主循环
win.mainloop()
```
希望这个示例可以帮助你重新实现贪吃蛇游戏!
阅读全文