85 lines
2.4 KiB
Java
85 lines
2.4 KiB
Java
package se.urmo.game.state;
|
|
|
|
import lombok.Getter;
|
|
import se.urmo.game.collision.CollisionChecker;
|
|
import se.urmo.game.collision.GhostCollisionChecker;
|
|
import se.urmo.game.entities.BlinkyStrategy;
|
|
import se.urmo.game.entities.Ghost;
|
|
import se.urmo.game.entities.PacMan;
|
|
import se.urmo.game.main.Game;
|
|
import se.urmo.game.map.GameMap;
|
|
import se.urmo.game.util.Direction;
|
|
|
|
import java.awt.*;
|
|
import java.awt.event.KeyEvent;
|
|
|
|
public class PlayingState implements GameState {
|
|
private final Game game;
|
|
private final GameStateManager gameStateManager;
|
|
private final GhostManager ghostManager;
|
|
private PacMan pacman;
|
|
@Getter
|
|
private GameMap map;
|
|
private int score;
|
|
|
|
public PlayingState(Game game, GameStateManager gameStateManager) {
|
|
this.game = game;
|
|
this.gameStateManager = gameStateManager;
|
|
this.map = new GameMap();
|
|
this.pacman = new PacMan(game, new CollisionChecker(map));
|
|
this.ghostManager = new GhostManager(new GhostCollisionChecker(map));
|
|
}
|
|
|
|
@Override
|
|
public void update() {
|
|
pacman.update();
|
|
ghostManager.update(pacman, map);
|
|
checkCollisions();
|
|
}
|
|
|
|
@Override
|
|
public void render(Graphics2D g) {
|
|
map.draw(g);
|
|
pacman.draw(g);
|
|
ghostManager.draw(g);
|
|
}
|
|
|
|
@Override
|
|
public void keyPressed(KeyEvent e) {
|
|
switch (e.getKeyCode()) {
|
|
case KeyEvent.VK_W -> move(Direction.UP);
|
|
case KeyEvent.VK_S -> move(Direction.DOWN);
|
|
case KeyEvent.VK_A -> move(Direction.LEFT);
|
|
case KeyEvent.VK_D -> move(Direction.RIGHT);
|
|
}
|
|
}
|
|
|
|
private void move(Direction direction) {
|
|
pacman.setMoving(true);
|
|
pacman.setDirection(direction);
|
|
}
|
|
|
|
@Override
|
|
public void keyReleased(KeyEvent e) {
|
|
pacman.setMoving(false);
|
|
pacman.setDirection(Direction.NONE);
|
|
}
|
|
|
|
private void checkCollisions() {
|
|
for (Ghost ghost : ghostManager.getGhosts()) {
|
|
double dist = pacman.distanceTo(ghost.getPosition());
|
|
if (dist < GameMap.MAP_TILESIZE / 2.0) {
|
|
if (ghost.isFrightened()) {
|
|
// Pac-Man eats ghost
|
|
score += 200;
|
|
ghost.resetPosition();
|
|
} else {
|
|
// Pac-Man loses a life
|
|
pacman.loseLife();
|
|
pacman.resetPosition();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|