A Tic Tac Toe board game and the two-dimensional integer array

Tic Tac Toe board game

We give a complete Java class for maintaining a Tic-Tac-Toe board for two players. 

 

 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
public class TicTacToe {
	protected static final int X = 1, O = -1;
	protected static final int EMPTY = 0;
	protected int board[][] = new int[3][3];
	protected 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 IllegalAccessException {
		if ((i < 0) || (i > 2) || (j < 0) || (j > 2))
			throw new IllegalAccessException("Invalid board position");
		if (board[i][j] != EMPTY)
			throw new IllegalAccessException("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)
				|| (board[1][0] + board[1][1] + board[1][2] == mark * 3)
				|| (board[2][0] + board[2][1] + board[2][2] == mark * 3)
				|| (board[0][0] + board[1][0] + board[2][0] == mark * 3)
				|| (board[0][1] + board[1][1] + board[2][1] == mark * 3)
				|| (board[0][2] + board[1][2] + board[2][2] == mark * 3)
				|| (board[0][0] + board[1][1] + board[2][2] == mark * 3)
				|| (board[2][0] + board[1][1] + board[0][2] == mark * 3));
	}

	public int winner() {
		if (isWin(X))
			return (X);
		else if (isWin(O))
			return (O);
		else
			return (0);
	}

	public String toString() {
		String string = "";
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {

				switch (board[i][j]) {
				case X:
					string += "X";
					break;
				case O:
					string += "O";
					break;
				case EMPTY:
					string += " ";
					break;
				}
				if (j < 2)
					string += "|";
			}
			if (i < 2)
				string += "\n-----\n";
		}
		return string;
	}

	public static void main(String[] args) throws IllegalAccessException {
		TicTacToe game = new TicTacToe();
		game.putMark(1, 1);
		game.putMark(0, 2);
		game.putMark(2, 2);
		game.putMark(0, 0);
		game.putMark(0, 1);
		game.putMark(2, 0);
		game.putMark(1, 2);
		game.putMark(1, 0);
		game.putMark(2, 1);

		System.out.println(game.toString());
		int winningPlayer = game.winner();
		if (winningPlayer != 0)
			System.out.println(winningPlayer + " Wins");
		else {
			System.out.println("Tie");
		}
	}

}


Output:

O|X|O
-----
O|X|X
-----
O|X|X
1 Wins

Next Post
No Comment
Add Comment
comment url