给我一个贪吃蛇的Python代码
时间: 2023-03-12 09:58:23 浏览: 78
python贪吃蛇完整的源代码资料.zip
当然可以,以下是一个基本的贪吃蛇游戏的 Python 代码:
```
import turtle
import time
import random
delay = 0.1
# 设置窗口
win = turtle.Screen()
win.title("贪吃蛇")
win.bgcolor("green")
win.setup(width=600, height=600)
# 创建蛇头
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 创建食物
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
# 蛇移动的函数
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 == "right":
x = head.xcor()
head.setx(x + 20)
if head.direction == "left":
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_right():
if head.direction != "left":
head.direction = "right"
def go_left():
if head.direction != "right":
head.direction = "left"
# 设置键盘监听
win.listen()
win.onkeypress(go_up, "Up")
win.onkeypress(go_down, "Down")
win.onkeypress(go_right, "Right")
win.onkeypress(go_left, "Left")
# 游戏循环
while True:
win.update()
# 判断蛇头和食物是否接触
if head.distance(food) < 20:
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# 蛇的身体部分跟随蛇头移动
for index in range(len(body)-1, 0, -1):
x = body[index-1].xcor()
y = body[index-1].ycor()
body[index].goto(x, y)
if len(body) > 0:
x = head.xcor()
y = head.ycor()
body[0].goto(x, y)
move()
# 判断蛇头是否撞墙或自己
for b in body:
if b.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# 清空身体部分
for b in body:
b.goto(1000, 1000)
# 清空身体列表
body.clear()
# 添加身体部分
if len(body) < 1:
new_body = turtle.Turtle()
new_body.speed(0)
new_body.shape("square")
new_body.color("grey")
new_body.penup()
body.append(new_body)
time.sleep(delay)
# 关闭窗口
win.mainloop()
```
注意:这只是一个基本的贪
阅读全文