KatInterview

Build a Tic-Tac-Toe Game Engine with Move Validation

Data Structure DesignModel answer
MediumModel answerData Structure Designstate-machinegame-logicobject-oriented-design

Last 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

  1. Player X always moves first
  2. Players alternate turns after each successful move
  3. 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
  4. A player wins by placing three marks in any row, column, or diagonal
  5. 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