1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 """
26 Renderer for Pygame using Twisted
27 """
28
29 import pygame
30 from pygame import time
31 from twisted.internet import reactor
32 from twisted.internet import task
33
35 """
36 A pygame game
37 """
39 self.renderer = None
40 self.running = True
41
43 """
44 Called on every frame
45 """
46 raise NotImplementedError("You must implement this in child classes.")
47
49 """
50 Called when pygame event occur
51 """
52 pass
53
55 """
56 Called just before exiting the application
57 """
58 pass
59
61 """
62 Integrates a pygame game and twisted.
63 See http://twistedmatrix.com/pipermail/twisted-python/2002-October/001884.html
64 """
65 - def __init__(self, game, verbose=False):
66 self.clock = time.Clock()
67 self.game = game
68 self.game.renderer = self
69 self.is_verbose = verbose
70 self.desired_fps = 12.0
71
72 self.check_for_events()
73 self._looping_events_check = None
74 self._setup_events_looping_call()
75 self.update()
76
78 """
79 ErrBack for the self._looping_events_check LoopingCall.
80 """
81 reason.printTraceback()
82
83 self._setup_events_looping_call()
84
86 """
87 Sets up the self._looping_events_check LoopingCall.
88 """
89 self._looping_events_check = task.LoopingCall(self.check_for_events)
90 deferred = self._looping_events_check.start(0.01, True)
91
92 deferred.addErrback(self._on_events_error)
93
95 """
96 Check for pygame events and warn the game.
97 :param events: got them using pygame.event.get()
98 """
99 events = pygame.event.get()
100 self.game.process_events(events)
101
102
104 """
105 Renders one frame sequenced using the Twisted events loop.
106 """
107 self.clock.tick()
108 self.ms = self.clock.get_rawtime()
109 framespeed = (1.0 / self.desired_fps) * 1000
110 lastspeed = self.ms
111 next = framespeed - lastspeed
112 if self.is_verbose:
113 print "FPS: %5f" % (self.clock.get_fps())
114
115 self.game.draw()
116
117 if not self.game.running:
118 self._stop()
119 else:
120 when = next / 1000.0 * 2.0
121 if when < 0:
122 when = 0
123 reactor.callLater(when, self.update)
124
126 """
127 Stops the game and quits
128 """
129 self.game.cleanup()
130 self._looping_events_check.stop()
131 reactor.stop()
132