From 2d073a3839db8090c56bacc979c14bb30eb80171 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Mon, 10 Jan 2022 14:22:33 -0500 Subject: [PATCH] Prevent playing after Game over, completing part 6 --- components/fighter.py | 2 ++ engine.py | 4 ++-- input_handlers.py | 33 ++++++++++++++++++++++++++++++++- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/components/fighter.py b/components/fighter.py index 59833f2..755d399 100644 --- a/components/fighter.py +++ b/components/fighter.py @@ -3,6 +3,7 @@ from __future__ import annotations from typing import TYPE_CHECKING from components.base_component import BaseComponent +from input_handlers import GameOverEventHandler from render_order import RenderOrder if TYPE_CHECKING: @@ -31,6 +32,7 @@ class Fighter(BaseComponent): def die(self) -> None: if self.engine.player is self.entity: death_message = "You died!" + self.engine.event_handler = GameOverEventHandler(self.engine) else: death_message = f"{self.entity.name} is dead!" diff --git a/engine.py b/engine.py index ef0e6e1..7d2c0b0 100644 --- a/engine.py +++ b/engine.py @@ -6,7 +6,7 @@ from tcod.context import Context from tcod.console import Console from tcod.map import compute_fov -from input_handlers import EventHandler +from input_handlers import MainGameEventHandler if TYPE_CHECKING: from entity import Actor @@ -17,7 +17,7 @@ class Engine: game_map: GameMap def __init__(self, player: Actor): - self.event_handler: EventHandler = EventHandler(self) + self.event_handler: EventHandler = MainGameEventHandler(self) self.player = player def handle_enemy_turns(self) -> None: diff --git a/input_handlers.py b/input_handlers.py index bdc924c..37e8cf0 100644 --- a/input_handlers.py +++ b/input_handlers.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Optional, TYPE_CHECKING +from typing import overload, Optional, TYPE_CHECKING import tcod.event @@ -52,6 +52,15 @@ class EventHandler(tcod.event.EventDispatch[Action]): def __init__(self, engine: Engine): self.engine = engine + @overload + def handle_events(self) -> None: + pass + + def ev_quit(self, event: tcod.event.Quit) -> Optional[Action]: + raise SystemExit() + + +class MainGameEventHandler(EventHandler): def handle_events(self) -> None: for event in tcod.event.wait(): action = self.dispatch(event) @@ -82,3 +91,25 @@ class EventHandler(tcod.event.EventDispatch[Action]): # No valid key was pressed return action + + +class GameOverEventHandler(EventHandler): + def handle_events(self) -> None: + for event in tcod.event.wait(): + action = self.dispatch(event) + + if action is None: + continue + + action.perform() + + def ev_keydown(self, event: tcod.event.KeyDown) -> Optional[Action]: + action: Optional[Action] = None + + key = event.sym + + if key == tcod.event.K_ESCAPE: + action = EscapeAction(self.engine.player) + + # No valid key was pressed + return action