Requirement 6 – win condition (II)

This is the first win condition requirement for players.

If a player inserts a disc and connects more than three discs of his color in a straight vertical line, then that player wins.

In fact, this requires one single check. If the current inserted disc connects other three discs in a vertical line, the current player wins the game:

@Test
public void when4VerticalDiscsAreConnectedThenPlayerWins() {
  for (int row = 0; row < 3; row++) {
    tested.putDiscInColumn(1); // R
    tested.putDiscInColumn(2); // G
  }
  assertThat(tested.getWinner(), isEmptyString());
  tested.putDiscInColumn(1); // R
  assertThat(tested.getWinner(), is("R"));
}

There are a couple of changes to the putDiscInColumn method. Also, a new method called checkWinner has been created:

private static final int DISCS_TO_WIN = 4;

private String winner = "";

private void checkWinner(int row, int column) {
  if (winner.isEmpty()) {
    String colour = board[row][column];
    Pattern winPattern =
      Pattern.compile(".*" + colour + "{" +
DISCS_TO_WIN + "}.*"); String vertical = IntStream
.range(0, ROWS) .mapToObj(r -> board[r][column]) .reduce(String::concat).get();
if (winPattern.matcher(vertical).matches())
winner = colour; } }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.42.251