Build a Tic-Tac-Toe Game Engine with Move Validation
Data Structure DesignModel answerLast updated
Design and implement a class that tracks board state, validates moves, detects winners, and enforces turn-based gameplay for a 3×3 grid game.
Problem
Design a game engine that manages the mechanics of a 3×3 grid-based two-player game where players alternate placing marks until someone completes a line or the grid fills completely.
Your implementation should encapsulate all gameplay rules without requiring a user interface. The engine must track whose turn it is, reject illegal moves, and determine when the game concludes.
Interface
Implement a class with the following methods:
class TicTacToe:
def __init__(self):
"""Create a new game with an empty 3×3 grid."""
pass
def make_move(self, row, col):
"""
Attempt to place the current player's mark at (row, col).
Returns True if the move succeeds, False if it's invalid.
"""
pass
def get_winner(self):
"""
Returns:
- 'X' if X completed a line
- 'O' if O completed a line
- 'Draw' if the grid is full with no winner
- None if the game is still in progress
"""
pass
def reset(self):
"""Clear the board and restart from the beginning."""
pass
Rules
- Player X always moves first
- Players alternate turns after each successful move
- A move fails (returns False) if:
- The coordinates fall outside the 3×3 grid
- The chosen cell already contains a mark
- The game has already ended
- A player wins by placing three marks in any row, column, or diagonal
- The game ends in a draw when all nine cells are filled without a winner
Examples
game = TicTacToe()
game.make_move(1, 1) # True - X places at center
game.make_move(1, 1) # False - cell occupied
game.make_move(0, 0) # True - O places at top-left
After moves at (0,0), (1,0), (0,1), (2,2), (0,2) by X, O, X, O, X respectively, get_winner() returns 'X' because the top row is complete.
Constraints
- Grid size is fixed at 3×3
- Row and column indices are zero-based (0, 1, or 2)
- Moves outside this range should be rejected, not raise exceptions
Hints
Hint 1
Store the board as a 2D list and track whose turn it is along with the current outcome
Hint 2
Only check for a win along the row, column, and diagonals that pass through the cell just played—you never need to scan the entire board
Hint 3
Cache the winner once determined so subsequent move attempts can immediately return False without re-checking
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem evaluates your ability to maintain consistent internal state and encapsulate business logic cleanly. The core challenge is ensuring that every state transition preserves correctness: invalid moves must leave the board unchanged, and win detection must be accurate and efficient.
State representation
Track four pieces of information:
- board: A 3×3 nested list, using
Nonefor empty cells and'X'or'O'for marks - turn: The current player (
'X'or'O') - moves: Count of successful placements (used to detect draws)
- winner: Cached result—
Noneduring play, then'X','O', or'Draw'
Keeping winner as an explicit field gives you a single source of truth for "has the game ended?" and makes get_winner() constant-time.
Move validation sequence
Each move attempt follows a strict order:
- Guard conditions: Check if the game is over, coordinates are out of bounds, types are invalid, or the cell is occupied. If any condition fails, return
Falseimmediately without changing state. - Apply the move: Place the current player's mark and increment the move counter.
- Evaluate the outcome: Check if this move completed a winning line. If so, record the winner. Otherwise, if all nine cells are filled, record a draw.
- Advance the turn: Toggle to the other player.
The key insight: only the player who just moved can have formed a new winning line, and only along lines passing through the cell they played. You never need to scan the entire board. Check the row, the column, and—if applicable—the two diagonals. This keeps each move O(1).
Why this works
- A winning line must include the most recent move, since all other cells were already in place and no line was complete before.
- Checking for a win before checking for a draw ensures that a move filling the ninth cell and completing a line is correctly classified as a win.
- Returning
Falsebefore mutating state prevents bugs where a rejected move inadvertently toggles the turn or corrupts the board.
Edge cases to handle
- Occupied cell: Return
Falsewithout changing the turn - Out-of-range indices: Explicitly check bounds (negative indices are valid Python syntax but semantically wrong here)
- Move after game ends: Once
winneris set, all further moves fail - Non-integer input: Guard with type checks to avoid exceptions
- Ninth-move win: A move that simultaneously fills the board and completes a line should be reported as a win, not a draw
- Center cell: (1,1) lies on both diagonals—check both
Complexity
- Time: O(1) per move—at most four lines of three cells each are checked
- Space: O(1)—the board is always nine cells
Solution
class TicTacToe:
SIZE = 3
def __init__(self):
self.reset()
def reset(self):
n = self.SIZE
self.board = [[None] * n for _ in range(n)]
self.turn = 'X'
self.moves = 0
self.winner = None
def make_move(self, row, col):
n = self.SIZE
# Guard: reject if game is over or input is invalid
if self.winner is not None:
return False
if not isinstance(row, int) or not isinstance(col, int):
return False
if not (0 <= row < n and 0 <= col < n):
return False
if self.board[row][col] is not None:
return False
# Apply move
player = self.turn
self.board[row][col] = player
self.moves += 1
# Evaluate outcome: check only lines through (row, col)
if self._check_win(player, row, col):
self.winner = player
elif self.moves == n * n:
self.winner = 'Draw'
# Advance turn
self.turn = 'O' if player == 'X' else 'X'
return True
def get_winner(self):
return self.winner
def _check_win(self, player, row, col):
n = self.SIZE
board = self.board
# Check row
if all(board[row][c] == player for c in range(n)):
return True
# Check column
if all(board[r][col] == player for r in range(n)):
return True
# Check main diagonal (if applicable)
if row == col and all(board[i][i] == player for i in range(n)):
return True
# Check anti-diagonal (if applicable)
if row + col == n - 1 and all(board[i][n - 1 - i] == player for i in range(n)):
return True
return False
Implementation notes
- Delegating from
__init__toreset()ensures the initial state is defined in one place, preventing inconsistency. - The type check for integers catches string indices like
"1"or floats like1.5, thoughboolvalues (which areintsubclasses) still pass—this is harmless since they map to 0 and 1.
Common mistakes
- Toggling turn on failed moves: This hands control to the wrong player.
- Rescanning the entire board: Unnecessary and slower; checking only affected lines is sufficient.
- Forgetting negative indices: In Python,
board[-1]accesses the last row without error, so explicit bounds checks are required. - Checking draw before win: A simultaneous ninth-move win would be misclassified as a draw.
Extensions
N×N board: Accept size as a constructor parameter. The line-checking approach scales to O(N) per move. For O(1) per move, maintain running sums per row, column, and diagonal: add +1 for X and −1 for O, then check if any updated counter reaches ±N.
Undo moves: Maintain a stack of (row, col, player) tuples. Pop to reverse the last move, clear the cell, decrement moves, restore the turn, and reset winner to None.
Variable win condition: For "K in a row on N×N", scan outward from the last move in all four directions (horizontal, vertical, two diagonals) counting consecutive marks, which takes O(K) time.