blob: ebd9dd3cb5a61d8fc3d91ff2248fa01eef58b753 (
plain) (
blame)
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
|
package tutorial;
import java.util.Random;
public class TicTacToeGame {
private final PLAYER[][] boardOccupancy;
private PLAYER currentPlayer;
private enum PLAYER {
CROSS('x'), CIRCLE('o'), NONE('-');
private char symbol;
private PLAYER(char symbol) {
this.symbol = symbol;
}
@Override
public String toString() {
return this.symbol + "";
}
}
private static PLAYER[][] createInitialOccupancy() {
PLAYER[][] result = new PLAYER[3][3];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
result[i][j] = PLAYER.NONE;
}
}
return result;
}
/**
* Creates a new game of TicTacToe. The first player is random.
*/
public TicTacToeGame() {
this.boardOccupancy = createInitialOccupancy();
this.currentPlayer = new Random().nextBoolean() ? PLAYER.CIRCLE : PLAYER.CROSS;
}
/**
* Prints the current board in text format.
*/
public void printBoard() {
System.out.println("Board:");
for (int i = 0; i < this.boardOccupancy.length; i++) {
for (int j = 0; j < this.boardOccupancy[0].length; j++) {
System.out.print(boardOccupancy[i][j]);
}
System.out.println();
}
}
/**
* Plays a move as the current player, then switches to the other player. Does
* nothing if the action is invalid (out of bounds or occupied cell).
*
* @param x The x coordinate.
* @param y The y coordinate.
*/
public void play(int x, int y) {
if (x >= 0 && x <= 2 && y >= 0 && y <= 2 && boardOccupancy[x][y] == PLAYER.NONE) {
this.boardOccupancy[x][y] = this.currentPlayer;
this.currentPlayer = this.currentPlayer == PLAYER.CROSS ? PLAYER.CIRCLE : PLAYER.CROSS;
}
}
}
|