在允许输入的同时无限期地移动Python海龟
我刚刚开始使用Turtle开发Snake的一个版本,我遇到了一个问题。我希望蛇无限期地移动,但也允许用户用键盘移动蛇。我让蛇从用户输入移动,但我不知道如何让蛇在没有输入的情况下保持同一方向移动,同时防止它忽略用户输入:在允许输入的同时无限期地移动Python海龟,python,turtle-graphics,Python,Turtle Graphics,我刚刚开始使用Turtle开发Snake的一个版本,我遇到了一个问题。我希望蛇无限期地移动,但也允许用户用键盘移动蛇。我让蛇从用户输入移动,但我不知道如何让蛇在没有输入的情况下保持同一方向移动,同时防止它忽略用户输入: while True: win.onkey(up,"Up") win.onkey(right,"Right") win.onkey(down,"Down") win.onkey(left,"Left") win.listen() #moves the snak
while True:
win.onkey(up,"Up")
win.onkey(right,"Right")
win.onkey(down,"Down")
win.onkey(left,"Left")
win.listen()
#moves the snake one unit in the same direction it is currently facing
movesnake()
from turtle import Screen, Turtle
def right():
snake.setheading(0)
def up():
snake.setheading(90)
def left():
snake.setheading(180)
def down():
snake.setheading(270)
def movesnake():
snake.forward(1)
screen.ontimer(movesnake, 100)
snake = Turtle("turtle")
screen = Screen()
screen.onkey(right, "Right")
screen.onkey(up, "Up")
screen.onkey(left, "Left")
screen.onkey(down, "Down")
screen.listen()
movesnake()
screen.mainloop()
我对海龟还不熟悉,这是我对如何解决这个问题的猜测——这显然是行不通的。任何帮助都将不胜感激。我意识到Pygame可能会让这变得更容易,但因为我已经开始使用Turtle,如果可能的话,我更愿意使用Turtle解决方案。像Turtle这样的事件驱动环境永远不应该有
,而True:
,因为它可能会阻止事件(例如键盘)。改用ontimer()
事件
通常,onkey()
和listen()
不属于循环——对于大多数程序,它们只需要调用一次
下面是一个由用户输入重定向的自主海龟的骨架示例:
while True:
win.onkey(up,"Up")
win.onkey(right,"Right")
win.onkey(down,"Down")
win.onkey(left,"Left")
win.listen()
#moves the snake one unit in the same direction it is currently facing
movesnake()
from turtle import Screen, Turtle
def right():
snake.setheading(0)
def up():
snake.setheading(90)
def left():
snake.setheading(180)
def down():
snake.setheading(270)
def movesnake():
snake.forward(1)
screen.ontimer(movesnake, 100)
snake = Turtle("turtle")
screen = Screen()
screen.onkey(right, "Right")
screen.onkey(up, "Up")
screen.onkey(left, "Left")
screen.onkey(down, "Down")
screen.listen()
movesnake()
screen.mainloop()
是的,非常感谢,效果非常好:)你知道的越多