-
Notifications
You must be signed in to change notification settings - Fork 9
/
Board.java
75 lines (63 loc) Β· 1.83 KB
/
Board.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package boardgame;
public class Board {
private int rows;
private int columns;
private Piece[][] pieces;
public Board(int rows, int columns) {
if(rows < 1 || columns < 1) {
throw new BoardException("Error creating board: there must be at least 1 row and 1 column");
}
this.rows = rows;
this.columns = columns;
pieces = new Piece[rows][columns];
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public Piece piece(int row, int column) {
if(!positionExists(row, column)) {
throw new BoardException("Position not on the board");
}
return pieces[row][column];
}
public Piece piece(Position position) {
if(!positionExists(position)) {
throw new BoardException("Position not on the board");
}
return pieces[position.getRow()][position.getColumn()];
}
public void placePiece(Piece piece, Position position) {
if(thereIsAPiece(position)) {
throw new BoardException("There is already a piece on position " + position);
}
pieces[position.getRow()][position.getColumn()] = piece;
piece.position = position;
}
public Piece removePiece(Position position) {
if(!positionExists(position)) {
throw new BoardException("Position not on the board");
}
if(piece(position) == null) {
return null;
}
Piece aux = piece(position);
aux.position = null;
pieces[position.getRow()][position.getColumn()] = null;
return aux;
}
private boolean positionExists(int row, int column) {
return row >= 0 && row < rows && column >= 0 && column < columns;
}
public boolean positionExists(Position position) {
return positionExists(position.getRow(), position.getColumn());
}
public boolean thereIsAPiece(Position position) {
if(!positionExists(position)) {
throw new BoardException("Position not on the board");
}
return piece(position) != null;
}
}