diff --git a/src/main/java/se/urmo/game/entities/Ghost.java b/src/main/java/se/urmo/game/entities/Ghost.java index 35df042..5f8ca99 100644 --- a/src/main/java/se/urmo/game/entities/Ghost.java +++ b/src/main/java/se/urmo/game/entities/Ghost.java @@ -74,30 +74,58 @@ public class Ghost { } private void updatePosition(PacMan pacman, GameMap map) { + // only move ghost on update interval - this is basically ghost speed; if (movementTick >= GHOST_MOVEMENT_UPDATE_FREQUENCY) { - if (isAlligned(position)) { - log.info("Evaluating possible directions"); - prevDirection = direction; - direction = chooseDirection( - prioritize(collisionChecker.calculateDirectionAlternatives(position)), - currentStrategy.chooseTarget(this, pacman, map)); - log.info("selecting direction {}", direction); - } + chooseDirection(pacman, map); - Point newPosition = new Point( - position.x + direction.dx, - position.y + direction.dy); - log.debug("Next position {}", newPosition); + Point newPosition = getNewPosition(); - Point destination = collisionChecker.canMoveTo(direction, newPosition); + move(newPosition); - if (destination != null) { - position = destination; - } movementTick = 0; } else movementTick++; } + /** + * Given a position and a direction - calculate the new position + * + * @return new position + */ + private Point getNewPosition() { + Point point = new Point( + position.x + direction.dx, + position.y + direction.dy); + log.debug("Next position {}", point); + return point; + + } + + /** + * Choose a new direction when 'aligned' ie when in the exact middle of a tile + * else continue with the existing direction. + * + * @param pacman + * @param map + */ + private void chooseDirection(PacMan pacman, GameMap map) { + if (isAlligned(position)) { + log.info("Evaluating possible directions"); + prevDirection = direction; + direction = chooseDirection( + prioritize(collisionChecker.calculateDirectionAlternatives(position)), + currentStrategy.chooseTarget(this, pacman, map)); + log.info("selecting direction {}", direction); + } + } + + private void move(Point newPosition) { + Point destination = collisionChecker.canMoveTo(direction, newPosition); + + if (destination != null) { + position = destination; + } + } + private Map prioritize(List directions) { return directions.stream() .filter(d -> d != Direction.NONE)