没有time.sleep()的Python循环延迟

时间:2012-05-31 19:55:46

标签: python loops delay

在MMO游戏客户端中,我需要创建一个循环,它将在30秒内循环30次(每秒1次)。 令我非常失望的是,我发现我不能在循环中使用time.sleep(),因为这会导致游戏在循环中冻结。

循环本身非常简单,唯一的困难是如何延迟它。

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

python库在客户端中作为.pyc文件存在于一个单独的文件夹中,我希望我可以避免弄乱它们。 你认为有任何方法可以实现这种延迟,还是死路一条?

3 个答案:

答案 0 :(得分:4)

你的游戏有一个主循环。 (是的,确实如此。)

每次进入检查状态循环时,移动玩家,重绘屏幕等,检查计时器上剩余的时间。如果已经过了至少1秒,则打印出剩余的剩余秒数"讽刺。如果已经过了至少30秒,则会触发您的操作。

答案 1 :(得分:1)

除非您愿意失去精确度,否则不能在没有阻止或线程的情况下执行此操作...

我建议像这样,但是线程是正确的方法......

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

甚至......

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

答案 2 :(得分:0)

假设循环内部的执行时间小于1秒:

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

这将使您的循环迭代时间等于1秒。

相关问题