/** * Restart or start a new game, will clear the board and win status */ public void restart() { clearCells(); winner = null; currentTurn = Player.X; state = GameState.IN_PROGRESS; }
private boolean isValid(int row, int col ) { if( state == GameState.FINISHED ) { return false; } else if( isOutOfBounds(row) || isOutOfBounds(col) ) { return false; } else if( isCellValueAlreadySet(row, col) ) { return false; } else { return true; } }
public Board() { restart(); }
/** * 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(); } } }
/** * This test will simulate and verify x is the winner. * * X | X | X * O | | * | O | */ @Test public void test3inRowAcrossTopForX() { board.mark(0,0); // x assertNull(board.getWinner()); board.mark(1,0); // o assertNull(board.getWinner()); board.mark(0,1); // x assertNull(board.getWinner()); board.mark(2,1); // o assertNull(board.getWinner()); board.mark(0,2); // x assertEquals(Player.X, board.getWinner()); }
@Before public void setup() { board = new Board(); }
/** * This test will simulate and verify o is the winner. * * O | X | X * | O | * | X | O */ @Test public void test3inRowDiagonalFromTopLeftToBottomForO() { board.mark(0,1); // x assertNull(board.getWinner()); board.mark(0,0); // o assertNull(board.getWinner()); board.mark(2,1); // x assertNull(board.getWinner()); board.mark(1,1); // o assertNull(board.getWinner()); board.mark(0,2); // x assertNull(board.getWinner()); board.mark(2,2); // o assertEquals(Player.O, board.getWinner()); }