【问题标题】:Timer in Python for a Game用于游戏的 Python 计时器
【发布时间】:2025-12-04 16:20:14
【问题描述】:

这是我编写的游戏中的计时器:

def function(event):
    time.sleep(.2)
    tx2 = time.time()
    if tx2-tx1 > 0.7:
        #do the repetitive stuff here
    return function(1)

tx1 = time.time()

thread.start_new_thread(function,(1,))

有没有更好的方法来写这个? 对我来说,调用递归函数和新线程似乎有点脏...... 而且它会在一段时间后崩溃......

【问题讨论】:

  • 您是否尝试实现延迟计时器?在这个例子中,一旦时间超过 0.7,它会不断地运行你重复的代码,直到你以某种方式再次触及 tx1 值,这需要保护,因为它的共享内存
  • @jdi 只是一个计时器,在 tot 毫秒后执行重复功能

标签: python timer


【解决方案1】:

您当前的示例遇到了递归限制的问题,因为它以递归方式调用自身。堆栈大小继续增长,直到达到默认的 1000,很可能。请参阅这个修改后的示例:

import time
import inspect
import thread

tx1 = time.time()

def loop(event):
    print "Stack size: %d" % len(inspect.stack())
    tx2 = time.time()
    if tx2-tx1 > 0.7:
            print "Running code."
    return loop(1)

thread.start_new_thread(loop, (1,))   
time.sleep(60)

## OUTPUT ##
Stack size: 1
Running code.
Stack size: 2
Running code.
...
Stack size: 999
Running code.
Exception RuntimeError: 'maximum recursion depth exceeded in ...

使用自定义 Thread 类可能是最简单的方法,该类可以一直运行,直到您告诉它停止为止。这样堆栈大小就不会继续增长。它只是循环并调用您的处理程序函数。 这是一个完整的工作示例:

import time
from threading import Thread

class IntervalTimer(Thread): 

def __init__(self, secs, func, args=(), kwargs={}):
    super(IntervalTimer, self).__init__(target=func, args=args, kwargs=kwargs)

    self.__interval = secs
    self.__func = func
    self.__args = args
    self.__kwargs = kwargs
    self.__exiting = False

def run(self):
    while not self.__exiting:
        time.sleep(self.__interval)
        self.__func(*self.__args, **self.__kwargs)

def cancel(self):
    self.__exiting = True


def test(val):
    print val

if __name__ == "__main__":
    t = IntervalTimer(2, test, args=("Hi",))
    t.start()
    time.sleep(10)
    t.cancel()

【讨论】:

  • 它不起作用,我尝试使用你的语法......它不会每 0.2 秒刷新一次画布,它只执行一次......
  • @Pella86:我已经修改了我的答案以解决这个问题,并提供了有关问题的更多详细信息。