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:
-
Pure Domain Rules (
InvalidMoveandGame)- The
3 x 3grid is stored inGame.boardas a flat 9-element list of strings ("","X", or"O") mapped byindex = 3 * row + col. Winning triples are listed inLINES. - A fresh
Game()starts withboard = [""] * 9,turn = "X",status = "in_progress",winner = None, andmoves = [](recording accepted(player, row, col)tuples in play order). game.play(player, row, col)validates a proposed move in strict priority order and raisesInvalidMove(code)without modifying any game attribute when a check fails:"game_over"—self.statusis already"won"or"draw"."bad_player"—playeris neither"X"nor"O"."not_your_turn"—playerdoes not matchself.turn."out_of_bounds"—roworcolis not a strictint(boolvalues likeTrue/False, floats like1.0, strings, andNonemust all be rejected) or falls outside0..2."occupied"—self.board[3 * row + col]already holds"X"or"O".
- When all checks pass, record the mark on
board, append(player, row, col)tomoves, and evaluate end-of-game conditions:- If
playernow occupies all three cells of any row, column, or diagonal inLINES, setstatus = "won",winner = player, andturn = None. (Check win before draw so completing a line on the 9th move counts as"won".) - Else if
len(moves) == 9, setstatus = "draw",winner = None, andturn = None. - Otherwise switch
turnto the other player ("X"<->"O").
- If
- The
-
Authoritative Backend Store (
ApiErrorandGameService)GameServicemanages 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), andmake_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)raisesApiError(404, "game_not_found")ifgame_iddoes not exist.make_move(game_id, player, row, col, expected_version)enforces optimistic concurrency and idempotent retries in strict priority order:- Raise
ApiError(404, "game_not_found")ifgame_idis unknown. - Raise
ApiError(400, "bad_version")ifexpected_versionis not a strictint(rejectingbool,float,str,None). - Let
current_version = len(game.moves). Ifexpected_version != current_version:- Idempotent retry: if
0 <= expected_version < current_version,rowandcolare strictintvalues in0..2, andgame.moves[expected_version] == (player, row, col), return the current state snapshot without error. - Otherwise raise
ApiError(409, "version_conflict").
- Idempotent retry: if
- Call
game.play(player, row, col); ifInvalidMove(code)is raised, translate it intoApiError(422, code)without altering server state. Otherwise return the updated snapshot.
- Raise
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
rowandcolmust be strict Pythonintinstances (type(v) is int) satisfying0 <= v <= 2. expected_versionmust be a strict Pythonintinstance (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.playorGameService.make_movemust leave all stored board cells, move history, turn, and version counters completely unchanged. - Use only the Python standard library (
threadingfor synchronization).
Step-by-step walkthrough
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.
- 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
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 (
9moves) before checking for a win, mislabeling a 9th-move victory as a draw. 2. Forgetting to reject moves oncestatus != "in_progress". 3. Usingisinstance(row, int), which acceptsTrueandFalsebecauseboolis a subclass ofintin Python (True == 1,False == 0). 4. Checkingboard[3 * row + col]before bounds checking, whererow = -1silently reads from the end of a Python list! 5. Mutatingboardorturnbefore all checks pass, leaving partial state after an exception.Part 1: Implement pure, UI-free game rules
We store the
3 x 3board as a flat 9-element list indexed by3 * row + coland predefine all 8 three-in-a-row index triples inLINES:(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
Gamehas 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 FalseVerify Part 1 with targeted edge-case tests
Before touching HTTP or HTML, lock down
Gamewith tests aimed right at the failure modes from our checklist: - Wins across all 8 lines (3rows,3columns,2diagonals) 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, andgame_overafter both a win and a draw), asserting the board andturndid not budge. - A randomized differential test comparing 200 random games against a separate
3 x 3nested-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])- Every invalid move (
Part 2: Make the backend the sole authority
Any user can bypass browser JavaScript with
curl, so the backendGameServiceacts 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 everymake_movesends theexpected_versionthe 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 callinggame.playmust happen atomically underself.lock(in SQL, the equivalent isUPDATE games SET ... WHERE id = ? AND version = ?). And_statealways returns fresh slices ofgame.boardso 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
GameServicehandling 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.Keep the frontend thin and synchronized with server state
The frontend renders four pieces of UI from a single
stateobject returned by the server: the3 x 3grid, whose turn it is (state.turn), a win/draw banner (state.statusandstate.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
inFlightboolean ignores extra clicks while a request is traveling over the network. -200 OK: replacestatewith the response JSON and clear any error banner. -422 Unprocessable Entity: display a friendly message forbody.error(e.g.,"Square already occupied") and leavestateuntouched. -409 Conflict: another move landed first; immediatelyGET /games/{id}to synchronizestate.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); } }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:- Reproduce with a failing test first: write
test_p3_regression_backend_rejects_move_after_winplaying 5 moves where"X"wins the top row(0,0)-(0,1)-(0,2)atversion = 5, then callingmake_move("g1", "O", 1, 2, 5)and asserting(422, "game_over")plus an unchanged board. Watching it fail proves you reproduced the exact bug. - 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 updateself.status = "won"insideplay, or checkingself.statusafter checkingoccupied/mutatingboard. - 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 ofGame.check_moveprotects every caller. Give the AI the failing test, the function, and the exact rule priority table, then inspect every line of its diff. - 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- Reproduce with a failing test first: write
Complete Python implementation
Here is the complete
GameandGameServiceimplementation 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, becausecheck_moveperforms 5 constant-time checks and_has_lineinspects at most8winning lines of3cells (24array reads total).GameService.create_game,get_game, andmake_move:O(1)time (under uncontended lock acquisition), because each call performs one dictionary lookup inself.games, runsO(1)validation/move logic, and copies9strings into a fresh3 x 3board snapshot.- Space:
O(1)per game andO(G)total acrossGgames, since eachGamestores a fixed9-elementboardlist and at most9tuples inmoves. On a long-running production server, completed games should be expired after a TTL or persisted to a database soGdoes 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_linebeforelen(moves) == 9ensures 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,
boolsubclassesint(isinstance(True, int)isTrueandTrue == 1,1.0 == 1). Checkingtype(value) is intin both_is_indexandmake_moveprevents JSONtrueor1.0from sneaking in as valid coordinates or idempotent retries. - Negative coordinates (
row = -1): Python lists allowboard[-1]as the last element, so_is_indexenforces0 <= value < 3before computing3 * row + col. - State isolation on returned dicts:
_stateslicesgame.boardinto three fresh sublists ([0:3],[3:6],[6:9]), so mutating a returned response dict in caller or test code cannot corrupt the storedGame. - Failed moves leave zero trace: All checks run before mutating
board,moves, orturn, so a rejected move leavesversionandturnuntouched.
Common mistakes
- Validating rules only in the frontend: Disabling occupied buttons in HTML helps UX, but without backend enforcement in
GameServiceany 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_moveprotects every caller at once. - Returning
422 not_your_turnon a double click: Without checking whether a staleexpected_versionmatchesgame.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 readversion = 4before either appends togame.movesunless protected bythreading.Lockor 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
+1for a bot win,-1for a loss,0for a draw). Because 3x3 Tic-Tac-Toe has only5,478reachable 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_movecommits versionv, the server broadcasts the updated state snapshot (carryingversion: v) to all subscribers ofgame_id, and clients discard any out-of-order message withversion <= state.version. When running multiple backend worker processes, a publish-subscribe (pub/sub) broker such as Redis relays move events across instances, whileGET /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?
boardexpands toM * Mcells (1 <= K <= M),_is_indexvalidates0 <= value < M, and a full-board draw happens atM * Mmoves. Instead of precomputing a staticLINEStable,_has_lineinspects 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 toK - 1steps inO(K)time per move. For larger boards (such as15 x 15withK = 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 oneinFlightboolean, 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 derivesboard,turn, andwinnerby replaying those<= 9moves.versionis naturallylen(moves), and full move-by-move replay history comes for free. - Server-rendered HTML with form posts (or HTMX): Rendering the
3 x 3HTML 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
- How would you implement an unbeatable single-player bot, and how would you prove that AI-generated search code has zero losing lines?
- How would you push board updates in real time between two separate client browsers instead of polling?
- How would you generalize the data model and win check to an M-by-M grid requiring K consecutive marks?
- Suppose your coding assistant suggests pulling in an unfamiliar third-party frontend state package. What criteria govern whether you adopt or reject it?
Similar questions
- Keyed Async Task Scheduler with Per-Name Queues and Cancellation
- Bar-Raiser Deep Dive: Justifying Past Engineering Choices and Outcomes
- Nudity View Prevalence in Content Moderation
- Architect a Flash-Sale Event Ticketing Platform
- Hotel Reservation Platform: Relational Schema and Atomic Booking
- Multi-Tenant Large-File Ingestion and Reporting Pipeline
More Airwallex interview questions
- Diagnosing Multi-Regime Shifts in Fintech Approval Rate Medium
- Bar-Raiser Deep Dive: Justifying Past Engineering Choices and Outcomes Medium
- Architect a Flash-Sale Event Ticketing Platform Medium Pro
- Hotel Reservation Platform: Relational Schema and Atomic Booking Medium Pro
- Reusable React Typeahead Component: Architecture, Portals, and Client Caching Medium Pro
- Investigating Step-Drops, Drift, and Seasonality in KYC Onboarding Medium Pro
- Approval-Rate Time-Series Diagnosis and Homepage CTA Swap Experiment Easy Pro
- Daily AI Coding Workflows and Guardrails for Autonomous Agents Medium Pro
- Experiment Design for Reordering Dual Landing-Page CTAs Medium Pro
- Largest Square of Ones Medium Pro