Add events.
authorSimon Cross <hodgestar@gmail.com>
Sun, 4 Sep 2016 14:30:49 +0000 (16:30 +0200)
committerSimon Cross <hodgestar@gmail.com>
Sun, 4 Sep 2016 14:30:49 +0000 (16:30 +0200)
tabakrolletjie/engine.py
tabakrolletjie/events.py [new file with mode: 0644]
tabakrolletjie/scenes/menu.py

index 8ee5fc96a43c5a8746c62fa653893a5d9ca34c15..4aac2e8e8bb7297ce86e317e4c8e68e5528f5212 100644 (file)
@@ -8,6 +8,7 @@ import pygame.time
 import pygame.locals as pgl
 
 from .constants import FPS
+from .events import QuitEvent, SceneChangeEvent
 
 
 class Engine(object):
@@ -20,7 +21,8 @@ class Engine(object):
         if self._scene is not None:
             self._scene.exit(self._gamestate)
         self._scene = scene
-        self._scene.enter(self._gamestate)
+        if scene is not None:
+            self._scene.enter(self._gamestate)
 
     def run(self):
         clock = pygame.time.Clock()
@@ -28,12 +30,14 @@ class Engine(object):
         while True:
             events = pygame.event.get()
             for ev in events:
-                if ev.type == pgl.QUIT:
+                if QuitEvent.matches(ev) or ev.type == pgl.QUIT:
+                    self.set_scene(None)
                     return
+                elif SceneChangeEvent.matches(ev):
+                    self.set_scene(ev.scene)
                 else:
                     self._scene.event(ev, self._gamestate)
 
             self._scene.render(self._screen, self._gamestate)
             pygame.display.flip()
-
             clock.tick(FPS)
diff --git a/tabakrolletjie/events.py b/tabakrolletjie/events.py
new file mode 100644 (file)
index 0000000..64ae475
--- /dev/null
@@ -0,0 +1,29 @@
+""" Custom events. """
+
+import pygame.event
+import pygame.locals as pgl
+
+
+class TabakEvent(object):
+    TYPE = "UNKNOWN"
+    ATTRIBUTES = set()
+
+    @classmethod
+    def post(cls, **attributes):
+        assert set(attributes.keys()) == cls.ATTRIBUTES
+        ev = pygame.event.Event(
+            pgl.USEREVENT, tabak_type=cls.TYPE, **attributes)
+        pygame.event.post(ev)
+
+    @classmethod
+    def matches(cls, ev):
+        return (ev.type == pgl.USEREVENT and ev.tabak_type == cls.TYPE)
+
+
+class QuitEvent(TabakEvent):
+    TYPE = "QUIT"
+
+
+class SceneChangeEvent(TabakEvent):
+    TYPE = "SCENE_CHANGE"
+    ATTRIBUTES = {'scene'}
index ca9e9b5b20650d85f0e882f230bcbf72544c80d2..1569d30c975b80efa01e76a89dc3979436b24812 100644 (file)
@@ -4,10 +4,11 @@ import pygame.event
 import pygame.locals as pgl
 
 from .base import BaseScene
+from ..events import QuitEvent
 
 
 class MenuScene(BaseScene):
     def event(self, ev, gamestate):
         if ev.type == pgl.KEYDOWN:
             if ev.key in (pgl.K_q, pgl.K_ESCAPE):
-                pygame.event.post(pygame.event.Event(pgl.QUIT))
+                QuitEvent.post()