KatInterview

Design and Implement Connect Four with Game Logic and State Management

Data Structure DesignModel answer
MediumModel answerData Structure DesignArraysGame DesignState Management

Last updated

Build a complete two-player Connect Four game on a 6x7 grid, including drop mechanics, win/draw state evaluation, edge-case prevention, and modular state architecture.

Design and implement the core engine and state management for a classic two-player Connect Four game on a standard grid (6 rows by 7 columns).

Rules & Mechanics

  1. Board Layout: The board consists of 6 rows (0 to 5) and 7 columns (0 to 6). Row 0 represents the top row, and row 5 represents the bottom row (or vice versa, provided your indexing is explicit).
  2. Turn Mechanics: Player 1 ('Red') and Player 2 ('Yellow') take alternating turns. A player selects a column (0–6), and their token occupies the lowest currently available cell in that column.
  3. Win Condition: The game ends immediately when a player places four of their tokens in an unbroken line horizontally, vertically, or diagonally.
  4. Draw Condition: The game ends in a tie if all 42 spaces are filled and neither player has formed a line of four.
  5. Move Validation: Attempting to play into a fully occupied column or making a move after the game has ended must be rejected without affecting the game state.

Expected Responsibilities

  • Implement a data model that accurately tracks the board configuration and current game status (e.g., IN_PROGRESS, PLAYER_1_WIN, PLAYER_2_WIN, DRAW).
  • Write an efficient win-checking algorithm that evaluates the board after every move.
  • Structure your logic so that game state evaluation is decoupled from UI rendering or input mechanisms.

Hints

Hint 1

Rather than checking the entire board for a win after every move, check only the straight lines passing through the cell where the most recent token was dropped.

Hint 2

Representing the grid as a 2D array (6x7) or 7 separate column stacks can simplify the gravity placement step.

Hint 3

Be mindful of grid boundary checks when counting matching tokens in diagonal directions.