Mercurial > fife-parpg
comparison engine/extensions/timer.py @ 165:fbc55c6f57cf
(Convenient) Timers.
author | phoku@33b003aa-7bff-0310-803a-e67f0ece8222 |
---|---|
date | Wed, 15 Oct 2008 18:04:52 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
164:5b04a7d3ded6 | 165:fbc55c6f57cf |
---|---|
1 import fife | |
2 | |
3 """ | |
4 Convenient timers | |
5 ================= | |
6 | |
7 Usage:: | |
8 import timer | |
9 timer.init( my_fife_engine.getTimeManager() ) | |
10 def spam(): | |
11 print "SPAM SPAM ", | |
12 return "More spam?" # a string is a true value, so it's repeated. | |
13 repeater = timer.repeatCall(500,spam) | |
14 def stop_spam(): | |
15 repeater.stop() | |
16 print "BACON EGGS AND SPAM" | |
17 timer.delayCall(50000,stop_spam) | |
18 | |
19 """ | |
20 | |
21 | |
22 _manager = None | |
23 _alltimers = {} | |
24 | |
25 def init(timemanager): | |
26 """ | |
27 Initialize timers. | |
28 | |
29 @param timemanager: A L{fife.TimeManager} as retuned by L{fife.Engine.getTimeManager}. | |
30 """ | |
31 global _manager | |
32 _manager = timemanager | |
33 | |
34 class Timer(fife.TimeEvent): | |
35 def __init__(self,delay=0,callback=None): | |
36 super(Timer,self).__init__(0) | |
37 self.is_registered = False | |
38 self.callback = callback | |
39 self.setPeriod(delay) | |
40 | |
41 def start(self): | |
42 if self.is_registered: | |
43 return | |
44 self.is_registered = True | |
45 global _alltimers | |
46 _alltimers[self]=1 | |
47 | |
48 _manager.registerEvent(self) | |
49 | |
50 def stop(self): | |
51 if not self.is_registered: | |
52 return | |
53 self.is_registered = False | |
54 global _alltimers | |
55 del _alltimers[self] | |
56 | |
57 _manager.unregisterEvent(self) | |
58 | |
59 def updateEvent(self,delta): | |
60 if callable(self.callback): | |
61 self.callback() | |
62 | |
63 def delayCall(delay,callback): | |
64 """ | |
65 Delay a function call by a number of milliseconds. | |
66 | |
67 @param delay Delay in milliseconds. | |
68 @param callback The function to call. | |
69 | |
70 @return The timer. | |
71 """ | |
72 timer = Timer(delay) | |
73 def real_callback(): | |
74 timer.stop() | |
75 callback() | |
76 timer.callback = real_callback | |
77 timer.start() | |
78 return timer | |
79 | |
80 from traceback import print_exc | |
81 def repeatCall(period,callback): | |
82 """ | |
83 Repeat a function call. | |
84 | |
85 @param period Period between calls in milliseconds. | |
86 @param callback The function to call. | |
87 | |
88 @return The timer. | |
89 | |
90 The call is repeated until the callback returns a False | |
91 value (i.e. None) or the timer is stopped. | |
92 """ | |
93 timer = Timer(period) | |
94 def real_callback(): | |
95 try: | |
96 if not callback(): | |
97 timer.stop() | |
98 except Exception: | |
99 print_exc() | |
100 timer.stop() | |
101 | |
102 timer.callback = real_callback | |
103 timer.start() | |
104 return timer | |
105 | |
106 __all__ = [init,Timer,delayCall,repeatCall] | |
107 |