请写一段python贪吃蛇代码
时间: 2023-02-24 12:20:45 浏览: 108
好的,这是一段基于python的简单的贪吃蛇游戏代码:
```
import turtle
import time
# 设置窗口的大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪吃蛇游戏")
# 创建一个Turtle对象
snake = turtle.Turtle()
snake.shape("square")
snake.color("red")
snake.speed(2)
# 设置食物的坐标
food = turtle.Turtle()
food.shape("circle")
food.color("yellow")
food.speed(0)
food.goto(0,100)
# 设置方向变量
direction = "stop"
# 定义函数处理移动
def move_up():
global direction
direction = "up"
def move_down():
global direction
direction = "down"
def move_left():
global direction
direction = "left"
def move_right():
global direction
direction = "right"
# 绑定键盘事件
turtle.listen()
turtle.onkeypress(move_up, "Up")
turtle.onkeypress(move_down, "Down")
turtle.onkeypress(move_left, "Left")
turtle.onkeypress(move_right, "Right")
# 主游戏循环
while True:
if direction == "up":
snake.sety(snake.ycor() + 20)
if direction == "down":
snake.sety(snake.ycor() - 20)
if direction == "left":
snake.setx(snake.xcor() - 20)
if direction == "right":
snake.setx(snake.xcor() + 20)
# 判断是否吃到食物
if snake.distance(food) < 20:
food.goto(0,0)
time.sleep(0.1)
```
希望这段代码能帮到你。
阅读全文