帮我写个贪吃蛇小程序
时间: 2023-02-25 16:12:45 浏览: 90
好的,我可以为您写一个简单的贪吃蛇小程序。
这是 Python 代码:
```
import turtle
import time
wn = turtle.Screen()
wn.title("贪吃蛇")
wn.bgcolor("black")
wn.setup(width=600, height=600)
# 创建一个蛇头
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
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)
# 创建一个蛇身
segments = []
# 定义方向
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"
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)
# 键盘事件
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
# 游戏循环
while True:
wn.update()
# 检查是否碰到边界
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 segment in segments:
segment.goto(1000, 1000)
# 清空蛇身列表
segments.clear()
# 碰到食物
if head.distance(food)
阅读全文