/** This file implements the TicTacToe class. We have a constructor * that initializes the board, a set() function that puts an X or O token * on the board, a toString() function that allows us to display the board * for the players, and a findWinner() function that sees if the game is over. */ public class TicTacToe { private char[][] board; private int numTokens; /** Create an empty game board. */ public TicTacToe() { board = new char[3][3]; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) board[i][j] = ' '; numTokens = 0; } /** The row and column numbers come in as 1-3, so we need to subtract * 1 from each when literally entering a value into the board. */ public boolean set(int i, int j, char player) { if (board[i-1][j-1] != ' ') { System.out.println("You should not cheat :("); return false; } else { board[i-1][j-1] = player; ++numTokens; return true; } } /** Create string representation of the board. */ public String toString() { String display = ""; for (int i = 0; i < 3; ++i) { display += "|"; for (int j = 0; j < 3; ++j) { display += board[i][j]; } display += "|\n"; } return display; } /** This function will determine if there is a winner, X or O. If there * is no winner yet, we return ' '. If the board is full and it's a tie, * return 'T'. */ public char findWinner() { // let's add a print statement for debugging... System.out.println("entering findWinner() with numTokens = " + numTokens); // need to make sure that we don't declare "blank" the winner! // try the 3 rows if (board[0][0] == board[0][1] && board[0][1] == board[0][2]) return board[0][0]; else if (board[1][0] == board[1][1] && board[1][1] == board[1][2]) return board[1][0]; else if (board[2][0] == board[2][1] && board[2][1] == board[2][2]) return board[2][0]; // try the 3 columns else if (board[0][0] == board[1][0] && board[1][0] == board[2][0]) return board[0][0]; else if (board[0][1] == board[1][1] && board[1][1] == board[2][1]) return board[0][1]; else if (board[0][2] == board[1][2] && board[1][2] == board[2][2]) return board[0][2]; // try the diagonals else if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0]; else if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2]; // is board full? else if (numTokens == 9) return 'T'; // if there is no match, say there is no winner yet else return ' '; } }