Python turtle wn.ontimer in an if statement -


i have turtle commands in code see below. put timer on these commands inside if statement. current code works so:

'# when user presses space, light turns green

'# when light green arrow moves 50 pixels

        player1.pendown()         player1.forward(50)         player2.pendown()         player2.forward(50) 

the arrow moves once every time press space key. turn timer arrow move every 60 milliseconds until user presses space key again.

i tried using wn.ontimer keep on messing something. below how 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 problem inconsistent , code out of sync description. here's believe stated wanted code do:

the turtle moves forward 1 step every 60 milliseconds , alternates between red/forward , green/backward whenever space bar pressed.

i believe code implements that, key event used detect space bar , timer event used keep 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 click on window make active before trying space bar. left unattended, turtle go off screen.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -