From 10966c2b64a9842f30d3372fdea2afccbe7edc87 Mon Sep 17 00:00:00 2001 From: Simon Cross Date: Sun, 4 Sep 2016 16:30:49 +0200 Subject: [PATCH] Add events. --- tabakrolletjie/engine.py | 10 +++++++--- tabakrolletjie/events.py | 29 +++++++++++++++++++++++++++++ tabakrolletjie/scenes/menu.py | 3 ++- 3 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 tabakrolletjie/events.py diff --git a/tabakrolletjie/engine.py b/tabakrolletjie/engine.py index 8ee5fc9..4aac2e8 100644 --- a/tabakrolletjie/engine.py +++ b/tabakrolletjie/engine.py @@ -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 index 0000000..64ae475 --- /dev/null +++ b/tabakrolletjie/events.py @@ -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'} diff --git a/tabakrolletjie/scenes/menu.py b/tabakrolletjie/scenes/menu.py index ca9e9b5..1569d30 100644 --- a/tabakrolletjie/scenes/menu.py +++ b/tabakrolletjie/scenes/menu.py @@ -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() -- 2.34.1