Design a core engine for Connect 4 Game

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-12-02

Problem Statement

Design the core engine for a Connect 4 game. Focus on OOP modeling, modularity, game rules enforcement, and win condition checking. No UI is required — this is purely the backend game logic.


Functional Requirements


1.Board Management
•Initialize a 6x7 grid (6 rows, 7 columns).
•Place tokens in a column; tokens fall to the lowest available row.
2.Players
•Support 2 players (could be extended to more).
•Each player has a unique token/color.
3.Game Mechanics
•Players take turns dropping tokens in columns.
•Validate moves: column must not be full.
•Track current player’s turn.
4.Win & Draw Conditions
•Check for 4 consecutive tokens: horizontally, vertically, diagonally (both directions).
•Detect draw when board is full without a winner.
5.Optional Features
•Undo/redo moves.
•Score tracking across multiple games.
•AI player logic.


Non-Functional Requirements


•Performance: Fast win/draw checking after each move.
•Extensibility: Ability to add AI, variable board size, or custom win conditions.
•Modularity: Separate classes for board, player, and game engine.


Edge Cases & Constraints


•Invalid column input → handle gracefully.
•Full column → prevent token placement.
•Multiple win conditions in the same move → game ends as soon as the first win is detected.
•Undo/redo → must maintain move history and board state.


Design Hints


•Key Classes / Interfaces:
•Game → manages game flow, players, and current turn.
•Board → maintains the 2D grid and provides methods to place tokens.
•Player → stores player information and token type.
•Move → represents a player move (row, column, token).
•GameEngine → enforces rules, checks for wins/draws, and updates board.
•Data Structures:
•2D Array (6x7) → board representation.
•Stack of Moves → for optional undo/redo functionality.
•Design Patterns:
•Command Pattern → optional, for undo/redo support.
•Observer Pattern → optional, notify UI or other components of game state changes.


Example Flow


1.Player A drops a token in column 3 → board updated at the lowest empty row.
2.GameEngine checks for 4 consecutive tokens → no win yet.
3.Player B drops a token in column 4 → board updated.
4.Player A continues → eventually 4 tokens in a row detected → Player A wins.


Evaluation Areas


•Correct board management and move validation.
•Efficient win/draw detection logic.
•Clean OOP modeling of players, board, moves, and game engine.
•Extensibility for undo/redo, AI, and custom rules.


This LLD problem tests OOP design, 2D array manipulation, game rule implementation, and optional undo/redo mechanics suitable for a Connect 4 game engine.

Solution

Comments