Merge branch 'master' of ctpug.org.za:koperkapel
[koperkapel.git] / koperkapel / scenes / base.py
1 """ Scene utilities. """
2
3 import functools
4
5
6 def apply_events(f):
7     """ Decorator that applies events to an engine. """
8     @functools.wraps(f)
9     def wrap(self, *args, **kw):
10         events = f(self, *args, **kw)
11         self._apply_events(events)
12     return wrap
13
14
15 class Engine:
16     """ A holder for game state. """
17
18     def __init__(self, app, scene):
19         self._app = app
20         self._scene = scene
21
22     def _apply_events(self, events):
23         if not events:
24             return
25         for ev in events:
26             ev.apply(self)
27
28     def change_scene(self, scene):
29         self._scene.exit()
30         self._scene = scene
31         self._scene.enter()
32
33     @apply_events
34     def update(self, dt):
35         return self._scene.update(dt)
36
37     def draw(self):
38         self._scene.draw(self._app.screen)
39
40     @apply_events
41     def on_mouse_down(self, pos, button):
42         return self._scene.on_mouse_down(pos, button)
43
44     @apply_events
45     def on_mouse_up(self, pos, button):
46         return self._scene.on_mouse_up(pos, button)
47
48     @apply_events
49     def on_key_down(self, key, mod, unicode):
50         return self._scene.on_key_down(key, mod, unicode)
51
52     @apply_events
53     def on_key_up(self, key, mod):
54         return self._scene.on_key_up(key, mod)
55
56     @apply_events
57     def on_music_end(self):
58         return self._scene.on_music_end()
59
60
61 class Event:
62     """ Base class for events. """
63
64     ENGINE_METHOD = "unknown_event"
65
66     def __init__(self, *args, **kw):
67         self._args = args
68         self._kw = kw
69
70     def apply(self, engine):
71         getattr(engine, self.ENGINE_METHOD)(*self._args, **self._kw)
72
73
74 class ChangeSceneEvent(Event):
75     """ Change to a new scene. """
76
77     ENGINE_METHOD = "change_scene"
78
79
80 class Scene:
81     """ Base class for scenes. """
82
83     def enter(self):
84         pass
85
86     def exit(self):
87         pass
88
89     def update(self, dt):
90         pass
91
92     def draw(self, screen):
93         pass
94
95     def on_mouse_down(self, pos, button):
96         pass
97
98     def on_mouse_up(self, pos, button):
99         pass
100
101     def on_key_down(self, key, mod, unicode):
102         pass
103
104     def on_key_up(self, key, mod):
105         pass
106
107     def on_music_end(self):
108         pass