From 10675e84022232a95053e82b2a28745282f97cf0 Mon Sep 17 00:00:00 2001 From: aniketShukla Date: Mon, 23 Nov 2026 11:42:14 +0530 Subject: [PATCH 1/2] feat: add TicTacToe and Connect Four games --- .../puzzlesandgames/ConnectFour.java | 134 +++++++++++++ .../puzzlesandgames/TicTacToe.java | 178 ++++++++++++++++++ .../puzzlesandgames/ConnectFourTest.java | 86 +++++++++ .../puzzlesandgames/TicTacToeTest.java | 109 +++++++++++ 4 files changed, 507 insertions(+) create mode 100644 src/main/java/com/thealgorithms/puzzlesandgames/ConnectFour.java create mode 100644 src/main/java/com/thealgorithms/puzzlesandgames/TicTacToe.java create mode 100644 src/test/java/com/thealgorithms/puzzlesandgames/ConnectFourTest.java create mode 100644 src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java diff --git a/src/main/java/com/thealgorithms/puzzlesandgames/ConnectFour.java b/src/main/java/com/thealgorithms/puzzlesandgames/ConnectFour.java new file mode 100644 index 000000000000..f9756757b2ef --- /dev/null +++ b/src/main/java/com/thealgorithms/puzzlesandgames/ConnectFour.java @@ -0,0 +1,134 @@ +package com.thealgorithms.puzzlesandgames; + +import java.util.Arrays; + +/** + * Connect Four on a 6-row by 7-column board. + * + *

+ * Players take turns dropping a disc into a column; the disc falls to the + * lowest free row. The first player to line up four discs horizontally, + * vertically or diagonally wins. If the board fills up the game is a draw. + *

+ * + *

+ * Win detection only inspects the four lines through the last disc played: + * Time Complexity O(1) per move, Space Complexity O(1) besides the board. + *

+ * + *

+ * See Connect Four on Wikipedia. + *

+ */ +public final class ConnectFour { + + public static final char EMPTY = '.'; + public static final char RED = 'R'; + public static final char YELLOW = 'Y'; + public static final int ROWS = 6; + public static final int COLS = 7; + private static final int CONNECT = 4; + // {rowStep, colStep}: horizontal, vertical, and the two diagonals + private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {1, 1}, {1, -1}}; + + private final char[][] board = new char[ROWS][COLS]; + private char currentPlayer = RED; + private char winner = EMPTY; + private int moves; + + /** Creates an empty board; {@code RED} moves first. */ + public ConnectFour() { + for (char[] row : board) { + Arrays.fill(row, EMPTY); + } + } + + /** + * Drops a disc for the current player into a column. + * + * @param col column index, 0-6 + * @return the row (0 is the top) where the disc landed + * @throws IllegalStateException if the game is already over + * @throws IllegalArgumentException if the column is invalid or full + */ + public int dropDisc(int col) { + if (isGameOver()) { + throw new IllegalStateException("Game is already over"); + } + if (col < 0 || col >= COLS) { + throw new IllegalArgumentException("Column is outside the board"); + } + int row = lowestFreeRow(col); + if (row < 0) { + throw new IllegalArgumentException("Column is full"); + } + board[row][col] = currentPlayer; + moves++; + if (isWinningMove(row, col)) { + winner = currentPlayer; + } + currentPlayer = currentPlayer == RED ? YELLOW : RED; + return row; + } + + /** @return the winning disc, or {@link #EMPTY} if nobody has won yet */ + public char getWinner() { + return winner; + } + + /** @return true if the board is full and nobody has won */ + public boolean isDraw() { + return winner == EMPTY && moves == ROWS * COLS; + } + + /** @return true if someone has won or the board is full */ + public boolean isGameOver() { + return winner != EMPTY || moves == ROWS * COLS; + } + + /** @return the disc of the player whose turn it is */ + public char getCurrentPlayer() { + return currentPlayer; + } + + /** @return a copy of the board, indexed {@code [row][col]} with row 0 at the top */ + public char[][] getBoard() { + char[][] copy = new char[ROWS][]; + for (int i = 0; i < ROWS; i++) { + copy[i] = board[i].clone(); + } + return copy; + } + + private int lowestFreeRow(int col) { + for (int row = ROWS - 1; row >= 0; row--) { + if (board[row][col] == EMPTY) { + return row; + } + } + return -1; + } + + private boolean isWinningMove(int row, int col) { + char disc = board[row][col]; + for (int[] d : DIRECTIONS) { + int count = 1 + countInDirection(row, col, d[0], d[1], disc) + countInDirection(row, col, -d[0], -d[1], disc); + if (count >= CONNECT) { + return true; + } + } + return false; + } + + private int countInDirection(int row, int col, int rowStep, int colStep, char disc) { + int count = 0; + int r = row + rowStep; + int c = col + colStep; + while (r >= 0 && r < ROWS && c >= 0 && c < COLS && board[r][c] == disc) { + count++; + r += rowStep; + c += colStep; + } + return count; + } +} diff --git a/src/main/java/com/thealgorithms/puzzlesandgames/TicTacToe.java b/src/main/java/com/thealgorithms/puzzlesandgames/TicTacToe.java new file mode 100644 index 000000000000..e9ee8c70979b --- /dev/null +++ b/src/main/java/com/thealgorithms/puzzlesandgames/TicTacToe.java @@ -0,0 +1,178 @@ +package com.thealgorithms.puzzlesandgames; + +/** + * Tic-Tac-Toe on a 3x3 board, with a perfect-play move finder based on the + * negamax form of the minimax algorithm. + * + *

+ * Players alternate placing marks; the first to fill a row, column or + * diagonal wins. If the board fills with no winner the game is a draw. + *

+ * + *

+ * Best-move search: Time Complexity O(b!) where b is the number of empty cells + * (at most 9! = 362880 positions). Space Complexity: O(b) recursion depth. + *

+ * + *

+ * See Tic-tac-toe on Wikipedia + * and Minimax on Wikipedia. + *

+ */ +public final class TicTacToe { + + public static final char EMPTY = ' '; + public static final char X = 'X'; + public static final char O = 'O'; + private static final int SIZE = 3; + + private final char[][] board = new char[SIZE][SIZE]; + private char currentPlayer = X; + + public TicTacToe() { + for (char[] row : board) { + java.util.Arrays.fill(row, EMPTY); + } + } + + /** + * Places the current player's mark and passes the turn. + * + * @param row row index, 0-2 + * @param col column index, 0-2 + * @throws IllegalStateException if the game is already over + * @throws IllegalArgumentException if the cell is outside the board or occupied + */ + public void placeMark(int row, int col) { + if (isGameOver()) { + throw new IllegalStateException("Game is already over"); + } + if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) { + throw new IllegalArgumentException("Cell is outside the board"); + } + if (board[row][col] != EMPTY) { + throw new IllegalArgumentException("Cell is already occupied"); + } + board[row][col] = currentPlayer; + currentPlayer = opponent(currentPlayer); + } + + public char getWinner() { + for (int i = 0; i < SIZE; i++) { + if (isLine(board[i][0], board[i][1], board[i][2])) { + return board[i][0]; + } + if (isLine(board[0][i], board[1][i], board[2][i])) { + return board[0][i]; + } + } + if (isLine(board[0][0], board[1][1], board[2][2])) { + return board[0][0]; + } + if (isLine(board[0][2], board[1][1], board[2][0])) { + return board[0][2]; + } + return EMPTY; + } + + /** @return true if the board is full and nobody has won */ + public boolean isDraw() { + return getWinner() == EMPTY && isFull(); + } + + /** @return true if someone has won or the board is full */ + public boolean isGameOver() { + return getWinner() != EMPTY || isFull(); + } + + /** @return the mark of the player whose turn it is */ + public char getCurrentPlayer() { + return currentPlayer; + } + + /** @return a copy of the board, indexed {@code [row][col]} */ + public char[][] getBoard() { + char[][] copy = new char[SIZE][]; + for (int i = 0; i < SIZE; i++) { + copy[i] = board[i].clone(); + } + return copy; + } + + /** + * Finds an optimal move for the current player using negamax. Among + * equally good outcomes, quicker wins and slower losses are preferred. + * + * @return {@code {row, col}} of the best move + * @throws IllegalStateException if the game is already over + */ + public int[] bestMove() { + if (isGameOver()) { + throw new IllegalStateException("Game is already over"); + } + int bestScore = Integer.MIN_VALUE; + int[] best = {-1, -1}; + char player = currentPlayer; + for (int row = 0; row < SIZE; row++) { + for (int col = 0; col < SIZE; col++) { + if (board[row][col] != EMPTY) { + continue; + } + board[row][col] = player; + int score = -negamax(opponent(player)); + board[row][col] = EMPTY; + if (score > bestScore) { + bestScore = score; + best = new int[] {row, col}; + } + } + } + return best; + } + + /** Score of the position from the point of view of {@code player}, who is to move. */ + private int negamax(char player) { + if (getWinner() != EMPTY) { + // The previous mover just won, so the player to move has lost. + return -(countEmpty() + 1); + } + if (isFull()) { + return 0; + } + int best = Integer.MIN_VALUE; + for (int row = 0; row < SIZE; row++) { + for (int col = 0; col < SIZE; col++) { + if (board[row][col] == EMPTY) { + board[row][col] = player; + best = Math.max(best, -negamax(opponent(player))); + board[row][col] = EMPTY; + } + } + } + return best; + } + + private int countEmpty() { + int count = 0; + for (char[] row : board) { + for (char cell : row) { + if (cell == EMPTY) { + count++; + } + } + } + return count; + } + + private boolean isFull() { + return countEmpty() == 0; + } + + private static char opponent(char player) { + return player == X ? O : X; + } + + private static boolean isLine(char a, char b, char c) { + return a != EMPTY && a == b && b == c; + } +} diff --git a/src/test/java/com/thealgorithms/puzzlesandgames/ConnectFourTest.java b/src/test/java/com/thealgorithms/puzzlesandgames/ConnectFourTest.java new file mode 100644 index 000000000000..412551fdf1a4 --- /dev/null +++ b/src/test/java/com/thealgorithms/puzzlesandgames/ConnectFourTest.java @@ -0,0 +1,86 @@ +package com.thealgorithms.puzzlesandgames; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class ConnectFourTest { + + private static ConnectFour play(int... columns) { + ConnectFour game = new ConnectFour(); + for (int col : columns) { + game.dropDisc(col); + } + return game; + } + + @Test + void newGameStartsEmptyWithRedToMove() { + ConnectFour game = new ConnectFour(); + assertEquals(ConnectFour.RED, game.getCurrentPlayer()); + assertEquals(ConnectFour.EMPTY, game.getWinner()); + assertFalse(game.isGameOver()); + } + + @Test + void discFallsToBottomAndStacks() { + ConnectFour game = new ConnectFour(); + assertEquals(ConnectFour.ROWS - 1, game.dropDisc(3)); + assertEquals(ConnectFour.ROWS - 2, game.dropDisc(3)); + assertEquals(ConnectFour.YELLOW, game.getBoard()[ConnectFour.ROWS - 2][3]); + } + + @Test + void verticalWin() { + ConnectFour game = play(0, 1, 0, 1, 0, 1, 0); + assertEquals(ConnectFour.RED, game.getWinner()); + assertTrue(game.isGameOver()); + } + + @Test + void horizontalWin() { + ConnectFour game = play(0, 0, 1, 1, 2, 2, 3); + assertEquals(ConnectFour.RED, game.getWinner()); + } + + @Test + void diagonalWinBothDirections() { + assertEquals(ConnectFour.RED, play(0, 1, 1, 2, 3, 2, 2, 3, 6, 3, 3).getWinner()); + assertEquals(ConnectFour.RED, play(6, 5, 5, 4, 3, 4, 4, 3, 0, 3, 3).getWinner()); + } + + @Test + void yellowCanWin() { + ConnectFour game = play(0, 1, 0, 1, 0, 1, 6, 1); + assertEquals(ConnectFour.YELLOW, game.getWinner()); + } + + @Test + void fullColumnThrows() { + ConnectFour game = play(0, 0, 0, 0, 0, 0); + assertThrows(IllegalArgumentException.class, () -> game.dropDisc(0)); + } + + @Test + void invalidColumnThrows() { + ConnectFour game = new ConnectFour(); + assertThrows(IllegalArgumentException.class, () -> game.dropDisc(-1)); + assertThrows(IllegalArgumentException.class, () -> game.dropDisc(ConnectFour.COLS)); + } + + @Test + void moveAfterGameOverThrows() { + ConnectFour game = play(0, 1, 0, 1, 0, 1, 0); + assertThrows(IllegalStateException.class, () -> game.dropDisc(2)); + } + + @Test + void getBoardReturnsCopy() { + ConnectFour game = new ConnectFour(); + game.getBoard()[0][0] = ConnectFour.RED; + assertEquals(ConnectFour.EMPTY, game.getBoard()[0][0]); + } +} diff --git a/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java b/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java new file mode 100644 index 000000000000..9b126d858882 --- /dev/null +++ b/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java @@ -0,0 +1,109 @@ +package com.thealgorithms.puzzlesandgames; + +import org.junit.jupiter.api.Assertions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class TicTacToeTest { + + private static TicTacToe play(int[]... moves) { + TicTacToe game = new TicTacToe(); + for (int[] move : moves) { + game.placeMark(move[0], move[1]); + } + return game; + } + + @Test + void newGameStartsEmptyWithXToMove() { + TicTacToe game = new TicTacToe(); + assertEquals(TicTacToe.X, game.getCurrentPlayer()); + assertEquals(TicTacToe.EMPTY, game.getWinner()); + assertFalse(game.isGameOver()); + } + + @Test + void rowWin() { + TicTacToe game = play(new int[] {0, 0}, new int[] {1, 0}, new int[] {0, 1}, new int[] {1, 1}, new int[] {0, 2}); + assertEquals(TicTacToe.X, game.getWinner()); + assertTrue(game.isGameOver()); + } + + @Test + void columnWin() { + TicTacToe game = play(new int[] {0, 0}, new int[] {0, 1}, new int[] {1, 0}, new int[] {1, 1}, new int[] {2, 0}); + assertEquals(TicTacToe.X, game.getWinner()); + } + + @Test + void diagonalWins() { + TicTacToe main = play(new int[] {0, 0}, new int[] {0, 1}, new int[] {1, 1}, new int[] {0, 2}, new int[] {2, 2}); + assertEquals(TicTacToe.X, main.getWinner()); + + TicTacToe anti = play(new int[] {0, 2}, new int[] {0, 0}, new int[] {1, 1}, new int[] {0, 1}, new int[] {2, 0}); + assertEquals(TicTacToe.X, anti.getWinner()); + } + + @Test + void oCanWin() { + TicTacToe game = play(new int[] {0, 0}, new int[] {1, 0}, new int[] {0, 1}, new int[] {1, 1}, new int[] {2, 2}, new int[] {1, 2}); + assertEquals(TicTacToe.O, game.getWinner()); + } + + @Test + void draw() { + TicTacToe game = play(new int[] {0, 0}, new int[] {0, 1}, new int[] {0, 2}, new int[] {1, 1}, new int[] {1, 0}, new int[] {1, 2}, new int[] {2, 1}, new int[] {2, 0}, new int[] {2, 2}); + assertTrue(game.isDraw()); + assertTrue(game.isGameOver()); + assertEquals(TicTacToe.EMPTY, game.getWinner()); + } + + @Test + void invalidMovesThrow() { + TicTacToe game = play(new int[] {1, 1}); + assertThrows(IllegalArgumentException.class, () -> game.placeMark(1, 1)); + assertThrows(IllegalArgumentException.class, () -> game.placeMark(-1, 0)); + assertThrows(IllegalArgumentException.class, () -> game.placeMark(0, 3)); + } + + @Test + void moveAfterGameOverThrows() { + TicTacToe game = play(new int[] {0, 0}, new int[] {1, 0}, new int[] {0, 1}, new int[] {1, 1}, new int[] {0, 2}); + assertThrows(IllegalStateException.class, () -> game.placeMark(2, 2)); + assertThrows(IllegalStateException.class, game::bestMove); + } + + @Test + void getBoardReturnsCopy() { + TicTacToe game = new TicTacToe(); + game.getBoard()[0][0] = TicTacToe.X; + assertEquals(TicTacToe.EMPTY, game.getBoard()[0][0]); + } + + @Test + void bestMoveTakesWinningMove() { + TicTacToe game = play(new int[] {0, 0}, new int[] {1, 0}, new int[] {0, 1}, new int[] {1, 1}); + Assertions.assertArrayEquals(new int[] {0, 2}, game.bestMove()); + } + + @Test + void bestMoveBlocksOpponent() { + TicTacToe game = play(new int[] {0, 0}, new int[] {1, 1}, new int[] {0, 1}); + Assertions.assertArrayEquals(new int[] {0, 2}, game.bestMove()); + } + + @Test + void perfectPlayAlwaysDraws() { + TicTacToe game = new TicTacToe(); + while (!game.isGameOver()) { + int[] move = game.bestMove(); + game.placeMark(move[0], move[1]); + } + assertTrue(game.isDraw()); + } +} From ecbce0e89e712db360e27daa25f386f8600b6869 Mon Sep 17 00:00:00 2001 From: aniketShukla Date: Mon, 23 Nov 2026 11:59:42 +0530 Subject: [PATCH 2/2] style: fix formatting in game implementations --- .../java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java b/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java index 9b126d858882..53c5b44a5c1b 100644 --- a/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java +++ b/src/test/java/com/thealgorithms/puzzlesandgames/TicTacToeTest.java @@ -1,12 +1,11 @@ package com.thealgorithms.puzzlesandgames; -import org.junit.jupiter.api.Assertions; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TicTacToeTest {