简体   繁体   中英

Python loop delay without time.sleep()

In an MMO game client, I need to create a loop that will loop 30 times in 30 seconds (1 time every second). To my greatest disappointment, I discovered that I can not use time.sleep() inside the loop because that causes the game to freeze during the loop.

The loop itself is pretty simple and the only difficulty is how to delay it.

limit = 31
while limit > 0 :
  print "%s seconds remaining" % (limit)
  limit = limit -1

The python libs exist in the client as .pyc files in a separate folder and I'm hoping that I can avoid messing with them. Do you think that there is any way to accomplish this delay or is it a dead end?

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 can't do it without blocking or threading unless you are willing to lose precision...

I'd 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 won't 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 won't 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

Supposing that the execution time of what's inside of the loop is less than 1 second:

limit = 0
while limit < 30 :
    time_a = time.time()
    """ Your code here """
    time_spent = time.time() - time_a
    if time_spent < 1:
        time.sleep(1 - time_spent)
    print "%s seconds remaining" % (limit)
    limit = limit -1

This will make your loop iteration time equal to 1 second.

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