Refactored package-structure

Extracted Animated-interface
This commit is contained in:
Urban Modig
2025-08-31 17:54:53 +02:00
parent 61d9df04f9
commit 2e9e7cc45e
24 changed files with 223 additions and 142 deletions

View File

@ -0,0 +1,236 @@
package se.urmo.game.entities.ghost;
import lombok.extern.slf4j.Slf4j;
import se.urmo.game.collision.GhostCollisionChecker;
import se.urmo.game.entities.BaseAnimated;
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.map.GameMap;
import se.urmo.game.state.GhostManager;
import se.urmo.game.util.Direction;
import se.urmo.game.util.MiscUtil;
import se.urmo.game.util.MyPoint;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.List;
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
private static final int COLLISION_BOX_SIZE = 16;
public static final int GHOST_SIZE = 32;
private static final int ANIMATION_UPDATE_FREQUENCY = 25;
private static final int COLLISION_BOX_OFFSET = COLLISION_BOX_SIZE / 2;
private static final BufferedImage COLLISION_BOX = MiscUtil.createOutlinedBox(COLLISION_BOX_SIZE, COLLISION_BOX_SIZE, Color.black, 2);
private static final int FRIGHTENED_DURATION_TICKS = 10 * Game.UPS_SET;
private final GhostCollisionChecker collisionChecker;
private final GhostStrategy chaseStrategy;
private final MyPoint startPos;
private final BufferedImage[] fearAnimation;
private final BufferedImage[] baseAnimation;
private MyPoint position;
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;
public Ghost(GhostCollisionChecker collisionChecker, GhostStrategy strategy, GhostStrategy scaterStrategy, int animation) {
super(ANIMATION_UPDATE_FREQUENCY, GhostManager.MAX_SPRITE_FRAMES);
this.collisionChecker = collisionChecker;
this.chaseStrategy = strategy;
this.scaterStrategy = scaterStrategy;
this.baseAnimation = SpriteSheetManager.get(SpriteLocation.GHOST).getAnimation(animation);
this.fearAnimation = SpriteSheetManager.get(SpriteLocation.GHOST).getAnimation(8);
position = new MyPoint(
13 * GameMap.MAP_TILESIZE + GameMap.OFFSET_X + ((double) GameMap.MAP_TILESIZE / 2),
4 * GameMap.MAP_TILESIZE + GameMap.OFFSET_Y + ((double) GameMap.MAP_TILESIZE / 2));
startPos = position;
this.currentStrategy = chaseStrategy;
this.animation = baseAnimation;
}
public void draw(Graphics g) {
g.drawImage(
animation[aniIndex],
(int) position.x - GHOST_SIZE / 2,
(int) position.y - GHOST_SIZE / 2,
GHOST_SIZE,
GHOST_SIZE, null);
}
public void update(PacMan pacman, GameMap map) {
//updateAnimationTick();
if (mode == GhostMode.FRIGHTENED) {
updateInFrightendMode();
}
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(new Point((int) position.x, (int) position.y))) {
log.info("Evaluating possible directions");
prevDirection = direction;
direction = chooseDirection(
prioritize(collisionChecker.calculateDirectionAlternatives(position)),
currentStrategy.chooseTarget(this, pacman, map));
log.info("selecting direction {}", 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 double getSpeed() {
return BASE_SPEED * 0.75;
}
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> prioritize(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;
}
}
return best;
}
// private void updateAnimationTick() {
// if (moving) {
// aniTick++;
// if (aniTick >= ANIMATION_UPDATE_FREQUENCY) {
// aniTick = 0;
// aniIndex++;
// if (aniIndex >= GhostManager.MAX_SPRITE_FRAMES) {
// aniIndex = 0;
// }
//
// }
// }
// }
public void setMode(GhostMode mode) {
this.mode = mode;
switch (mode) {
case CHASE -> {
animation = baseAnimation;
currentStrategy = chaseStrategy;
}
case SCATTER -> currentStrategy = scaterStrategy;
case FRIGHTENED -> {
frightenedTimer = FRIGHTENED_DURATION_TICKS;
isBlinking = false;
animation = fearAnimation;
currentStrategy = fearStrategy;
}
case EATEN -> currentStrategy = null;
}
}
public boolean isFrightened() {
return mode == GhostMode.FRIGHTENED;
}
public void resetPosition() {
position = startPos;
}
public Point getPosition() {
return new Point((int) position.x, (int) position.y);
}
}