Connect Four Game Implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-07-11

Problem Statement

Design and implement the Connect Four game in an object-oriented way. Connect Four is a two-player strategy game where players drop colored discs into a vertical grid. The first player to connect four consecutive discs horizontally, vertically, or diagonally wins. If the board fills up without a winner, the game ends in a draw.


✅ Functional Requirements

1.<span></span>Game Setup
2.<span></span>Initialize a 6x7 grid (6 rows, 7 columns).
3.<span></span>Two players: Player 1 (e.g., 🔴), Player 2 (e.g., 🟡).
4.<span></span>Gameplay
5.<span></span>Players take turns choosing a column to drop their disc.
6.<span></span>Discs fall to the lowest available row in that column.
7.<span></span>Prevent dropping into a full column.
8.<span></span>Win & Draw Conditions
9.<span></span>Check after every move if a player has aligned 4 in a row:
10.<span></span>Horizontally
11.<span></span>Vertically
12.<span></span>Diagonally (both directions)
13.<span></span>If all cells are filled and no winner, declare a draw.
14.<span></span>Game State Management
15.<span></span>Keep track of turns.
16.<span></span>Display the board after each move.
17.<span></span>Announce winner or draw.


⚙️ Non-Functional Requirements

1.<span></span>Should follow object-oriented principles (encapsulation, separation of concerns).
2.<span></span>Must be extendable (e.g., allow custom board sizes).
3.<span></span>Should handle invalid input gracefully (e.g., choosing a full column).


🔐 Constraints

1.<span></span>Exactly 2 players.
2.<span></span>Board size defaults to 6x7, but should be configurable.
3.<span></span>Moves are sequential, no simultaneous actions.


🧱 Key Classes to Model

1.<span></span>Game – Controls game loop, player turns, and win/draw detection.
2.<span></span>Board – Manages grid state, placing discs, and checking validity.
3.<span></span>Player – Holds player info (ID, name, disc color).
4.<span></span>Disc (optional) – Represents a disc placed by a player.


🧪 Example Gameplay Flow

<div><div><br /></div><div>Game starts with empty 6x7 board.</div><div><br /></div><div>Player 1 (Red) chooses column 3 → Disc falls to row 6. </div><div>Player 2 (Yellow) chooses column 4 → Disc falls to row 6. </div><div>Player 1 (Red) chooses column 3 → Disc falls to row 5. </div><div>...</div><div>Game continues until:</div><div>- Player 1 wins by 4 in a row vertically, OR</div><div>- Player 2 wins by 4 in a row diagonally, OR</div><div>- Board is full → Draw.</div></div>


👉 This LLD problem evaluates:

1.<span></span>OOP design & modeling (classes, interactions).
2.<span></span>Game state management.
3.<span></span>Algorithmic logic (win detection).
4.<span></span>Extensibility & clean abstractions.


Solution

Comments