1 package nl.tudelft.jpacman.game;
2
3 import java.util.List;
4
5 import nl.tudelft.jpacman.board.Direction;
6 import nl.tudelft.jpacman.level.Level;
7 import nl.tudelft.jpacman.level.Level.LevelObserver;
8 import nl.tudelft.jpacman.level.Player;
9 import nl.tudelft.jpacman.points.PointCalculator;
10
11 /**
12 * A basic implementation of a Pac-Man game.
13 *
14 * @author Jeroen Roosen
15 */
16 public abstract class Game implements LevelObserver {
17
18 /**
19 * <code>true</code> if the game is in progress.
20 */
21 private boolean inProgress;
22
23 /**
24 * Object that locks the start and stop methods.
25 */
26 private final Object progressLock = new Object();
27
28 /**
29 * The algorithm used to calculate the points that
30 * they player gets whenever some action happens.
31 */
32 private PointCalculator pointCalculator;
33
34 /**
35 * Creates a new game.
36 *
37 * @param pointCalculator
38 * The way to calculate points upon collisions.
39 */
40 protected Game(PointCalculator pointCalculator) {
41 this.pointCalculator = pointCalculator;
42 inProgress = false;
43 }
44
45 /**
46 * Starts or resumes the game.
47 */
48 public void start() {
49 synchronized (progressLock) {
50 if (isInProgress()) {
51 return;
52 }
53 if (getLevel().isAnyPlayerAlive() && getLevel().remainingPellets() > 0) {
54 inProgress = true;
55 getLevel().addObserver(this);
56 getLevel().start();
57 }
58 }
59 }
60
61 /**
62 * Pauses the game.
63 */
64 public void stop() {
65 synchronized (progressLock) {
66 if (!isInProgress()) {
67 return;
68 }
69 inProgress = false;
70 getLevel().stop();
71 }
72 }
73
74 /**
75 * @return <code>true</code> iff the game is started and in progress.
76 */
77 public boolean isInProgress() {
78 return inProgress;
79 }
80
81 /**
82 * @return An immutable list of the participants of this game.
83 */
84 public abstract List<Player> getPlayers();
85
86 /**
87 * @return The level currently being played.
88 */
89 public abstract Level getLevel();
90
91 /**
92 * Moves the specified player one square in the given direction.
93 *
94 * @param player
95 * The player to move.
96 * @param direction
97 * The direction to move in.
98 */
99 public void move(Player player, Direction direction) {
100 if (isInProgress()) {
101 // execute player move.
102 getLevel().move(player, direction);
103 pointCalculator.pacmanMoved(player, direction);
104 }
105 }
106
107 @Override
108 public void levelWon() {
109 stop();
110 }
111
112 @Override
113 public void levelLost() {
114 stop();
115 }
116 }