Design and Implement Connect Four with Game Logic and State Management
Data Structure DesignModel answerLast 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
- 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).
- 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.
- Win Condition: The game ends immediately when a player places four of their tokens in an unbroken line horizontally, vertically, or diagonally.
- Draw Condition: The game ends in a tie if all 42 spaces are filled and neither player has formed a line of four.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
A robust implementation of Connect Four relies on two core aspects: clean state separation and an optimized win-checking procedure.
Instead of re-scanning all 42 cells on every turn—which would require checking dozens of potential 4-in-a-row sequences—we only need to inspect the lines intersecting the last placed token. A single token can complete a winning line horizontally, vertically, or along either of the two diagonal axes.
Key Data Structures
- Board Representation: A 2D array of size
6 × 7initialized tonull(or0). Let row0be the top row and row5be the bottom row. - Column Heights / Next Available Row: An array
columnHeightsof size 7, tracking the lowest open row index for each column. - Game Status: An enum or string tracking state:
'IN_PROGRESS','PLAYER_1_WIN','PLAYER_2_WIN', or'DRAW'.
Win Detection Strategy
After placing a disc at (row, col) for currentPlayer:
Check four directions relative to (row, col):
- Horizontal: Left
(0, -1)and Right(0, 1) - Vertical: Down
(1, 0)(Up is not strictly necessary since a dropped piece lands on top, but checking both directions standardizes the algorithm) - Positive Diagonal ( / ): Bottom-Left
(1, -1)and Top-Right(-1, 1) - Negative Diagonal ( \ ): Top-Left
(-1, -1)and Bottom-Right(1, 1)
For each axis, step outward in both opposing directions while consecutive cells match currentPlayer. If count >= 4, the current player wins.
Implementation (Python)
class ConnectFour:
ROWS = 6
COLS = 7
def __init__(self):
# 6 rows x 7 columns grid, initialized to None
self.board = [[None for _ in range(self.COLS)] for _ in range(self.ROWS)]
# Track open row from bottom up (row 5 is bottom, row 0 is top)
self.available_row = [self.ROWS - 1 for _ in range(self.COLS)]
self.current_player = 1 # 1 or 2
self.status = "IN_PROGRESS" # IN_PROGRESS, PLAYER_1_WIN, PLAYER_2_WIN, DRAW
self.moves_count = 0
def make_move(self, col: int) -> bool:
"""
Executes a turn for the current player in the specified column.
Returns True if the move was valid and executed, False otherwise.
"""
if self.status != "IN_PROGRESS":
return False # Game is already finished
if col < 0 or col >= self.COLS or self.available_row[col] < 0:
return False # Invalid column index or column is full
row = self.available_row[col]
self.board[row][col] = self.current_player
self.available_row[col] -= 1
self.moves_count += 1
if self._check_win(row, col):
self.status = f"PLAYER_{self.current_player}_WIN"
elif self.moves_count == self.ROWS * self.COLS:
self.status = "DRAW"
else:
# Switch turn
self.current_player = 2 if self.current_player == 1 else 1
return True
def _check_win(self, last_row: int, last_col: int) -> bool:
player = self.board[last_row][last_col]
# Directions defined as (delta_row, delta_col) pairs for opposite directions
axes = [
[(0, -1), (0, 1)], # Horizontal
[(1, 0), (-1, 0)], # Vertical
[(1, -1), (-1, 1)], # Positive Diagonal (/)
[(-1, -1), (1, 1)] # Negative Diagonal (\)
]
for dir1, dir2 in axes:
consecutive = 1 # Count the newly placed piece itself
# Count matching pieces in first direction
consecutive += self._count_consecutive(last_row, last_col, dir1[0], dir1[1], player)
# Count matching pieces in opposite direction
consecutive += self._count_consecutive(last_row, last_col, dir2[0], dir2[1], player)
if consecutive >= 4:
return True
return False
def _count_consecutive(self, r: int, c: int, dr: int, dc: int, player: int) -> int:
count = 0
r += dr
c += dc
while 0 <= r < self.ROWS and 0 <= c < self.COLS and self.board[r][c] == player:
count += 1
r += dr
c += dc
return count
Complexity Analysis
- Time Complexity:
make_move: $\mathcal{O}(1)$. The algorithm explores at most 3 cells in 8 ray directions starting from the dropped piece. At most $3 \times 8 = 24$ cells are inspected during win checking.
- Space Complexity:
- $\mathcal{O}(R \times C)$ to store the board state, which is $\mathcal{O}(1)$ given fixed dimensions of $6 \times 7$.
Common Edge Cases & Handling
- Placing a piece in a full column: Handled by checking
available_row[col] < 0before making state mutations. - Placing a piece in the middle of a winning line: Solved by stepping in both directions along each axis starting from the newly dropped token.
- Board boundary overruns: Handled by bounds-checking
0 <= r < ROWSand0 <= c < COLSduring ray scanning. - Draw condition: Validated by checking if
moves_count == 42when no winner is detected on the current turn.