帮我写一个Python贪吃蛇的代码
时间: 2023-06-13 07:05:50 浏览: 88
我们可以使用Python的 turtle 库来写一个贪吃蛇游戏,这是一个简单的示例:import turtle# 创建一个屏幕
wn = turtle.Screen()
wn.title("贪吃蛇")
wn.bgcolor("light green")
wn.setup(width=600, height=600)
wn.tracer(0) # Turns off the screen updates# 创建一个蛇
snake = turtle.Turtle()
snake.speed(0)
snake.shape("square")
snake.color("black")
snake.penup()
snake.goto(0,0)
snake.direction = "stop"# 创建一个食物
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0,100)# 创建一个游戏循环
while True:
wn.update() # 移动蛇
if snake.direction == "up":
y = snake.ycor()
snake.sety(y + 20) if snake.direction == "down":
y = snake.ycor()
snake.sety(y - 20) if snake.direction == "left":
x = snake.xcor()
snake.setx(x - 20) if snake.direction == "right":
x = snake.xcor()
snake.setx(x + 20) # 检查边界
if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290:
snake.goto(0,0)
snake.direction = "stop" # 检查是否吃到食物
if snake.distance(food) < 20:
# 计算一个新的食物位置
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y) # 绑定键盘事件
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")delay = raw_input("Press enter to finish.")
阅读全文