我正在尝试编写一个程序,通过按空格键来启动和停止乌龟。我得到了启动乌龟移动的代码,但是当我再次按下它时并没有停止它。看来只是增加了速度。这是我的编码要求和键入的代码。

创建一个具有三个功能来控制乌龟的乌龟程序。创建一个名为turnLeft的函数,当按键盘上的向右箭头时,该函数将乌龟向左旋转90度。创建一个名为turnRight的函数,当按下向右箭头时,该函数将乌龟向右旋转90度。创建一个名为move()的第三个函数,该函数在按下空格键时将乌龟向前移动,然后在再次按下空格键时将乌龟停止。

import turtle

turtle.setup(400,500)
wn = turtle.Screen()
wn.title("Tess moves in space")
wn.bgcolor("lightgreen")
tess = turtle.Turtle()

def leftTurtle():
    tess.left(90)

def rightTurtle():
    tess.right(90)

state_num = 0

def advance_state_machine():
    global state_num
    if state_num == 0:
        tess.penup()
        state_num = 1
    else:
        tess.pendown()
        tess.forward(2)
        state_num = 0
    wn.ontimer(advance_state_machine, 25)

def exitWindow():
    wn.bye()

wn.onkey(advance_state_machine, "space")
wn.onkey(exitWindow, "q")
wn.onkey(leftTurtle, "Left")
wn.onkey(rightTurtle, "Right")

wn.listen()
wn.mainloop()

最佳答案

除了一些微小的细节需要更改外,您几乎可以理解。全局变量state_numadvance_state_machine()函数中确定乌龟是否应该移动。您在转弯时获得了正确的逻辑,那么为什么不对移动/暂停应用相同的逻辑呢?

在原始代码中,您只是将每个显示的帧将全局变量值从一种状态切换到另一种状态,并使用SPACE键启动了advance_state_machine()的另一个实例,这使乌龟变得更快。乌龟变得更快,因为在每个SPACE中,开始在advance_state_machine()中实现的另一个循环与现有循环并行运行。

在下面的代码中,函数movementControl()将布尔值should_move的值更改为SPACE上的相反值,并且advance_state_machine()评估should_move允许乌龟移动或停止:

import turtle

turtle.setup(400,500)
wn = turtle.Screen()
wn.title("Tess moves in space")
wn.bgcolor("lightgreen")
tess = turtle.Turtle()

def leftTurtle():
    tess.left(90)

def rightTurtle():
    tess.right(90)

should_move = False

def movementControl():
    global should_move
    should_move = not should_move

def advance_state_machine():
    global should_move
    if should_move:
        tess.pendown()
        tess.forward(2)
    else:
        tess.penup()
    wn.ontimer(advance_state_machine, 25)

def exitWindow():
    wn.bye()

wn.onkey(movementControl, "space")
wn.onkey(exitWindow, "q")
wn.onkey(leftTurtle, "Left")
wn.onkey(rightTurtle, "Right")

wn.listen()
advance_state_machine()

wn.mainloop()




哇!!!在cdlane's的帮助下,我们在这里给出了一个非常不错的基本乌龟示例。

现在,我已经对HIS代码进行了一些修改,以简化版本,并且也摆脱了MovementControl()函数。

我个人不喜欢使用from turtle import *类型的导入语句,因为它们提供了大量“不可见”的可用方法和变量,因为您无法直接看到它们的来源,但是……这么短的代码难道不值得吗?

from turtle import *
setup(400, 500); title('Turtle moves in space')
bgcolor('lightgreen'); up()
def advance_state_machine():
    if isdown(): fd(2)
    ontimer(advance_state_machine, 25)
onkey(lambda: (pd, pu)[isdown()](), 'space')
onkey(bye, 'q')
onkey(lambda: lt(90), 'Left')
onkey(lambda: rt(90), 'Right')
listen(); advance_state_machine(); done()

关于python - 使用空格键启动和停止Python Turtle,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43591581/

10-15 12:52