1 |
/** |
2 |
A 3 x 3 Tic-Tac-Toe board. |
3 |
*/ |
4 |
public class TicTacToe |
5 |
{ |
6 |
/** |
7 |
Constructs an empty board. |
8 |
*/ |
9 |
public TicTacToe() |
10 |
{ |
11 |
board = new char[ROWS][COLUMNS]; |
12 |
|
13 |
// fill with spaces |
14 |
for (int i = 0; i < ROWS; i++) |
15 |
for (int j = 0; j < COLUMNS; j++) |
16 |
board[i][j] = ' '; |
17 |
} |
18 |
|
19 |
/** |
20 |
Sets a field in the board. The field must be unoccupied. |
21 |
@param i the row index |
22 |
@param j the column index |
23 |
@param player the player ('x' or 'o') |
24 |
*/ |
25 |
public void set(int i, int j, char player) |
26 |
{ |
27 |
if (board[i][j] != ' ') |
28 |
throw new IllegalArgumentException("Position occupied"); |
29 |
board[i][j] = player; |
30 |
} |
31 |
|
32 |
/** |
33 |
Creates a string representation of the board such as |
34 |
|x o| |
35 |
| x | |
36 |
| o| |
37 |
@return the string representation |
38 |
public String toString() |
39 |
{ |
40 |
String r = ""; |
41 |
for (int i = 0; i < ROWS; i++) |
42 |
{ |
43 |
r = r + "|"; |
44 |
for (int j = 0; j < COLUMNS; j++) |
45 |
r = r + board[i][j]; |
46 |
r = r + "|\n"; |
47 |
} |
48 |
return r; |
49 |
} |
50 |
|
51 |
private char[][] board; |
52 |
private static final int ROWS = 3; |
53 |
private static final int COLUMNS = 3; |
54 |
} |