-
Notifications
You must be signed in to change notification settings - Fork 0
/
TicTacToe.java
102 lines (98 loc) · 3.31 KB
/
TicTacToe.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
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
public class TicTacToe{
public static final int X = 1, O = -1;
public static final int EMPTY = 0;
private int board[][] = new int[3][3];
private int player;
public TicTacToe(){clearBoard();}
public void clearBoard(){
for (int i = 0; i <3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j]=EMPTY;
}
}
player = X;
}
public void putMark(int i, int j) throws IllegalArgumentException {
if ((i<0) || (i>2) || (j<0) || (j>2)) {
throw new IllegalArgumentException("Invalid boardposition.");
}
if (board[i][j] != EMPTY) {
throw new IllegalArgumentException("Board position occupied.");
}
board[i][j]=player;
player= -player;
}
public boolean isWin(int mark) {
return ((board[0][0] + board[0][1] + board[0][2] == mark*3) // row 0
|| (board[1][0] + board[1][1] + board[1][2] == mark*3) // row 1
|| (board[2][0] + board[2][1] + board[2][2] == mark*3) // row 2
|| (board[0][0] + board[1][0] + board[2][0] == mark*3) // column 0
|| (board[0][1] + board[1][1] + board[2][1] == mark*3) // column 1
|| (board[0][2] + board[1][2] + board[2][2] == mark*3) // column 2
|| (board[0][0] + board[1][1] + board[2][2] == mark*3) // diagonal
|| (board[2][0] + board[1][1] + board[0][2] == mark*3)); // rev diag
}
public int winner(){
if (isWin(X)) {
return(X);
}
else if (isWin(O)) {
return(O);
}
else{
return 0;
}
}
public String toString(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
switch (board[i][j]){
case X:{
sb.append("X");
break;
}
case O:{
sb.append("O");
break;
}
case EMPTY:{
sb.append(" ");
break;
}
}
if (j<2) {
sb.append("|");
}
}
if (i<2) {
sb.append("\n_____\n");
}
}
return sb.toString();
}
public static void main(String[] args){
TicTacToe game = new TicTacToe();
// O wins
// game.putMark(0,0); game.putMark(0,2);
// game.putMark(1,1); game.putMark(0,1);
// game.putMark(2,0); game.putMark(2,2);
// game.putMark(2,1); game.putMark(1,2);
// X Wins
// game.putMark(1,1); game.putMark(0,2);
// game.putMark(2,1); game.putMark(0,0);
// game.putMark(0,1); game.putMark(2,2);
// game.putMark(1,2); game.putMark(1,0);
// game.putMark(2,0);
// Tie
game.putMark(1,1); game.putMark(0,2);
game.putMark(2,2); game.putMark(0,0);
game.putMark(0,1); game.putMark(2,1);
game.putMark(1,2); game.putMark(1,0);
game.putMark(2,0);
System.out.println(game);
int winningPlayer = game.winner();
String[] outcome = {"O Wins","Tie", "X Wins"};
System.out.println(outcome[1+winningPlayer]);
}
}