2011-10-07 75 views
0

这是一个游戏编程,我里面的定时器:定时器的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,)) 

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

+0

这可能会帮助您:http://stackoverflow.com/questions/156330/get-timer-ticks-in-python – GoingTharn

+0

你们是不是要达到一个延迟计时器?在这个例子中,一旦时间超过0.7,它会不断运行你的重复代码,直到你再次触及tx1值,这将需要保护,因为它的共享内存 – jdi

+0

@jdi只是一个计时器,在tot毫秒后重复函数 – Pella86

回答

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 ... 

它可能比较容易使用,可以运行,直到你告诉它停止自定义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

+0

@ Pella86:我修改了我的答案以解决这个问题,关于这个问题的更多细节。 – jdi

+0

Thx你:D它的工作! – Pella86