From 291f92906477a2f363d48e2de3e80e4875693764 Mon Sep 17 00:00:00 2001 From: Urban Modig Date: Sat, 6 Sep 2025 00:42:40 +0200 Subject: [PATCH] Refactor Ghost mode handling to prioritize mode transitions Reordered GhostMode enum for logical priority and updated `setMode` to enforce transitions only to higher-priority modes. Added `currentMode` method for determining the Ghost's active mode, ensuring cleaner and safer state management. --- .../java/se/urmo/game/entities/ghost/Ghost.java | 13 ++++++++++++- .../se/urmo/game/entities/ghost/mode/GhostMode.java | 6 +++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/se/urmo/game/entities/ghost/Ghost.java b/src/main/java/se/urmo/game/entities/ghost/Ghost.java index 277c037..db59b49 100644 --- a/src/main/java/se/urmo/game/entities/ghost/Ghost.java +++ b/src/main/java/se/urmo/game/entities/ghost/Ghost.java @@ -88,7 +88,10 @@ public class Ghost extends BaseAnimated { } public void setMode(GhostMode mode) { - currentState = states.get(mode); + GhostMode currentMode = currentMode(); + if (currentMode == null || mode.ordinal() < currentMode.ordinal()) { // only if new mode has higher prio + currentState = states.get(mode); + } } public boolean isFrightened() { @@ -99,6 +102,14 @@ public class Ghost extends BaseAnimated { return states.get(GhostMode.EATEN) == currentState; } + public GhostMode currentMode() { + return states.entrySet().stream() + .filter(s -> s.getValue() == currentState) + .map(Map.Entry::getKey) + .findFirst() + .orElse(null); + } + public void reset() { currentState = states.get(GhostMode.CHASE); ((ChaseGhostMode) currentState).resetPosition(); diff --git a/src/main/java/se/urmo/game/entities/ghost/mode/GhostMode.java b/src/main/java/se/urmo/game/entities/ghost/mode/GhostMode.java index d9b0b92..99ec128 100644 --- a/src/main/java/se/urmo/game/entities/ghost/mode/GhostMode.java +++ b/src/main/java/se/urmo/game/entities/ghost/mode/GhostMode.java @@ -1,10 +1,10 @@ package se.urmo.game.entities.ghost.mode; public enum GhostMode { - CHASE, - SCATTER, FRIGHTENED, EATEN, HOUSE, - FROZEN + FROZEN, + CHASE, + SCATTER }