如何在移动之前让乌龟完成转弯?

时间:2017-11-22 22:14:27

标签: python-3.x turtle-graphics

我一直在为一个学校项目研究WASD控制的海龟计划。我有这个故障,如果在转动钥匙后很快敲击W键,乌龟将在转弯中向前移动并在移动后完成转弯。这不是一个大问题,但这是一个我想整理出来的错误。

    from turtle import *
    Screen()
    move = Turtle()

    def forkey():
        move.forward(50)

    def backey():
        move.back(50)

    def rigkey():
        move.right(45)

    def lefkey():
        move.left(45)

    onkey(forkey, "w")
    onkey(backey, "s")
    onkey(rigkey, "d")
    onkey(lefkey, "a")

    listen()
    mainloop()

1 个答案:

答案 0 :(得分:0)

尝试在事件处理程序中禁用事件处理程序,以避免堆积事件:

from turtle import Turtle, Screen

def forkey():
    screen.onkey(None, "w")
    move.forward(50)
    screen.onkey(forkey, "w")

def backey():
    screen.onkey(None, "s")
    move.back(50)
    screen.onkey(backey, "s")

def rigkey():
    screen.onkey(None, "d")
    move.right(45)
    screen.onkey(rigkey, "d")

def lefkey():
    screen.onkey(None, "a")
    move.left(45)
    screen.onkey(lefkey, "a")

move = Turtle()

screen = Screen()

screen.onkey(forkey, "w")
screen.onkey(backey, "s")
screen.onkey(rigkey, "d")
screen.onkey(lefkey, "a")

screen.listen()
screen.mainloop()

如果这不能解决您的问题,则下一步可能是在任何事件处理程序处于活动状态时禁用所有事件处理程序。您可以使用全局变量暂时禁用它们,而不是明确地将它们全部关闭。