Debian Codegraph @

docs/core/examples/threadedselect/pygamedemo.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Demonstration of how L{twisted.internet._threadedselect} might be used (this is
6 not an example showing the best way to integrate Twisted with pygame).
7 """
8 # import Twisted and install
9 from twisted.internet import _threadedselect
10
11 _threadedselect.install()
12 import pygame
13 from pygame.locals import *
14
15 from twisted.internet import reactor
16
17 try:
18 import pygame.fastevent as eventmodule
19 except ImportError:
20 import pygame.event as eventmodule
21
22
23 # You can customize this if you use your
24 # own events, but you must OBEY:
25 #
26 # USEREVENT <= TWISTEDEVENT < NUMEVENTS
27 #
28 TWISTEDEVENT = USEREVENT
29
30
31 def postTwistedEvent(func):
32 # if not using pygame.fastevent, this can explode if the queue
33 # fills up.. so that's bad. Use pygame.fastevent, in pygame CVS
34 # as of 2005-04-18.
35 eventmodule.post(eventmodule.Event(TWISTEDEVENT, iterateTwisted=func))
36
37
38 def helloWorld():
39 print("hello, world")
40 reactor.callLater(1, helloWorld)
41
42
43 reactor.callLater(1, helloWorld)
44
45
46 def twoSecondsPassed():
47 print("two seconds passed")
48
49
50 reactor.callLater(2, twoSecondsPassed)
51
52
53 def eventIterator():
54 while True:
55 yield eventmodule.wait()
56 while True:
57 event = eventmodule.poll()
58 if event.type == NOEVENT:
59 break
60 else:
61 yield event
62
63
64 def main():
65 pygame.init()
66 if hasattr(eventmodule, "init"):
67 eventmodule.init()
68 screen = pygame.display.set_mode((300, 300))
69
70 # send an event when twisted wants attention
71 reactor.interleave(postTwistedEvent)
72 # make shouldQuit a True value when it's safe to quit
73 # by appending a value to it. This ensures that
74 # Twisted gets to shut down properly.
75 shouldQuit = []
76 reactor.addSystemEventTrigger("after", "shutdown", shouldQuit.append, True)
77
78 for event in eventIterator():
79 if event.type == TWISTEDEVENT:
80 event.iterateTwisted()
81 if shouldQuit:
82 break
83 elif event.type == QUIT:
84 reactor.stop()
85 elif event.type == KEYDOWN and event.key == K_ESCAPE:
86 reactor.stop()
87
88 pygame.quit()
89
90
91 if __name__ == "__main__":
92 main()