Implement Connect4 Game
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-11-13
Problem Statement
Connect4 is a classic two-player board game where players take turns dropping colored discs into a vertical grid. The first player to form a line of four discs in a row (horizontally, vertically, or diagonally) wins the game. If the grid is completely filled and no player has connected four, the game ends in a draw.
You are asked to design and implement the core game engine for Connect4 focusing on clean class design, extensibility, and correctness.
Functional Requirements
1.Board Setup
•Default board size: 6 rows × 7 columns.
•Should support custom board sizes (rows, columns).
2.Players
•Two players (Player 1 = Red, Player 2 = Yellow by default).
•Turn-based play.
3.Game Rules
•A player chooses a column and drops a disc → it occupies the lowest available slot in that column.
•Validate moves (reject if column is full).
•Detect win condition: four consecutive discs in row, column, or diagonal.
•Detect draw (when board is full and no winner).
4.Game Flow
•Alternate turns between players.
•Display board after each move.
•Declare winner/draw at end.
Non-Functional Requirements
•Clean OOP design (Board, Player, GameController, etc.).
•Extensibility → allow variations like different board sizes, AI opponent, or more than 2 players.
•Testability → easy to unit test win/draw detection logic.
•Concurrency (optional) → support multiple games in parallel sessions.
Example Scenarios
•Player 1 drops disc in column 3 → disc goes to bottom-most empty cell.
•Game detects Player 2 wins with diagonal sequence.
•Board fills up with no winner → game outputs Draw.
Design Hints for Interview
•Classes to consider:
•Board → maintains grid state.
•Player → stores player ID, disc color.
•GameController → orchestrates gameplay, alternates turns, validates moves.
•WinChecker (optional) → encapsulates win detection logic.
•Think about:
•How to represent board internally (int[][], char[][], or enums).
•How to efficiently check for win after each move.
•How to handle invalid moves.
•How to extend to support AI or multiple players.