forked from wesleywerner/mvc-game-design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventmanager.py
110 lines (84 loc) · 2.74 KB
/
eventmanager.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
class Event(object):
"""
A superclass for any events that might be generated by an
object and sent to the EventManager.
"""
def __init__(self):
self.name = "Generic event"
def __str__(self):
return self.name
class QuitEvent(Event):
"""
Quit event.
"""
def __init__ (self):
self.name = "Quit event"
class TickEvent(Event):
"""
Tick event.
"""
def __init__ (self):
self.name = "Tick event"
class InputEvent(Event):
"""
Keyboard or mouse input event.
"""
def __init__(self, unicodechar, clickpos):
self.name = "Input event"
self.char = unicodechar
self.clickpos = clickpos
def __str__(self):
return '%s, char=%s, clickpos=%s' % (self.name, self.char, self.clickpos)
class InitializeEvent(Event):
"""
Tells all listeners to initialize themselves.
This includes loading libraries and resources.
Avoid initializing such things within listener __init__ calls
to minimize snafus (if some rely on others being yet created.)
"""
def __init__ (self):
self.name = "Initialize event"
class StateChangeEvent(Event):
"""
Change the model state machine.
Given a None state will pop() instead of push.
"""
def __init__(self, state):
self.name = "State change event"
self.state = state
def __str__(self):
if self.state:
return '%s pushed %s' % (self.name, self.state)
else:
return '%s popped' % (self.name, )
class EventManager(object):
"""
We coordinate communication between the Model, View, and Controller.
"""
def __init__(self):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
def RegisterListener(self, listener):
"""
Adds a listener to our spam list.
It will receive Post()ed events through it's notify(event) call.
"""
self.listeners[listener] = 1
def UnregisterListener(self, listener):
"""
Remove a listener from our spam list.
This is implemented but hardly used.
Our weak ref spam list will auto remove any listeners who stop existing.
"""
if listener in self.listeners.keys():
del self.listeners[listener]
def Post(self, event):
"""
Post a new event to the message queue.
It will be broadcast to all listeners.
"""
if not isinstance(event, TickEvent):
# print the event (unless it is TickEvent)
print(str(event))
for listener in self.listeners.keys():
listener.notify(event)