// Class to define and manipulate a Tic-Tac-Toe Board
public class TicTacToeBoard {
private char[][] board = new char[4][4]; // ignore row [0]
// constructor
TicTacToeBoard () {
int i;
int j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
board[i][j] = ' ';
}
// return printable string to represent the board
public String toString() {
String ret = ""; // build a return string
int i;
int j;
for (i = 1; i <= 3; i++) {
ret = ret + "|";
for (j = 1; j <= 3; j++)
ret = ret + board[i][j];
ret = ret + "|\n";
}
return ret;
}
// tries to play c (X or O) at row, col
// returns true if square was legal and not occupied
public boolean makeMove(int row, int col, char c) {
boolean valid = false;
if ( (row < 1) || (row > 3) || (col < 1) || (col > 3))
valid = false; // subscripts are not in range
else if (board[row][col] != ' ')
valid = false; // the requested spot is taken
else { // spot can be claimed
valid = true;
board[row][col] = c;
}
return valid;
}
// returns true if the board is a win for either X or O
public boolean isWin() {
boolean win = false;
int i;
for (i = 1; i <= 3; i++) { // check row i and col i
if (board[i][1] != ' ') // first spot is taken
if ( (board[i][1] == board[i][2]) && (board[i][1] == board[i][3])) {
//System.out.println("Found winner in row " + i );
win = true; // found 3 in a row
}
if (board[1][i] != ' ')
if ( (board[1][i] == board[2][i]) && (board[1][i] == board[3][i])) {
//System.out.println("Found winner in col " + i + "\n" + toString());
win = true; // found 3 in a col;
}
}
//if (win)
// System.out.println("\nFound win in col or row\n");
// there could be a more cleaver way to check the diagonals in the same loop
if (board[1][1] != ' ') // first spot is taken
if ( (board[1][1] == board[2][2]) && (board[1][1] == board[3][3]))
win = true; // found 3 in diagonal top left to bottom right;
if (board[1][3] != ' ') // top right is taken
if ( (board[1][3] == board[2][2]) && (board[1][3] == board[3][1]))
win = true; // found 3 in a diagonal top right to bottom left;
return win;
}
} // end of TicTacToeBoard Class
|