private void clearCells() { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { cells[i][j] = new Cell(); } } }
private boolean isCellValueAlreadySet(int row, int col) { return cells[row][col].getValue() != null; }
/** * Mark the current row for the player who's current turn it is. * Will perform no-op if the arguments are out of range or if that position is already played. * Will also perform a no-op if the game is already over. * * @param row 0..2 * @param col 0..2 * */ public void mark( int row, int col ) { if(isValid(row, col)) { cells[row][col].setValue(currentTurn); if(isWinningMoveByPlayer(currentTurn, row, col)) { state = GameState.FINISHED; winner = currentTurn; } else { // flip the current turn and continue flipCurrentTurn(); } } }
/** * Algorithm adapted from http://www.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe.html * @param player * @param currentRow * @param currentCol * @return true if <code>player</code> who just played the move at the <code>currentRow</code>, <code>currentCol</code> * has a tic tac toe. */ private boolean isWinningMoveByPlayer(Player player, int currentRow, int currentCol) { return (cells[currentRow][0].getValue() == player // 3-in-the-row && cells[currentRow][1].getValue() == player && cells[currentRow][2].getValue() == player || cells[0][currentCol].getValue() == player // 3-in-the-column && cells[1][currentCol].getValue() == player && cells[2][currentCol].getValue() == player || currentRow == currentCol // 3-in-the-diagonal && cells[0][0].getValue() == player && cells[1][1].getValue() == player && cells[2][2].getValue() == player || currentRow + currentCol == 2 // 3-in-the-opposite-diagonal && cells[0][2].getValue() == player && cells[1][1].getValue() == player && cells[2][0].getValue() == player); }