Ghost refactoring

This commit is contained in:
Urban Modig
2025-09-05 23:22:45 +02:00
parent ebbc82b70e
commit 5f118a75f6
9 changed files with 454 additions and 190 deletions

View File

@ -1,16 +1,14 @@
package se.urmo.game.entities.ghost;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import se.urmo.game.collision.GhostCollisionChecker;
import se.urmo.game.entities.BaseAnimated;
import se.urmo.game.entities.ghost.strategy.EatenStrategy;
import se.urmo.game.entities.ghost.strategy.FearStrategy;
import se.urmo.game.entities.ghost.strategy.GhostStrategy;
import se.urmo.game.entities.pacman.PacMan;
import se.urmo.game.graphics.SpriteLocation;
import se.urmo.game.graphics.SpriteSheetManager;
import se.urmo.game.main.Game;
import se.urmo.game.main.GhostManager;
import se.urmo.game.main.LevelManager;
import se.urmo.game.map.GameMap;
@ -18,64 +16,69 @@ import se.urmo.game.util.Direction;
import se.urmo.game.util.MyPoint;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
public class Ghost extends BaseAnimated {
private static final double BASE_SPEED = 0.40;
private static final int WARNING_THRESHOLD = 180; // 3 seconds of warning
public static final double BASE_SPEED = 0.40;
public static final int GHOST_SIZE = 32;
private static final int ANIMATION_UPDATE_FREQUENCY = 25;
private static final int FRIGHTENED_DURATION_TICKS = 10 * Game.UPS_SET;
private final GhostCollisionChecker collisionChecker;
private final GhostStrategy chaseStrategy;
private final MyPoint startPos;
private static final BufferedImage[] fearAnimation = SpriteSheetManager.get(SpriteLocation.GHOST).getAnimation(8);
private final BufferedImage[] baseAnimation;
private final LevelManager levelManager;
private static final BufferedImage[] eatenAnimation = SpriteSheetManager.get(SpriteLocation.GHOST).getAnimation(9);
private double speed;
@Getter
private MyPoint position;
private final GhostCollisionChecker collisionChecker;
@Getter
private final BufferedImage[] baseAnimation;
@Getter
private final int animation;
@Getter
private final LevelManager levelManager;
@Getter
private final GhostStrategy scaterStrategy;
private GhostStrategy currentStrategy;
private BufferedImage[] animation;
private Direction direction;
private Direction prevDirection;
private GhostMode mode;
private final GhostStrategy fearStrategy = new FearStrategy();
private int frightenedTimer = 0;
private boolean isBlinking = false;
private static final GhostStrategy eatenStrategy = new EatenStrategy();
private GhostState currentState;
private final Map<GhostMode, GhostState> states = new EnumMap<>(GhostMode.class);
// Movement-related state
@Getter
@Setter
protected MyPoint position;
@Getter
@Setter
protected Direction direction;
@Getter
@Setter
protected Direction prevDirection;
@Getter
private static final MyPoint startPosition = new MyPoint(
GameMap.colToScreen(13) + ((double) GameMap.MAP_TILESIZE / 2),
GameMap.rowToScreen(4) + ((double) GameMap.MAP_TILESIZE / 2));
;
public Ghost(GhostCollisionChecker collisionChecker, GhostStrategy chaseStrategy, GhostStrategy scaterStrategy, int animation, LevelManager levelManager) {
super(ANIMATION_UPDATE_FREQUENCY, GhostManager.MAX_SPRITE_FRAMES);
this.collisionChecker = collisionChecker;
this.chaseStrategy = chaseStrategy;
this.scaterStrategy = scaterStrategy;
this.currentStrategy = this.chaseStrategy;
this.baseAnimation = SpriteSheetManager.get(SpriteLocation.GHOST).getAnimation(animation);
position = new MyPoint(
GameMap.colToScreen(13) + ((double) GameMap.MAP_TILESIZE / 2),
GameMap.rowToScreen(4) + ((double) GameMap.MAP_TILESIZE / 2));
startPos = position;
this.animation = baseAnimation;
this.animation = animation;
this.levelManager = levelManager;
this.speed = BASE_SPEED * levelManager.getGhostSpeed();
states.put(GhostMode.CHASE, new ChaseGhostMode(this, chaseStrategy));
states.put(GhostMode.SCATTER, new ScatterGhostMode(this, scaterStrategy));
states.put(GhostMode.FRIGHTENED, new FrightenedGhostMode(this));
states.put(GhostMode.EATEN, new EatenGhostMode(this));
states.put(GhostMode.FROZEN, new FrozenGhostMode(this));
reset();
}
public void draw(Graphics g) {
MyPoint position = currentState.getPosition();
g.drawImage(
animation[aniIndex],
currentState.getAnimation()[aniIndex],
(int) position.x - GHOST_SIZE / 2,
(int) position.y - GHOST_SIZE / 2,
GHOST_SIZE,
@ -83,162 +86,25 @@ public class Ghost extends BaseAnimated {
}
public void update(PacMan pacman, GameMap map) {
switch (mode) {
case FRIGHTENED -> {
updateInFrightendMode();
updatePosition(pacman, map);
}
case EATEN -> {
if (position.asPoint().distance(startPos.asPoint()) < 10) {
setMode(GhostMode.CHASE);
}
updatePosition(pacman, map);
}
case FROZEN -> {
}
default -> updatePosition(pacman, map);
}
}
private void updateInFrightendMode() {
frightenedTimer--;
if (frightenedTimer <= WARNING_THRESHOLD) {
isBlinking = (frightenedTimer / 25) % 2 == 0;
animation = isBlinking ? fearAnimation : baseAnimation;
}
if (frightenedTimer <= 0) {
setMode(GhostMode.CHASE);
}
}
private void updatePosition(PacMan pacman, GameMap map) {
if (map.isAligned(position.asPoint())) {
prevDirection = direction;
direction = chooseDirection(
prioritizeDirections(collisionChecker.calculateDirectionAlternatives(position)),
currentStrategy.chooseTarget(this, pacman, map));
log.debug("Ghost moving to {}", direction);
}
moveTo(getNewPosition());
}
/**
* Given a position and a direction - calculate the new position
* Moves one pixel in the given direction
*
* @return new position
*/
private MyPoint getNewPosition() {
return new MyPoint(
position.x + direction.dx * getSpeed(),
position.y + direction.dy * getSpeed());
}
private void moveTo(MyPoint newPosition) {
MyPoint destination = collisionChecker.canMoveTo(direction, newPosition.x, newPosition.y);
if (destination != null) {
position = destination;
}
}
/**
* Creates a map of directions and their associated priority values based on the given list of directions.
* Directions with a value of {@code Direction.NONE} are excluded. If a direction is opposite to the
* previous direction, it is given a higher priority value.
*
* @param directions a list of potential movement directions
* @return a map where keys are valid directions and values are their associated priority
*/
private Map<Direction, Integer> prioritizeDirections(List<Direction> directions) {
return directions.stream()
.filter(d -> d != Direction.NONE)
.collect(Collectors.toMap(
d -> d,
d -> (prevDirection != null && d == prevDirection.opposite()) ? 2 : 1
));
}
/**
* Selects the best movement direction for the ghost based on priority and distance to the target.
* The method evaluates the directions with the lowest priority value and chooses the one that
* minimizes the distance to the target point.
*
* @param options a map where keys represent potential movement directions and values
* represent their associated priority levels
* @param target the target point towards which the direction is evaluated
* @return the direction that has the lowest priority and minimizes the distance to the target
*/
private Direction chooseDirection(Map<Direction, Integer> options, Point target) {
// Find the lowest priority
int lowestPriority = options.values().stream()
.mapToInt(Integer::intValue)
.min()
.orElse(Integer.MAX_VALUE);
// Collect all directions that have this priority
List<Direction> directions = options.entrySet().stream()
.filter(entry -> entry.getValue() == lowestPriority)
.map(Map.Entry::getKey)
.toList();
// Calculate the direction that has the lowest distance to the target
Direction best = directions.getFirst();
double bestDist = Double.MAX_VALUE;
for (Direction d : directions) {
double nx = position.x + d.dx * GameMap.MAP_TILESIZE;
double ny = position.y + d.dy * GameMap.MAP_TILESIZE;
double dist = target.distance(nx, ny);
if (dist < bestDist) {
bestDist = dist;
best = d;
}
}
log.debug("Ghost comming from {}, choosing {}, from {} (dist={})", prevDirection, best, directions, bestDist);
return best;
currentState.update(this, pacman, map);
}
public void setMode(GhostMode mode) {
this.mode = mode;
switch (mode) {
case CHASE -> {
animation = baseAnimation;
currentStrategy = chaseStrategy;
speed = BASE_SPEED * levelManager.getGhostSpeed();
}
case SCATTER -> currentStrategy = scaterStrategy;
case FRIGHTENED -> {
frightenedTimer = FRIGHTENED_DURATION_TICKS;
isBlinking = false;
animation = fearAnimation;
currentStrategy = fearStrategy;
}
case EATEN -> {
speed = 1.0;
currentStrategy = eatenStrategy;
animation = eatenAnimation;
}
case FROZEN -> {/* Do nothing */}
}
}
private double getSpeed() {
return this.speed;
currentState = states.get(mode);
//currentState.enter(this);
}
public boolean isFrightened() {
return mode == GhostMode.FRIGHTENED;
}
public void reset() {
position = startPos;
this.speed = BASE_SPEED * levelManager.getGhostSpeed();
return states.get(GhostMode.FRIGHTENED) == currentState;
}
public boolean isEaten() {
return mode == GhostMode.EATEN;
return states.get(GhostMode.EATEN) == currentState;
}
public void reset() {
currentState = states.get(GhostMode.CHASE);
//currentState.enter(this);
((ChaseGhostMode) currentState).resetPosition();
}
}