简体   繁体   中英

Python turtle wn.ontimer in an if statement

I have Turtle commands in my code as you see below. I would like to put a timer on these commands inside an if statement. My current code just works like so:

'# WHEN USER PRESSES SPACE, LIGHT TURNS GREEN

'# WHEN LIGHT IS GREEN ARROW MOVES 50 PIXELS

        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.

I tried using an wn.ontimer but I keep on messing up something. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM