From 4084d98efd715a57f97b384b5ce3c74d0b0caadc Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Thu, 12 May 2022 08:53:26 -0700 Subject: [PATCH] Clean up Action processing a little bit - Sort entities by their Euclidean distance to the hero so actions from entities near the hero are processed first - Fewer local variables for cleaner reading - Pass hero into the RegerateRoomsAction, which was causing a pylint error --- roguebasin/events.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/roguebasin/events.py b/roguebasin/events.py index a9d210c..09dfef2 100644 --- a/roguebasin/events.py +++ b/roguebasin/events.py @@ -32,18 +32,25 @@ class EventHandler(tcod.event.EventDispatch[Action]): '''Handle the given event. Transform that event into an Action via an EventHandler and perform it.''' action = self.dispatch(event) + # Unhandled event. Ignore it. if not action: + LOG.debug('Unhandled event: %s', event) return result = self.perform_action_until_done(action) - # Action failed, so do nothing further. + # Player's action failed, don't proceed with turn. if not result.success and result.done: return - # Copy the list so we only act on the entities that exist at the start of this turn - entities = list(self.engine.entities) - for ent in entities: + # Copy the list so we only act on the entities that exist at the start of this turn. Sort it by Euclidean + # distance to the Hero, so entities closer to the hero act first. + hero_position = self.engine.hero.position + entities = sorted( + self.engine.entities, + key=lambda e: e.position.euclidean_distance_to(hero_position)) + + for i, ent in enumerate(entities): if not isinstance(ent, Actor): continue @@ -62,18 +69,15 @@ class EventHandler(tcod.event.EventDispatch[Action]): LOG.debug('Performed action success=%s done=%s alternate=%s', result.success, result.done, result.alternate) while not result.done: - alternate = result.alternate - assert alternate is not None, f'Action {result.action} incomplete but no alternate action given' + action = result.alternate + assert action is not None, f'Action {result.action} incomplete but no alternate action given' - result = alternate.perform(self.engine) + result = action.perform(self.engine) LOG.debug('Performed action success=%s done=%s alternate=%s', result.success, result.done, result.alternate) if result.success: break - if result.done: - break - return result def ev_quit(self, event: tcod.event.Quit) -> Optional[Action]: @@ -103,7 +107,7 @@ class EventHandler(tcod.event.EventDispatch[Action]): case tcod.event.KeySym.y: action = BumpAction(hero, Direction.NorthWest) case tcod.event.KeySym.SPACE: - action = RegenerateRoomsAction() + action = RegenerateRoomsAction(hero) case tcod.event.KeySym.PERIOD: action = WaitAction(hero)