From: Simon Cross Date: Sun, 4 Sep 2016 14:30:49 +0000 (+0200) Subject: Add events. X-Git-Tag: tabakrolletjie-v1.0.0~265 X-Git-Url: https://git.ctpug.org.za/?a=commitdiff_plain;h=10966c2b64a9842f30d3372fdea2afccbe7edc87;p=tabakrolletjie.git Add events. --- 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()