写一个贪吃蛇 python 代码
时间: 2023-03-22 11:01:16 浏览: 106
好的,下面是一个简单的贪吃蛇代码:
```python
import turtle
import time
# 设置画布大小
turtle.setup(width=600, height=600)
# 设置画笔速度
turtle.speed(8)
# 画蛇的身体
def draw_snake(snake_list):
for x, y in snake_list:
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.circle(20)
# 设置蛇头初始位置
head_x = 0
head_y = 0
# 初始化蛇的身体
snake_list = [(head_x, head_y)]
draw_snake(snake_list)
# 设置食物的位置
food_x = 100
food_y = 100
# 画食物
turtle.penup()
turtle.goto(food_x, food_y)
turtle.pendown()
turtle.circle(20)
# 设置移动方向
direction = "right"
# 游戏循环
while True:
# 移动蛇头
if direction == "right":
head_x += 20
elif direction == "left":
head_x -= 20
elif direction == "up":
head_y += 20
elif direction == "down":
head_y -= 20
# 检查是否吃到食物
if head_x == food_x and head_y == food_y:
food_x = turtle.xcor()
food_y = turtle.ycor()
turtle.penup()
turtle.goto(food_x, food_y)
turtle.pendown()
turtle.circle(20)
else:
snake_list.pop(0)
# 在蛇头位置画一个新的圆形
snake_list.append((head_x, head_y))
draw_snake(snake_list)
# 设置方向
turtle.onkeypress(lambda: turtle.setheading(0), "Right")
turtle.onkeypress(lambda: turtle.setheading(180), "Left")
turtle.onkeypress(lambda: turtle.setheading(90), "Up")
turtle.onkeypress(lambda: turtle.setheading(270), "Down")
turtle.listen()
time.sleep(0.1)
```
希望这段代码对您有所帮助!
阅读全文