From 715592c38f5bc722b6518a7c924ceea4d47a16f2 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 6 Jan 2022 11:28:03 -0500 Subject: [PATCH] Create game engine class --- engine.py | 35 +++++++++++++++++++++++++++++++++++ main.py | 21 ++++++--------------- 2 files changed, 41 insertions(+), 15 deletions(-) create mode 100644 engine.py diff --git a/engine.py b/engine.py new file mode 100644 index 0000000..9d6f9fa --- /dev/null +++ b/engine.py @@ -0,0 +1,35 @@ +from typing import Set, Iterable, Any + +from tcod.context import Context +from tcod.console import Console + +from actions import EscapeAction, MovementAction +from entity import Entity +from input_handlers import EventHandler + + +class Engine: + def __init__(self, entities: Set[Entity], event_handler: EventHandler, player: Entity): + self.entities = entities + self.event_handler = event_handler + self.player = player + + def handle_events(self, events: Iterable[Any]) -> None: + for event in events: + action = self.event_handler.dispatch(event) + + if action is None: + continue + + if isinstance(action, MovementAction): + self.player.move(dx=action.dx, dy=action.dy) + elif isinstance(action, EscapeAction): + raise SystemExit() + + def render(self, console: Console, context: Context) -> None: + for entity in self.entities: + console.print(entity.x, entity.y, entity.char, fg=entity.color) + + # Actually output to screen + context.present(console) + console.clear() diff --git a/main.py b/main.py index 766397e..e7a4b24 100755 --- a/main.py +++ b/main.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 import tcod -from actions import EscapeAction, MovementAction +from engine import Engine from entity import Entity from input_handlers import EventHandler @@ -23,6 +23,8 @@ def main() -> None: npc = Entity(int(screen_width / 2 - 5), int(screen_height / 2), "@", (255, 255, 0)) entities = {npc, player} + engine = Engine(entities, event_handler, player) + with tcod.context.new_terminal( screen_width, screen_height, @@ -32,22 +34,11 @@ def main() -> None: ) as context: root_console = tcod.Console(screen_width, screen_height, order="F") while True: - root_console.print(x=player.x, y=player.y, string=player.char, fg=player.color) + engine.render(root_console, context) - # Actually display on the screen - context.present(root_console) - root_console.clear() + events = tcod.event.wait() - for event in tcod.event.wait(): - action = event_handler.dispatch(event) - - if action is None: - continue - - if isinstance(action, MovementAction): - player.move(dx=action.dx, dy=action.dy) - elif isinstance(action, EscapeAction): - raise SystemExit() + engine.handle_events(events) if __name__ == "__main__":