Python loop delay without time.sleep()

Python loop delay without time.sleep()

Your game has a main loop. (Yes, it does.)

Each time through the loop when you go to check state, move the players, redraw the screen, etc., you check the time left on your timer. If at least 1 second has elapsed, you print out your seconds remaining quip. If At least 30 seconds has elapsed, you trigger whatever your action is.

You cant do it without blocking or threading unless you are willing to lose precision…

Id suggest sometime like this, but threading is the correct way to do this…

import time

counter = 31
start = time.time()
while True:
    ### Do other stuff, it wont be blocked
    time.sleep(0.1)
    print looping...

    ### When 1 sec or more has elapsed...
    if time.time() - start > 1:
        start = time.time()
        counter = counter - 1

        ### This will be updated once per second
        print %s seconds remaining % counter

        ### Countdown finished, ending loop
        if counter <= 0:
            break

or even…

import time

max = 31
start = time.time()
while True:
    ### Do other stuff, it wont be blocked
    time.sleep(0.1)
    print looping...

    ### This will be updated every loop
    remaining = max + start - time.time()
    print %s seconds remaining % int(remaining)

    ### Countdown finished, ending loop
    if remaining <= 0:
        break

Python loop delay without time.sleep()

Leave a Reply

Your email address will not be published. Required fields are marked *