Python游戏中的计时器
这是我编写的一个游戏里的计时器:
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,))
有没有更好的写法呢?我觉得这样写有点乱,既调用了递归函数,又用了新线程……而且过一段时间后还会崩溃……
1 个回答
3
你现在的例子遇到了递归限制的问题,因为它是通过递归的方式调用自己的。这样一来,调用的次数会越来越多,直到达到默认的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 ...
最简单的方法可能是使用一个自定义的线程类,这样它可以一直运行,直到你告诉它停止。这样一来,调用的次数就不会继续增加了。它只是不断循环,并调用你的处理函数。下面是一个完整的可运行的例子:
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()