[英]Python turtle wn.ontimer in an if statement
I have Turtle commands in my code as you see below. 如下所示,我的代码中包含Turtle命令。 I would like to put a timer on these commands inside an if statement.
我想在if语句中的这些命令上放置一个计时器。 My current code just works like so:
我当前的代码如下所示:
'# WHEN USER PRESSES SPACE, LIGHT TURNS GREEN '#用户按下空格时,指示灯变为绿色
'# WHEN LIGHT IS GREEN ARROW MOVES 50 PIXELS '#当光是绿色箭头移动50像素时
player1.pendown()
player1.forward(50)
player2.pendown()
player2.forward(50)
The arrow really only moves once every time I press the space key. 每次按空格键,箭头实际上只移动一次。 I would like to turn that into a timer so the arrow would move every 60 milliseconds until the user presses the space key again.
我想将其变成一个计时器,以便箭头每60毫秒移动一次,直到用户再次按下空格键。
I tried using an wn.ontimer but I keep on messing up something. 我尝试使用wn.ontimer,但我一直在弄乱一些东西。 Below is how the code looks now:
下面是代码的外观:
def advance_state_machine():
global state_num
if state_num == 0:
tess.forward(70)
tess.fillcolor("red")
state_num = 1
else:
tess.back(70)
tess.fillcolor("green")
state_num = 0
player1.pendown()
player1.forward(50)
player2.pendown()
player2.forward(50)
wn.onkey(advance_state_machine, "space")
wn.listen()
wn.mainloop()
Your description of your problem is inconsistent and your code is out of sync with your description. 您对问题的描述不一致,并且代码与您的描述不同步。 Here's what I believe you stated you wanted your code to do:
这是我认为您说过要执行的代码:
The turtle moves forward 1 step every 60 milliseconds and alternates between red/forward and green/backward whenever the space bar is pressed. 每60毫秒乌龟向前移动1步,每当按下空格键时,乌龟就会在红色/向前和绿色/向后交替。
I believe this code implements that, a key event is used to detect the space bar and a timer event is used to keep the turtle in motion: 我相信这段代码实现了,一个关键事件用于检测空格键,而一个计时器事件则用于使乌龟运动:
from turtle import Turtle, Screen, mainloop
def advance_state_machine():
global state_num
wn.onkey(None, 'space') # avoid overlapping events
if state_num > 0:
tess.fillcolor('green')
else:
tess.fillcolor('red')
state_num = -state_num
wn.onkey(advance_state_machine, 'space')
def advance_tess():
tess.forward(state_num)
wn.ontimer(advance_tess, 60)
wn = Screen()
tess = Turtle()
tess.fillcolor('red')
state_num = 1
wn.onkey(advance_state_machine, 'space')
wn.ontimer(advance_tess, 60)
wn.listen()
mainloop()
Make sure to click on the window to make it active before trying the space bar. 在尝试使用空格键之前,请确保单击该窗口使其处于活动状态。 Left unattended, the turtle will eventually go off screen.
如果无人看管,乌龟最终将离开屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.