1 package nl.tudelft.jpacman.board;
2
3
4 /**
5 * A top-down view of a matrix of {@link Square}s.
6 *
7 * @author Jeroen Roosen
8 */
9 public class Board {
10
11 /**
12 * The grid of squares with board[x][y] being the square at column x, row y.
13 */
14 private final Square[][] board;
15
16 /**
17 * Creates a new board.
18 *
19 * @param grid
20 * The grid of squares with grid[x][y] being the square at column
21 * x, row y.
22 */
23 @SuppressWarnings("PMD.ArrayIsStoredDirectly")
24 Board(Square[][] grid) {
25 assert grid != null;
26 this.board = grid;
27 assert invariant() : "Initial grid cannot contain null squares";
28 }
29
30 /**
31 * Whatever happens, the squares on the board can't be null.
32 * @return false if any square on the board is null.
33 */
34 protected final boolean invariant() {
35 for (Square[] row : board) {
36 for (Square square : row) {
37 if (square == null) {
38 return false;
39 }
40 }
41 }
42 return true;
43 }
44
45 /**
46 * Returns the number of columns.
47 *
48 * @return The width of this board.
49 */
50 public int getWidth() {
51 return board.length;
52 }
53
54 /**
55 * Returns the number of rows.
56 *
57 * @return The height of this board.
58 */
59 public int getHeight() {
60 return board[0].length;
61 }
62
63 /**
64 * Returns the square at the given <code>x,y</code> position.
65 *
66 * Precondition: The <code>(x, y)</code> coordinates are within the
67 * width and height of the board.
68 *
69 * @param x
70 * The <code>x</code> position (column) of the requested square.
71 * @param y
72 * The <code>y</code> position (row) of the requested square.
73 * @return The square at the given <code>x,y</code> position (never null).
74 */
75 public Square squareAt(int x, int y) {
76 assert withinBorders(x, y);
77 Square result = board[x][y];
78 assert result != null : "Follows from invariant.";
79 return result;
80 }
81
82 /**
83 * Determines whether the given <code>x,y</code> position is on this board.
84 *
85 * @param x
86 * The <code>x</code> position (row) to test.
87 * @param y
88 * The <code>y</code> position (column) to test.
89 * @return <code>true</code> iff the position is on this board.
90 */
91 public boolean withinBorders(int x, int y) {
92 return x >= 0 && x < getWidth() && y >= 0 && y < getHeight();
93 }
94 }