import turtle
import time
delay = 0.1
ms = turtle.Screen()
ms.title("hungry snake Game by @Rafa")
ms.bgcolor("green")
ms.setup(width=600, height=600)
ms.tracer(0)
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
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)
# main game loop
while True:
ms.update()
move()
time.sleep(delay)
//Here is where am having trouble with the code?
ms.mainloop()
这里真正的错误是在事件驱动的环境(如turtle)中使用while True:
和sleep()
。我们可以用乌龟time.sleep()
方法替换无限循环和ontimer()
:
from turtle import Screen, Turtle
DELAY = 100 # milliseconds
def move():
if direction == 'up':
y = turtle.ycor()
turtle.sety(y + 20)
elif direction == 'down':
y = turtle.ycor()
turtle.sety(y - 20)
elif direction == 'left':
x = turtle.xcor()
turtle.setx(x - 20)
elif direction == 'right':
x = turtle.xcor()
turtle.setx(x + 20)
screen.update()
screen.ontimer(move, DELAY)
def up():
global direction
direction = 'up'
def down():
global direction
direction = 'down'
def left():
global direction
direction = 'left'
def right():
global direction
direction = 'right'
screen = Screen()
screen.title("Hungry Snake Game")
screen.bgcolor('green')
screen.setup(width=600, height=600)
screen.tracer(0)
turtle = Turtle()
turtle.shape('square')
turtle.speed('fastest')
turtle.penup()
direction = 'stop'
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
# main game loop
move()
screen.mainloop()