Full-Stack Tic-Tac-Toe Engine and Backend Service

Medium · Software Engineering Fundamentals · Backend Engineer · Other

Problem Statement

In this AI-assisted engineering exercise, you will build a two-player Tic-Tac-Toe domain engine from scratch and expand it into a thread-safe backend service capable of powering a browser client. Throughout an interview session of this style, you are evaluated both on code correctness and on engineering discipline when collaborating with AI coding assistants: defining contracts up front, separating domain logic from transport/UI layers, catching subtle generated bugs, and proving behavior with regression tests.

Implement two layers in Python following the exact class and exception contracts in starter.py:

  1. Pure Domain Rules (InvalidMove and Game)

    • The 3 x 3 grid is stored in Game.board as a flat 9-element list of strings ("", "X", or "O") mapped by index = 3 * row + col. Winning triples are listed in LINES.
    • A fresh Game() starts with board = [""] * 9, turn = "X", status = "in_progress", winner = None, and moves = [] (recording accepted (player, row, col) tuples in play order).
    • game.play(player, row, col) validates a proposed move in strict priority order and raises InvalidMove(code) without modifying any game attribute when a check fails:
      1. "game_over" — self.status is already "won" or "draw".
      2. "bad_player" — player is neither "X" nor "O".
      3. "not_your_turn" — player does not match self.turn.
      4. "out_of_bounds" — row or col is not a strict int (bool values like True/False, floats like 1.0, strings, and None must all be rejected) or falls outside 0..2.
      5. "occupied" — self.board[3 * row + col] already holds "X" or "O".
    • When all checks pass, record the mark on board, append (player, row, col) to moves, and evaluate end-of-game conditions:
      • If player now occupies all three cells of any row, column, or diagonal in LINES, set status = "won", winner = player, and turn = None. (Check win before draw so completing a line on the 9th move counts as "won".)
      • Else if len(moves) == 9, set status = "draw", winner = None, and turn = None.
      • Otherwise switch turn to the other player ("X" <-> "O").
  2. Authoritative Backend Store (ApiError and GameService)

    • GameService manages games in memory under a lock so concurrent requests cannot race. Created games receive sequential IDs "g1", "g2", "g3", and so on.
    • create_game(), get_game(game_id), and make_move(...) each return a fresh copy snapshot dictionary: python { "id": str, # e.g. "g1" "board": List[List[str]],# 3 rows of 3 cell strings "turn": Optional[str], # "X", "O", or None "status": str, # "in_progress", "won", or "draw" "winner": Optional[str], # "X", "O", or None "version": int, # len(game.moves) } Mutating a returned snapshot in caller code must never corrupt stored server state.
    • get_game(game_id) raises ApiError(404, "game_not_found") if game_id does not exist.
    • make_move(game_id, player, row, col, expected_version) enforces optimistic concurrency and idempotent retries in strict priority order:
      1. Raise ApiError(404, "game_not_found") if game_id is unknown.
      2. Raise ApiError(400, "bad_version") if expected_version is not a strict int (rejecting bool, float, str, None).
      3. Let current_version = len(game.moves). If expected_version != current_version:
        • Idempotent retry: if 0 <= expected_version < current_version, row and col are strict int values in 0..2, and game.moves[expected_version] == (player, row, col), return the current state snapshot without error.
        • Otherwise raise ApiError(409, "version_conflict").
      4. Call game.play(player, row, col); if InvalidMove(code) is raised, translate it into ApiError(422, code) without altering server state. Otherwise return the updated snapshot.

Examples

Example 1

Input:

game = Game()
game.play("X", 0, 0)
game.play("O", 0, 2)
game.play("X", 0, 1)
game.play("O", 1, 1)
# Attempt an occupied cell, then continue:
# game.play("X", 1, 1) -> raises InvalidMove("occupied")
game.play("X", 2, 2)
game.play("O", 2, 0)
# Attempt a move after a win:
# game.play("X", 1, 0) -> raises InvalidMove("game_over")

Output:

game.board  == ["X", "X", "O", "", "O", "", "O", "", "X"]
game.status == "won"
game.winner == "O"
game.turn   == None
len(game.moves) == 6

Explanation: "X" attempting (1, 1) on move 5 raises InvalidMove("occupied") and leaves turn = "X". After "X" plays (2, 2), "O" plays (2, 0) to complete the anti-diagonal (0, 2) - (1, 1) - (2, 0). Any subsequent call to play immediately raises InvalidMove("game_over") even when targeting an empty square like (1, 0).

Example 2

Input:

game = Game()
for player, r, c in [
    ("X", 0, 2), ("O", 0, 0),
    ("X", 1, 0), ("O", 0, 1),
    ("X", 1, 2), ("O", 1, 1),
    ("X", 2, 1), ("O", 2, 0),
    ("X", 2, 2),
]:
    game.play(player, r, c)

Output:

game.board  == ["O", "O", "X", "X", "O", "X", "O", "X", "X"]
game.status == "won"
game.winner == "X"
game.turn   == None

Explanation: Through move 8 no three-in-a-row exists. Move 9 places "X" at (2, 2), simultaneously filling all 9 cells and completing the right column (0, 2) - (1, 2) - (2, 2). Because win detection runs before the 9-move draw check, the result is "won" for "X", not "draw".

Example 3

Input:

svc = GameService()
s0 = svc.create_game()
s1 = svc.make_move("g1", "X", 0, 1, 0)
s1_dup = svc.make_move("g1", "X", 0, 1, 0)   # duplicate network retry
s2 = svc.make_move("g1", "O", 2, 1, 1)
# svc.make_move("g1", "O", 1, 2, 1)          -> raises ApiError(409, "version_conflict")

Output:

s0["id"] == "g1" and s0["version"] == 0
s1 == s1_dup
s1["board"] == [["", "X", ""], ["", "", ""], ["", "", ""]] and s1["version"] == 1
s2["board"] == [["", "X", ""], ["", "", ""], ["", "O", ""]] and s2["version"] == 2

Explanation: s1_dup repeats the exact ("X", 0, 1) move originally committed at version = 0, so GameService treats it as an idempotent retry and returns the version = 1 state. Once "O" plays (2, 1) at version = 1 (advancing to version = 2), a stale request proposing a different move ("O", 1, 2) at expected_version = 1 raises ApiError(409, "version_conflict").

Constraints

  • Board coordinates row and col must be strict Python int instances (type(v) is int) satisfying 0 <= v <= 2.
  • expected_version must be a strict Python int instance (type(expected_version) is int).
  • Valid player identifiers are "X" and "O", with "X" always moving first on a new board.
  • Invalid calls to Game.play or GameService.make_move must leave all stored board cells, move history, turn, and version counters completely unchanged.
  • Use only the Python standard library (threading for synchronization).

Step-by-step walkthrough

  1. Clarify requirements and plan how to work with the AI

    In an AI-assisted build round, the interviewer grades how you steer, review, and verify the AI just as heavily as the finished code. Before writing or generating a single line, ask clarifying questions (or state explicit defaults if left up to you):

    • Where are the two players? Assume two browsers talking to one shared backend (same-screen play is then just the special case where one browser sends both "X" and "O" moves).
    • What persistence is expected? Games live on the server so refreshing the browser restores the board; surviving a server restart would swap the in-memory dictionary for SQLite or Postgres.
    • What counts as "polished" here? Rock-solid rule enforcement, clear error codes, automated unit/regression tests, and clean status feedback come before visual polish.
    • How will we use the AI? We write the specification and edge-case checklist first, ask the AI for small isolated modules (pure rules -> backend service -> thin UI), review every line against our spec, and never paste proprietary secrets.

    Building in small, verified layers ensures that when something breaks, we immediately know which layer caused it.

  2. Write the exact rule specification before prompting

    Prompting an AI with "write tic-tac-toe" invites subtle bugs because every ambiguous edge case is left to chance. Instead, write down the exact input-to-output contract before prompting:

    Condition (checked in this exact order)        Outcome
    ---------------------------------------------  ------------------------------------------------
    1. Game status is already "won" or "draw"      Raise InvalidMove("game_over"); change nothing
    2. player is neither "X" nor "O"               Raise InvalidMove("bad_player"); change nothing
    3. player != current turn                      Raise InvalidMove("not_your_turn"); change nothing
    4. row or col not a strict int in 0..2         Raise InvalidMove("out_of_bounds"); change nothing
    5. Target square is non-empty                  Raise InvalidMove("occupied"); change nothing
    6. Valid move                                  Write mark; check WIN first, then DRAW (9 moves),
                                                   otherwise flip turn ("X" <-> "O")
    

    Give that specification directly to the AI, and write (or inspect every assertion of) the test suite yourself — if the AI writes both the code and the tests in one shot, both often share the exact same blind spot! When reviewing the AI's draft, scan specifically for five classic bugs: 1. Checking for a draw (9 moves) before checking for a win, mislabeling a 9th-move victory as a draw. 2. Forgetting to reject moves once status != "in_progress". 3. Using isinstance(row, int), which accepts True and False because bool is a subclass of int in Python (True == 1, False == 0). 4. Checking board[3 * row + col] before bounds checking, where row = -1 silently reads from the end of a Python list! 5. Mutating board or turn before all checks pass, leaving partial state after an exception.

  3. Part 1: Implement pure, UI-free game rules

    We store the 3 x 3 board as a flat 9-element list indexed by 3 * row + col and predefine all 8 three-in-a-row index triples in LINES:

    (row, col) coordinates        Flat index = 3 * row + col
     (0,0) | (0,1) | (0,2)              0 | 1 | 2
    -------+-------+-------            ---+---+---
     (1,0) | (1,1) | (1,2)     ===>     3 | 4 | 5
    -------+-------+-------            ---+---+---
     (2,0) | (2,1) | (2,2)              6 | 7 | 8
    
    8 winning LINES:
      Rows: (0,1,2), (3,4,5), (6,7,8)   Cols: (0,3,6), (1,4,7), (2,5,8)   Diags: (0,4,8), (2,4,6)
    

    Notice how Game has zero HTTP, JSON, or UI imports — you can instantiate it in a millisecond inside a unit test.

    def _is_index(value) -> bool:
        """Return True only for strict ints 0, 1, or 2 (rejecting bools like True and floats like 1.0)."""
        # Use `type(value) is int` because `bool` subclasses `int` in Python (`isinstance(True, int)` is True)
        return type(value) is int and 0 <= value < 3
    
    
    class Game:
        """Part 1: pure Tic-Tac-Toe domain rules with zero UI, HTTP, or I/O dependencies."""
    
        def __init__(self):
            # board: 9 cell marks ("", "X", or "O") indexed by 3 * row + col
            self.board: List[str] = [""] * 9
            # turn: player expected next ("X" or "O"), or None once the game ends
            self.turn: Optional[str] = "X"
            # status: "in_progress", "won", or "draw"
            self.status: str = "in_progress"
            # winner: "X", "O", or None
            self.winner: Optional[str] = None
            # moves: chronological history of accepted (player, row, col) tuples
            self.moves: List[Tuple[str, int, int]] = []
    
        def check_move(self, player, row, col) -> None:
            """Validate a proposed move in strict priority order without mutating state."""
            if self.status != "in_progress":
                raise InvalidMove("game_over")
            if player not in ("X", "O"):
                raise InvalidMove("bad_player")
            if player != self.turn:
                raise InvalidMove("not_your_turn")
            if not _is_index(row) or not _is_index(col):
                raise InvalidMove("out_of_bounds")
            cell_index = 3 * row + col
            if self.board[cell_index] != "":
                raise InvalidMove("occupied")
    
        def play(self, player, row, col) -> None:
            """Apply a move, or raise InvalidMove(code) leaving the game completely unchanged."""
            # Validate every rule first so a failed move never half-updates the board or turn
            self.check_move(player, row, col)
    
            cell_index = 3 * row + col
            self.board[cell_index] = player
            self.moves.append((player, row, col))
    
            # Check win BEFORE draw: the 9th move can fill the last square and complete a 3-in-a-row!
            if self._has_line(player):
                self.status = "won"
                self.winner = player
                self.turn = None
            elif len(self.moves) == 9:
                self.status = "draw"
                self.turn = None
            else:
                self.turn = "O" if player == "X" else "X"
    
        def _has_line(self, player: str) -> bool:
            """Return True if `player` occupies all three squares of any row, column, or diagonal."""
            for a, b, c in LINES:
                if self.board[a] == player and self.board[b] == player and self.board[c] == player:
                    return True
            return False
    
  4. Verify Part 1 with targeted edge-case tests

    Before touching HTTP or HTML, lock down Game with tests aimed right at the failure modes from our checklist: - Wins across all 8 lines (3 rows, 3 columns, 2 diagonals) for "X" and a win for "O" (such as Example 1's anti-diagonal (0,2)-(1,1)-(2,0)). - A full-board draw (X O X / X O O / O X X). - A win on the 9th (final) square (Example 2), where move #9 fills (2, 2) and completes the right column (0,2)-(1,2)-(2,2):

    Moves 1..8:               Move 9: X plays (2, 2)
      O | O | X                 O | O | X
     ---+---+---               ---+---+---
      X | O | X      ===>       X | O | X     -> board is full AND right column X-X-X is complete!
     ---+---+---               ---+---+---       Must report status="won", winner="X" (NOT "draw")
      O | X | .                 O | X | X
    
    • Every invalid move (not_your_turn, bad_player, negative/out-of-range/bool/float/None coordinates, occupied, and game_over after both a win and a draw), asserting the board and turn did not budge.
    • A randomized differential test comparing 200 random games against a separate 3 x 3 nested-loop grid scanner.
    def test_sample_2():
        """Example 2: 9th move fills the board and completes right column for X (won, not draw)."""
        game = Game()
        _play_all(
            game,
            [(0, 2), (0, 0), (1, 0), (0, 1), (1, 2), (1, 1), (2, 1), (2, 0), (2, 2)],
        )
        _check(game.board, ["O", "O", "X", "X", "O", "X", "O", "X", "X"])
        _check([game.status, game.winner, game.turn], ["won", "X", None])
    
  5. Part 2: Make the backend the sole authority

    Any user can bypass browser JavaScript with curl, so the backend GameService acts as the single source of truth (the sole authority storing game state and deciding move legality). Three compact endpoints handle the entire lifecycle:

    POST /games             -> 201 {id, board: 3x3, turn, status, winner, version: 0}
    GET  /games/{id}        -> 200 state | 404 {"error": "game_not_found"}
    POST /games/{id}/moves  -> body: {player, row, col, version}
                            -> 200 state | 400 bad_version | 404 game_not_found
                                         | 409 version_conflict | 422 <rule_code>
    

    How do we handle double clicks and simultaneous moves cleanly? Each state carries version = len(game.moves), and every make_move sends the expected_version the client last saw — a pattern called optimistic concurrency control (accepting an update only if the version has not changed since the client read it). Combined with an idempotent retry check (allowing an identical repeat of an already-applied request to return the same result safely without re-executing), look at how Example 3 resolves both cases:

    Case A — Double click / network retry (same move sent twice at version 0):
      Req 1: make_move("g1", "X", 0, 1, expected_version=0) -> matches version 0 -> applied! version becomes 1
      Req 2: make_move("g1", "X", 0, 1, expected_version=0) -> 0 < 1 AND moves[0] == ("X", 0, 1) -> returns version 1 state (200)!
    
    Case B — Stale / conflicting click (client still looking at version 1 after version 2 happened):
      Move 2: make_move("g1", "O", 2, 1, expected_version=1) -> applied! version becomes 2
      Stale:  make_move("g1", "O", 1, 2, expected_version=1) -> moves[1] was ("O", 2, 1) != ("O", 1, 2)
                                                             -> 409 version_conflict! Client re-fetches version 2.
    

    Inside a multi-threaded Python server, checking len(game.moves) and calling game.play must happen atomically under self.lock (in SQL, the equivalent is UPDATE games SET ... WHERE id = ? AND version = ?). And _state always returns fresh slices of game.board so external callers cannot mutate server memory.

    class GameService:
        def __init__(self):
            # games: {game_id: Game}, e.g. {"g1": Game(), "g2": Game()}
            self.games: Dict[str, Game] = {}
            self.next_id: int = 1
            # lock: serializes check-and-apply across threads so two simultaneous moves cannot race
            self.lock = threading.Lock()
    
        def make_move(self, game_id: str, player, row, col, expected_version) -> dict:
            with self.lock:
                game = self._find(game_id)
                # Reject bools/strings/None for expected_version using strict type check
                if type(expected_version) is not int:
                    raise ApiError(400, "bad_version")
    
                current_version = len(game.moves)
                if expected_version != current_version:
                    # Idempotent retry check: ensure row/col are strict ints (since True == 1 in Python)
                    # and match the exact move originally applied at `expected_version`.
                    is_recorded_version = 0 <= expected_version < current_version
                    if (
                        is_recorded_version
                        and _is_index(row)
                        and _is_index(col)
                        and game.moves[expected_version] == (player, row, col)
                    ):
                        return self._state(game_id)
                    raise ApiError(409, "version_conflict")
    
                try:
                    game.play(player, row, col)
                except InvalidMove as error:
                    raise ApiError(422, error.code)
                return self._state(game_id)
    

    With GameService handling all logic, the HTTP wrapper (such as Flask or FastAPI) is ~20 lines of pure JSON plumbing, and in a two-browser setup the server issues a secret player token per seat so neither browser can spoof the opponent's mark.

  6. Keep the frontend thin and synchronized with server state

    The frontend renders four pieces of UI from a single state object returned by the server: the 3 x 3 grid, whose turn it is (state.turn), a win/draw banner (state.status and state.winner), and a "New game" button (POST /games), plus an error message slot.

    To stay effortlessly in sync with the backend, the frontend never mutates the board locally on click — it sends the request and renders whatever snapshot the server returns: - An inFlight boolean ignores extra clicks while a request is traveling over the network. - 200 OK: replace state with the response JSON and clear any error banner. - 422 Unprocessable Entity: display a friendly message for body.error (e.g., "Square already occupied") and leave state untouched. - 409 Conflict: another move landed first; immediately GET /games/{id} to synchronize state.

    async function clickCell(row, col) {
      if (inFlight || state.status !== "in_progress") return;
      inFlight = true;
      try {
        const res = await fetch(`/games/${state.id}/moves`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ player: myMark, row, col, version: state.version }),
        });
        const body = await res.json();
        if (res.ok) {
          state = body;
          clearError();
        } else {
          showError(body.error);
          if (res.status === 409) {
            const latest = await fetch(`/games/${state.id}`);
            state = await latest.json();
          }
        }
      } finally {
        inFlight = false;
        render(state);
      }
    }
    
  7. Part 3: Debug AI-generated bugs with a failing test first

    Suppose during testing you discover a bug: after "X" wins, the backend still accepts "O"'s next move on an empty square. Instead of pasting the whole file into the AI and saying "fix this", follow a disciplined four-step loop:

    1. Reproduce with a failing test first: write test_p3_regression_backend_rejects_move_after_win playing 5 moves where "X" wins the top row (0,0)-(0,1)-(0,2) at version = 5, then calling make_move("g1", "O", 1, 2, 5) and asserting (422, "game_over") plus an unchanged board. Watching it fail proves you reproduced the exact bug.
    2. Trace the root cause before editing: follow the request from make_move -> game.play -> check_move. Common culprits in AI-generated code are computing wins only in the frontend, forgetting to update self.status = "won" inside play, or checking self.status after checking occupied/mutating board.
    3. Fix at the domain layer, not the UI: disabling clicks in JavaScript only hides the symptom; enforcing if self.status != "in_progress": raise InvalidMove("game_over") at the top of Game.check_move protects every caller. Give the AI the failing test, the function, and the exact rule priority table, then inspect every line of its diff.
    4. Run the regression suite AND a live verification checklist on the integrated app before calling it complete:
    Pre-ship live verification checklist:
      [x] Two browser tabs: X wins -> both tabs freeze the board and display "X wins"
      [x] Full-board draw and 9th-square column win both show the right banner
      [x] Rapid double-click on a cell places one mark and shows no error
      [x] Simultaneous clicks in two tabs: one succeeds, the other refreshes via 409
      [x] Browser reload mid-game restores the exact board and turn from GET /games/{id}
      [x] Manual curl with row=5 or post-win move returns 422 JSON without altering state
    
  8. Complete Python implementation

    Here is the complete Game and GameService implementation passing all Part 1, Part 2, and Part 3 tests:

    from typing import Dict, List, Optional, Tuple
    import threading
    
    # Flat board indices 0..8 where index = 3 * row + col:
    #   0 | 1 | 2
    #  ---+---+---
    #   3 | 4 | 5
    #  ---+---+---
    #   6 | 7 | 8
    LINES = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8),  # 3 horizontal rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8),  # 3 vertical columns
        (0, 4, 8), (2, 4, 6),             # 2 diagonals
    ]
    
    
    class InvalidMove(Exception):
        """Raised when a move violates game rules; `code` identifies which rule failed."""
    
        def __init__(self, code: str):
            super().__init__(code)
            self.code = code
    
    
    def _is_index(value) -> bool:
        """Return True only for strict ints 0, 1, or 2 (rejecting bools like True and floats like 1.0)."""
        # Use `type(value) is int` because `bool` subclasses `int` in Python (`isinstance(True, int)` is True)
        return type(value) is int and 0 <= value < 3
    
    
    class Game:
        """Part 1: pure Tic-Tac-Toe domain rules with zero UI, HTTP, or I/O dependencies."""
    
        def __init__(self):
            # board: 9 cell marks ("", "X", or "O") indexed by 3 * row + col
            self.board: List[str] = [""] * 9
            # turn: player expected next ("X" or "O"), or None once the game ends
            self.turn: Optional[str] = "X"
            # status: "in_progress", "won", or "draw"
            self.status: str = "in_progress"
            # winner: "X", "O", or None
            self.winner: Optional[str] = None
            # moves: chronological history of accepted (player, row, col) tuples
            self.moves: List[Tuple[str, int, int]] = []
    
        def check_move(self, player, row, col) -> None:
            """Validate a proposed move in strict priority order without mutating state."""
            if self.status != "in_progress":
                raise InvalidMove("game_over")
            if player not in ("X", "O"):
                raise InvalidMove("bad_player")
            if player != self.turn:
                raise InvalidMove("not_your_turn")
            if not _is_index(row) or not _is_index(col):
                raise InvalidMove("out_of_bounds")
            cell_index = 3 * row + col
            if self.board[cell_index] != "":
                raise InvalidMove("occupied")
    
        def play(self, player, row, col) -> None:
            """Apply a move, or raise InvalidMove(code) leaving the game completely unchanged."""
            # Validate every rule first so a failed move never half-updates the board or turn
            self.check_move(player, row, col)
    
            cell_index = 3 * row + col
            self.board[cell_index] = player
            self.moves.append((player, row, col))
    
            # Check win BEFORE draw: the 9th move can fill the last square and complete a 3-in-a-row!
            if self._has_line(player):
                self.status = "won"
                self.winner = player
                self.turn = None
            elif len(self.moves) == 9:
                self.status = "draw"
                self.turn = None
            else:
                self.turn = "O" if player == "X" else "X"
    
        def _has_line(self, player: str) -> bool:
            """Return True if `player` occupies all three squares of any row, column, or diagonal."""
            for a, b, c in LINES:
                if self.board[a] == player and self.board[b] == player and self.board[c] == player:
                    return True
            return False
    
    
    class ApiError(Exception):
        """Structured backend error mapped by the HTTP layer to `status` and `{"error": code}`."""
    
        def __init__(self, status: int, code: str):
            super().__init__(f"{status} {code}")
            self.status = status
            self.code = code
    
    
    class GameService:
        """Part 2: authoritative backend store enforcing rules, versions, and idempotent retries.
    
        Clients send `expected_version` (the move count they last rendered). If `expected_version`
        lags behind the server, we return 409 `version_conflict` — EXCEPT when the request repeats
        the exact move already recorded at `expected_version` (a double click or network retry),
        in which case we return the current game state idempotently.
        """
    
        def __init__(self):
            # games: {game_id: Game}, e.g. {"g1": Game(), "g2": Game()}
            self.games: Dict[str, Game] = {}
            self.next_id: int = 1
            # lock: serializes check-and-apply across threads so two simultaneous moves cannot race
            self.lock = threading.Lock()
    
        def create_game(self) -> dict:
            with self.lock:
                game_id = "g" + str(self.next_id)
                self.next_id += 1
                self.games[game_id] = Game()
                return self._state(game_id)
    
        def get_game(self, game_id: str) -> dict:
            with self.lock:
                self._find(game_id)
                return self._state(game_id)
    
        def make_move(self, game_id: str, player, row, col, expected_version) -> dict:
            with self.lock:
                game = self._find(game_id)
                # Reject bools/strings/None for expected_version using strict type check
                if type(expected_version) is not int:
                    raise ApiError(400, "bad_version")
    
                current_version = len(game.moves)
                if expected_version != current_version:
                    # Idempotent retry check: ensure row/col are strict ints (since True == 1 in Python)
                    # and match the exact move originally applied at `expected_version`.
                    is_recorded_version = 0 <= expected_version < current_version
                    if (
                        is_recorded_version
                        and _is_index(row)
                        and _is_index(col)
                        and game.moves[expected_version] == (player, row, col)
                    ):
                        return self._state(game_id)
                    raise ApiError(409, "version_conflict")
    
                try:
                    game.play(player, row, col)
                except InvalidMove as error:
                    raise ApiError(422, error.code)
                return self._state(game_id)
    
        def _find(self, game_id: str) -> Game:
            if game_id not in self.games:
                raise ApiError(404, "game_not_found")
            return self.games[game_id]
    
        def _state(self, game_id: str) -> dict:
            """Build a fresh JSON-ready snapshot so callers cannot mutate internal Game lists."""
            game = self.games[game_id]
            board_rows = [
                game.board[0:3],
                game.board[3:6],
                game.board[6:9],
            ]
            return {
                "id": game_id,
                "board": board_rows,
                "turn": game.turn,
                "status": game.status,
                "winner": game.winner,
                "version": len(game.moves),
            }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the architecture like an official chess tournament table with a referee: players never reach across and rearrange the official scoreboard themselves — they announce a proposed move to the referee (GameService), who consults a standalone rulebook (Game) before touching the board and stamps each new position with a sequential move number (version). Separating the pure rulebook from the web server and browser UI also gives you the best workflow for AI-assisted coding: you write down the exact rule table first, generate and test one small layer at a time, and reproduce any bug as a failing test before asking the AI for a fix.

Asking an AI to generate an entire full-stack app in one prompt, or enforcing rules only in browser JavaScript, falls apart quickly. Anyone can bypass frontend checks with curl, AI-generated rules frequently miss edge cases like winning on the 9th move or rejecting Python True as coordinate 1, and double clicks or network retries cause confusing "not your turn" errors without server-side version tracking. We solve concurrency with optimistic concurrency control (requiring each move request to include the expected_version the client last saw and rejecting stale versions with 409), paired with idempotency (returning the current state safely when a duplicate request repeats the exact move already recorded at expected_version).

Walk through Example 3 on a fresh game "g1" (version = 0, turn = "X"): 1. Valid move: Browser A sends make_move("g1", "X", 0, 1, expected_version=0). 0 == 0 and (0, 1) is legal, so "X" claims the top-middle cell, turn flips to "O", and the server returns version = 1. 2. Accidental double click: Browser A's duplicate click arrives with ("X", 0, 1, expected_version=0). Although 0 != 1, game.moves[0] is ("X", 0, 1), so the server recognizes an idempotent retry and returns the version = 1 snapshot instead of raising an error. 3. Conflicting stale move: Once "O" plays (2, 1) at version = 1 (advancing the server to version = 2), a stale tab sending ("O", 1, 2, expected_version=1) does not match game.moves[1], so the server raises 409 version_conflict and the client re-fetches version = 2.

Complexity

Let G be the number of active games stored in GameService.

  • Game.play: O(1) time, because check_move performs 5 constant-time checks and _has_line inspects at most 8 winning lines of 3 cells (24 array reads total).
  • GameService.create_game, get_game, and make_move: O(1) time (under uncontended lock acquisition), because each call performs one dictionary lookup in self.games, runs O(1) validation/move logic, and copies 9 strings into a fresh 3 x 3 board snapshot.
  • Space: O(1) per game and O(G) total across G games, since each Game stores a fixed 9-element board list and at most 9 tuples in moves. On a long-running production server, completed games should be expired after a TTL or persisted to a database so G does not grow forever in RAM.

Edge cases

  • Winning on the 9th (last) square: Move #9 both fills the board (len(moves) == 9) and can complete a line; checking _has_line before len(moves) == 9 ensures it is scored as "won" rather than "draw".
  • Moves after a win or draw: Checked first (status != "in_progress" -> "game_over"), so neither "X" nor "O" can place marks on leftover empty cells after a 5-move win.
  • Booleans and floats as coordinates or versions: In Python, bool subclasses int (isinstance(True, int) is True and True == 1, 1.0 == 1). Checking type(value) is int in both _is_index and make_move prevents JSON true or 1.0 from sneaking in as valid coordinates or idempotent retries.
  • Negative coordinates (row = -1): Python lists allow board[-1] as the last element, so _is_index enforces 0 <= value < 3 before computing 3 * row + col.
  • State isolation on returned dicts: _state slices game.board into three fresh sublists ([0:3], [3:6], [6:9]), so mutating a returned response dict in caller or test code cannot corrupt the stored Game.
  • Failed moves leave zero trace: All checks run before mutating board, moves, or turn, so a rejected move leaves version and turn untouched.

Common mistakes

  • Validating rules only in the frontend: Disabling occupied buttons in HTML helps UX, but without backend enforcement in GameService any raw HTTP request can cheat or corrupt the board.
  • Trusting AI-generated tests that came from the same prompt as the code: If the AI forgot the 9th-move win rule in play(), its generated tests almost certainly forgot to test it too. Write the spec and critical edge-case tests yourself.
  • Patching symptoms in the wrong layer: Fixing "moves accepted after a win" by hiding the HTML board leaves the backend API broken; fixing it in Game.check_move protects every caller at once.
  • Returning 422 not_your_turn on a double click: Without checking whether a stale expected_version matches game.moves[expected_version], a harmless network retry or double tap shows a scary error for a move that actually succeeded.
  • Checking and applying moves without a lock (or atomic SQL WHERE version = ?): Under a threaded server, two simultaneous requests can both read version = 4 before either appends to game.moves unless protected by threading.Lock or an atomic database update.

Follow-up questions

  • How would you implement an unbeatable single-player bot, and how would you prove that AI-generated search code has zero losing lines? Use minimax — a recursive search algorithm where the bot picks the move that maximizes its worst-case outcome assuming an optimal human opponent (scoring +1 for a bot win, -1 for a loss, 0 for a draw). Because 3x3 Tic-Tac-Toe has only 5,478 reachable legal board states from an empty board, minimax with memoization (caching each solved board tuple so repeated positions are evaluated once) runs in milliseconds and guarantees at least a draw. To prove AI-generated minimax code has zero blind spots, write an exhaustive test harness that explores every legal human reply sequence against the bot playing both "X" and "O" and asserts zero bot losses across the entire game tree, alongside unit tests checking immediate 1-move wins and immediate 1-move blocks.
  • How would you push board updates in real time between two separate client browsers instead of polling? Replace periodic HTTP polling with server push over WebSockets (a persistent full-duplex TCP channel between browser and server) or Server-Sent Events (a lightweight one-way HTTP event stream from server to browser). Whenever make_move commits version v, the server broadcasts the updated state snapshot (carrying version: v) to all subscribers of game_id, and clients discard any out-of-order message with version <= state.version. When running multiple backend worker processes, a publish-subscribe (pub/sub) broker such as Redis relays move events across instances, while GET /games/{id} recovers full state after brief disconnects.
  • How would you generalize the data model and win check to an M-by-M grid requiring K consecutive marks? board expands to M * M cells (1 <= K <= M), _is_index validates 0 <= value < M, and a full-board draw happens at M * M moves. Instead of precomputing a static LINES table, _has_line inspects only the 4 axes passing through the most recently played cell (row, col) — horizontal (0, 1), vertical (1, 0), main diagonal (1, 1), and anti-diagonal (1, -1) — counting contiguous matching marks forward and backward up to K - 1 steps in O(K) time per move. For larger boards (such as 15 x 15 with K = 5), full minimax becomes intractable and requires depth-limited alpha-beta pruning with heuristic line-threat evaluation.
  • Suppose your coding assistant suggests pulling in an unfamiliar third-party frontend state package. What criteria govern whether you adopt or reject it? Evaluate every proposed dependency against actual problem complexity and your obligation to understand and maintain every line shipped. Here, client state is a single server snapshot ({id, board, turn, status, winner, version}) plus one inFlight boolean, so native component state is smaller, clearer, and introduces zero external failure modes — reject the package. You should only adopt a new dependency when it solves genuine architectural complexity (like multi-view cache synchronization or offline queues), has active maintenance and a permissive license, and you read its documentation and test its edge cases firsthand.

Alternative approaches

  • Client-generated idempotency keys: An idempotency key is a unique random token (such as a UUID) generated per user click and sent in a header so the server caches and replays the exact response on retries. This generalizes beyond Tic-Tac-Toe to operations where two distinct legitimate actions could carry the same parameters.
  • Event-sourced move log: Event sourcing stores only moves: [(player, row, col), ...] as the primary record and derives board, turn, and winner by replaying those <= 9 moves. version is naturally len(moves), and full move-by-move replay history comes for free.
  • Server-rendered HTML with form posts (or HTMX): Rendering the 3 x 3 HTML table directly on the server eliminates client-side JavaScript state synchronization altogether, trading a tiny HTML swap per click for near-zero frontend code.

Follow-up questions

Similar questions

More Airwallex interview questions

All 19 Airwallex questions →