-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.java
More file actions
127 lines (98 loc) · 2.66 KB
/
Copy pathBoard.java
File metadata and controls
127 lines (98 loc) · 2.66 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
This is Board class. It contains the following methods:
1. boolean isEmpty(int row, int col)
2. void put(int row, int col, int turn)
3. int[][] getBoard(int row, int col)
4. boolean checkWin()
5. boolean checkTie()
*/
public class Board {
private int [][] board;
private int numOfEmptyCells;
public final static int size = 3;
public final static int USER_1_TURN = 1;
public final static int USER_2_TURN = 2;
public Board() {
board = new int [size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = -1;
}
}
numOfEmptyCells = size * size;
}
/*
Method to check if the certain cell is already occupied
Args:
row (int): row number of the cell
col (int): col number of the cell
Returns:
Boolean: true if the cell is occupied; false otherwise
*/
public boolean isEmpty(int row, int col){
if (board[row-1][col-1] == -1)
return true;
return false;
}
/*
Method to set certain cell of the board to a certain draw.
Args:
row(int): row number of the cell
col(int): col number of the cell
turn(int): user turn
Returns:
None
*/
public void put(int row, int col, int turn){
board[row-1][col-1] = (turn == USER_1_TURN)? 1 : 0;
numOfEmptyCells--;
}
/*
Method to access the internal matrix.
Args:
None
Returns:
int[][]
*/
public int[][] getBoard() {
return board;
}
/*
Method to check if the game is tied.
Args:
None
Returns:
Boolean: true if there's a tie; false otherwise
*/
public boolean checkTie() {
if (numOfEmptyCells == 0)
return !checkWin();
return false;
}
/*
Method to check if there's a winner in the board.
Args:
None
Returns:
boolean: true if there's a winner; false otherwise
*/
public boolean checkWin() {
//check winning vertically and horizontally
for (int i = 0; i < size; i++) {
if (board[i][0] == board[i][1] && board[i][0] == board[i][2]
&& board[i][0] != -1)
return true;
if (board[0][i] == board[1][i] && board[0][i] == board [2][i]
&& board[0][i] != -1)
return true;
}
//check winning diagonally
if (board[0][0] == board [1][1] && board[0][0] == board[2][2]
&& board[0][0] != -1)
return true;
if (board[0][2] == board [1][1] && board[0][2] == board[2][0]
&& board[0][2] != -1)
return true;
return false;
}
}