O'Reilly logo

Test-Driven Java Development - Second Edition by Viktor Farcic, Alex Garcia

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Requirement 6 – win condition (II)

The first win condition.

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

The checkWinCondition private method implements this rule by scanning whether or not the last move is a winning one:

... 
private Color winner;

public static final int DISCS_FOR_WIN = 4;
 
public void putDisc(int column) {
  ...
  if (numOfDiscs < ROWS) {
    board[column - 1][numOfDiscs] = currentPlayer;
    printBoard();
    checkWinCondition(column - 1, numOfDiscs);
    switchPlayer();
    ...
}
 
private void checkWinCondition(int col, int row) {
  Pattern winPattern = Pattern.compile(".*" + currentPlayer + "{" + DISCS_FOR_WIN + "}.*"); // Vertical check StringJoiner stringJoiner ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required