Python turtle wn.ontimer在if语句中使用
我在代码中有一些Turtle命令,像你看到的那样。我想在这些命令里加一个定时器,放在一个if语句里面。现在我的代码是这样工作的:
'# 当用户按下空格键时,灯变成绿色
'# 当灯是绿色时,箭头移动50个像素
player1.pendown()
player1.forward(50)
player2.pendown()
player2.forward(50)
其实箭头每次我按下空格键时只移动一次。 我想把这个改成一个定时器,这样箭头就可以每60毫秒移动一次,直到用户再次按下空格键。
我试着用wn.ontimer,但总是搞错什么。下面是现在的代码样子:
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()
1 个回答
0
你描述的问题有点不一致,而且你的代码和描述也不太匹配。根据我的理解,你想要的功能是这样的:
乌龟每60毫秒向前移动一步,并且每当按下空格键时,它会在红色向前和绿色向后之间切换。
我认为下面的代码实现了这个功能,它使用键盘事件来检测空格键,同时用定时器事件来保持乌龟的运动:
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()
在尝试按空格键之前,确保先点击窗口使其变为活动状态。如果不操作,乌龟最终会跑出屏幕。