diff --git a/core/src/com/me/pacman/entity/Ghost.java b/core/src/com/me/pacman/entity/Ghost.java index 666bf70..1548291 100644 --- a/core/src/com/me/pacman/entity/Ghost.java +++ b/core/src/com/me/pacman/entity/Ghost.java @@ -102,7 +102,35 @@ public class Ghost extends MovableEntity { return; } - if (getNextDirection() != null) { + Direction nextDirection = getNextDirection(); + + if (!canMove) { + // we're stuck somewhere, let's change directions to a new valid direction + + // check if we already have a nextDirection which will get us unstuck + if (nextDirection != null) { + Vector2 adjacent = nextDirection.getVector().add(pos); + LevelTile adjTile = state.level.getTile(adjacent); + if (adjTile != null && adjTile.isPassable()) { + return; + } + } + + for (Direction dir : GHOST_ORDER) { + if (dir.isOpposite(currDirection) || dir == currDirection) { + // don't just turn around or keep going our current direction (since we'll continue being stuck) + continue; + } + Vector2 adjacent = dir.getVector().add(pos); + LevelTile adjTile = state.level.getTile(adjacent); + if (adjTile != null && adjTile.isPassable()) { + setNextDirection(dir); + return; + } + } + } + + if (nextDirection != null) { return; } @@ -118,8 +146,8 @@ public class Ghost extends MovableEntity { } Vector2 ahead = new Vector2((int) pos.x, (int) pos.y).add(currDirection.getVector()); + float shortest = Float.MAX_VALUE; - Direction nextDirection = null; for (Direction dir : GHOST_ORDER) { if (dir.isOpposite(currDirection)) {