简体   繁体   中英

Why does Python Turtle need WIN.update() in #Game Loop?

I've written the following #Game Loop trying to teach my students a lesson. The turtle would not move or respond to any of the functions until I added the line WIN.update(). Why would that be necessary? Other turtle #Game Loops I've created have not needed it. When does it become a requirement to help the turtle respond to both key commands and user created functions?

enter image description here

In a turtle program, the update() is only necessary if you've previously done tracer(0) , and doesn't directly affect keyboard events.

However, your program isn't assembled properly as while True: , or equivalent, defeats an event-driven environment like turtle. The addition of update() gave your program a chance to clear the event queue. What we really should use is a timed event. This is what I would have expected your program fragment to look like:

def game_loop():
    if RUNNING:
        Move()  # Move the Turtle

        Barriers()  # Barrier Check

        WIN.update()  # Only if Win.tracer(0) is in effect

        WIN.ontimer(game_loop, 100)  # Delay in milliseconds

WIN.onkey(Up, 'Up')
WIN.onky(Down, 'Down')
WIN.onkey(Left, 'Left')
WIN.onkey(Right, 'Right')
WIN.listen()

game_loop()

WIN.mainloop()

Note that onkey() and listen() do not belong in the game loop, they only need to be applied once.

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