Tic-tac-toe looks too small for a design round, which is exactly why interviewers like it. Everyone can write a 3x3 version in 20 minutes. What they are watching is whether your 3x3 version survives the next three questions: “make it N x N”, “make the win check faster”, “add undo”. If any of those forces a rewrite, the design was wrong. The design below answers all three before they are asked, and adds a bot that cannot lose.
Pin down the scope first
Spend two minutes here. The answers change the design more than you would expect.
What the game must do:
- Two players, X and O, alternate turns. X moves first.
- The board is N x N, with N = 3 by default. Ask for N on day one; it is the most common follow-up and it is free if you plan for it.
- A player wins with a complete row, column or either main diagonal. If the board fills with no winner, it is a draw.
- Reject illegal moves (occupied cell, off the board, moving after the game ended) with a clear error, and leave the game state unchanged when you do.
- Undo the last move, any number of times.
- Players can be humans or bots, and the game engine must not care which.
Out of scope, and say so out loud:
- Rendering, console input parsing and networking. The engine takes
(row, col)and returns a status; a UI or a server wraps it. - Accounts, matchmaking, ratings, timers.
- Persistence. The move list is enough to rebuild any game if someone asks later.
- Concurrency. Turns are strictly sequential, so there is no shared state to protect inside one game. A server hosting thousands of games keeps one
Gameper match and serialises moves per match; that is a thread safety question, not a tic-tac-toe one.
Entities
| Class | Owns | Why it exists |
|---|---|---|
Symbol | X or O, and other() | Turn switching becomes turn = turn.other() instead of an if/else in three places |
Move | row, col, symbol | Immutable record of one placement. The undo stack is a list of these |
Board | the N x N grid, a filled-cell count | Placement and validation. Knows nothing about winning |
WinRule | whatever bookkeeping it needs | Answers “did the move just played win?” and can revert that bookkeeping |
Game | board, rule, whose turn, status, winner, history | The rules engine: enforces turn order, game over, undo |
PlayerStrategy | nothing shared | Picks a move given the game. Scripted input, random bot and minimax bot implement it |
Two things are missing on purpose. There is no Player object inside Game, and no Cell class. A cell is a slot in a 2D array holding a symbol or nothing; wrapping it in a class adds an object per square and no behaviour. Players live outside the engine: a small run() loop maps each symbol to a strategy and asks it for moves. That split pays off later, because the minimax bot drives the same Game through play and undo while it searches.
Class diagram
classDiagram
class Game {
+board: Board
+rule: WinRule
+turn: Symbol
+status: Status
+winner: Symbol | None
+history: list~Move~
+play(row, col) Status
+undo() Move
}
class Board {
+n: int
+cells: Symbol[][]
+filled: int
+place(row, col, symbol)
+clear(row, col)
+is_full() bool
+empty_cells() list
}
class Move {
+row: int
+col: int
+symbol: Symbol
}
class WinRule {
<<interface>>
+record(board, move) bool
+revert(board, move)
}
class CounterWinRule {
-rows: int[]
-cols: int[]
-diag: int
-anti: int
}
class LineScanWinRule {
-k: int
}
class PlayerStrategy {
<<interface>>
+choose(game) row_col
}
class ScriptedPlayer
class RandomPlayer
class MinimaxPlayer {
+nodes: int
}
class Symbol {
<<enumeration>>
X
O
}
class Status {
<<enumeration>>
IN_PROGRESS
WON
DRAW
}
Game "1" *-- "1" Board
Game --> WinRule
Game "1" *-- "many" Move : history
WinRule <|.. CounterWinRule
WinRule <|.. LineScanWinRule
PlayerStrategy <|.. ScriptedPlayer
PlayerStrategy <|.. RandomPlayer
PlayerStrategy <|.. MinimaxPlayer
PlayerStrategy ..> Game : reads, and minimax plays/undoes
Game --> Status
Move --> SymbolThe win check is the whole interview
The naive check scans every row, every column and both diagonals after each move: 2N + 2 lines of N cells, so O(N²) per move. On 3x3 nobody cares. The interviewer will still ask “can you do better?”, and the answer they want is the counter trick.
Keep one integer per row, one per column, and one each for the two diagonals. X adds 1, O subtracts 1. After a move at (r, c) you update at most four counters, and the mover has won if any of them reached +N or -N. A row can only reach +3 on a 3x3 board if all three cells are X; a single O in it pulls the sum down and it can never get there. That is O(1) time per move and O(N) extra space.
Walk through the first demo game below. X plays (0,2), (1,1), (2,0); O plays (0,0) and (2,2). The anti-diagonal is the cells where row + col == N - 1, here (0,2), (1,1), (2,0). After X’s third move the anti-diagonal counter is 3, so X wins. O’s two moves both sit on the main diagonal, which ends at -2 + 1 = -1 after X took the centre.
The two diagonal conditions trip people up. (1,1) on a 3x3 board is on both diagonals, so the code uses two independent ifs, not if/elif. On an even board like 4x4 no cell is on both, and the same code still works.
Undo is where counters cost you something: they are derived state, so undo has to subtract what the move added. That is why WinRule has a revert method and why CounterWinRule runs the same update with the sign flipped. Forget it and the counters drift: undo a winning move, play somewhere else, and the game declares a win that is not on the board.
Counters stop working when the rule changes from “fill a line” to “get K in a row” (Gomoku: 5 in a row on 15x15). A row with five X’s split by an O never sums to anything useful. For that rule, check only the four lines through the last move and walk outwards in both directions, counting matching symbols: O(K) per move with no extra state. That is LineScanWinRule, and it is the reason WinRule is an interface at all. Demo 6 plays 2,000 random 3x3 games with both rules side by side and checks after every move that they agree.
Patterns: used, and turned down
Strategy, twice. WinRule swaps the win condition (full line with counters, or K in a row by scanning) without touching Game. PlayerStrategy swaps who picks moves: a human behind a console, a scripted list for tests, a random bot, minimax. Both are real variation points the interviewer is likely to ask about, which is the test for whether an interface earns its place.
A move stack for undo. Each Move is stored, and undo pops one and reverses it: clear the cell, revert the rule, restore the turn, reset status to in progress. I’d call it a lightweight Command or Memento if asked, but I would not build the full Command pattern (MoveCommand with execute() and unexecute() plus an invoker). There is exactly one kind of action in this game. One record and one undo method say the same thing in a third of the code.
Turned down:
- State pattern for game status. The vending machine in lesson 10 needed it because each state accepts different operations with different behaviour. Here there are three states, and the only state-dependent rule is “no moves once the game is over”, which is one guard clause in
play. An enum is the right size. - Singleton for
GameorBoard. A server runs many games at once and tests create dozens. A singleton makes both impossible and buys nothing. - Factory for players. Unless the prompt says players are configured from a file or a menu,
new MinimaxPlayer()is clear enough. Add a factory when the creation logic grows a switch statement. - Observer for the UI. Worth mentioning as an extension (a board view or a spectator feed subscribes to moves). Building it into a 45-minute answer is time you need for the win check and undo.
The code
Both versions were run on the box this lesson was written on (Python 3.13.5, OpenJDK 21) and print identical output, byte for byte. The random bot uses a tiny linear congruential generator written into both files instead of the language’s own random, so the “random” games are the same in Python and Java. The files are in course-code/low-level-design/13/ in the course repository.
Points worth noticing while you read:
playcallsboard.placefirst. If the move is illegal it throws before the history, the counters or the turn change, so a rejected move leaves no trace.- The minimax bot never copies the board. It calls
game.play, recurses, thengame.undo. Undo was a requirement; the bot gets it for free and becomes a test of it, since one bad revert would corrupt every search. - Scores are
100 - depthfor a win, so the bot prefers a win in 3 over a win in 7, and drags out a loss when it cannot avoid one. Without the depth term it may “win eventually” and look broken.
Python
"""Tic-tac-toe low-level design: N x N board, O(1) win check, undo, pluggable players.
Run: python3 tictactoe.py
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
class Symbol(Enum):
X = "X"
O = "O"
def other(self) -> "Symbol":
return Symbol.O if self is Symbol.X else Symbol.X
class Status(Enum):
IN_PROGRESS = "in progress"
WON = "won"
DRAW = "draw"
class InvalidMove(Exception):
pass
@dataclass(frozen=True)
class Move:
row: int
col: int
symbol: Symbol
def __str__(self) -> str:
return f"{self.symbol.value}@({self.row},{self.col})"
class Board:
def __init__(self, n: int):
self.n = n
self.cells: list[list[Symbol | None]] = [[None] * n for _ in range(n)]
self.filled = 0
def place(self, row: int, col: int, s: Symbol) -> None:
if not (0 <= row < self.n and 0 <= col < self.n):
raise InvalidMove(f"({row},{col}) is off a {self.n}x{self.n} board")
if self.cells[row][col] is not None:
raise InvalidMove(f"({row},{col}) is taken by {self.cells[row][col].value}")
self.cells[row][col] = s
self.filled += 1
def clear(self, row: int, col: int) -> None:
self.cells[row][col] = None
self.filled -= 1
def is_full(self) -> bool:
return self.filled == self.n * self.n
def empty_cells(self) -> list[tuple[int, int]]:
return [(r, c) for r in range(self.n) for c in range(self.n) if self.cells[r][c] is None]
def render(self) -> str:
return "\n".join(" ".join(c.value if c else "." for c in row) for row in self.cells)
class WinRule(ABC):
"""Decides whether the move just played wins. revert() keeps it correct across undo."""
@abstractmethod
def record(self, board: Board, m: Move) -> bool: ...
@abstractmethod
def revert(self, board: Board, m: Move) -> None: ...
class CounterWinRule(WinRule):
"""Full row/column/diagonal on N x N. X adds 1, O subtracts 1; |sum| == n means a win. O(1) per move."""
def __init__(self, n: int):
self.n = n
self.rows, self.cols = [0] * n, [0] * n
self.diag = self.anti = 0
def _apply(self, m: Move, sign: int) -> bool:
d = (1 if m.symbol is Symbol.X else -1) * sign
n = self.n
self.rows[m.row] += d
self.cols[m.col] += d
if m.row == m.col:
self.diag += d
if m.row + m.col == n - 1:
self.anti += d
return n in (abs(self.rows[m.row]), abs(self.cols[m.col]), abs(self.diag), abs(self.anti))
def record(self, board, m):
return self._apply(m, +1)
def revert(self, board, m):
self._apply(m, -1)
class LineScanWinRule(WinRule):
"""k in a row anywhere (Gomoku-style). Walks the 4 lines through the last move: O(k) per move."""
def __init__(self, k: int):
self.k = k
def record(self, board, m):
for dr, dc in ((0, 1), (1, 0), (1, 1), (1, -1)):
run = 1
for sign in (1, -1):
r, c = m.row + dr * sign, m.col + dc * sign
while 0 <= r < board.n and 0 <= c < board.n and board.cells[r][c] is m.symbol:
run += 1
r, c = r + dr * sign, c + dc * sign
if run >= self.k:
return True
return False
def revert(self, board, m):
pass # stateless: it reads the board
class Game:
def __init__(self, n: int = 3, rule: WinRule | None = None, first: Symbol = Symbol.X):
self.board = Board(n)
self.rule = rule or CounterWinRule(n)
self.turn = first
self.status = Status.IN_PROGRESS
self.winner: Symbol | None = None
self.history: list[Move] = []
def play(self, row: int, col: int) -> Status:
if self.status is not Status.IN_PROGRESS:
raise InvalidMove(f"game is over ({self.status.value})")
m = Move(row, col, self.turn)
self.board.place(row, col, m.symbol) # validates before any state changes
self.history.append(m)
if self.rule.record(self.board, m):
self.status, self.winner = Status.WON, m.symbol
elif self.board.is_full():
self.status = Status.DRAW
self.turn = self.turn.other()
return self.status
def undo(self) -> Move:
if not self.history:
raise InvalidMove("nothing to undo")
m = self.history.pop()
self.rule.revert(self.board, m)
self.board.clear(m.row, m.col)
self.status, self.winner, self.turn = Status.IN_PROGRESS, None, m.symbol
return m
class PlayerStrategy(ABC):
@abstractmethod
def choose(self, game: Game) -> tuple[int, int]: ...
class ScriptedPlayer(PlayerStrategy):
"""Stands in for console or network input in the demo."""
def __init__(self, moves):
self.moves = iter(moves)
def choose(self, game):
return next(self.moves)
class Lcg:
"""Tiny deterministic RNG so the Python and Java demos print the same games."""
def __init__(self, seed: int):
self.state = seed
def next_int(self, bound: int) -> int:
self.state = (self.state * 1103515245 + 12345) % 2**31
return (self.state >> 16) % bound # high bits: the low bits of an LCG cycle quickly
class RandomPlayer(PlayerStrategy):
def __init__(self, rng: Lcg):
self.rng = rng
def choose(self, game):
cells = game.board.empty_cells()
return cells[self.rng.next_int(len(cells))]
class MinimaxPlayer(PlayerStrategy):
"""Perfect play with alpha-beta pruning. Uses game.play/undo, so it never copies the board."""
def __init__(self):
self.nodes = 0
def choose(self, game):
me = game.turn
best, best_score = None, -10**9
for r, c in game.board.empty_cells():
game.play(r, c)
score = -self._negamax(game, -10**9, 10**9, 1)
game.undo()
if score > best_score:
best, best_score = (r, c), score
return best
def _negamax(self, game, alpha, beta, depth):
"""Score from the point of view of the player to move. Faster wins score higher."""
self.nodes += 1
if game.status is Status.WON:
return -(100 - depth) # the previous mover won, so the side to move has lost
if game.status is Status.DRAW:
return 0
best = -10**9
for r, c in game.board.empty_cells():
game.play(r, c)
best = max(best, -self._negamax(game, -beta, -alpha, depth + 1))
game.undo()
alpha = max(alpha, best)
if alpha >= beta:
break
return best
def run(game: Game, players: dict[Symbol, PlayerStrategy]) -> Game:
while game.status is Status.IN_PROGRESS:
r, c = players[game.turn].choose(game)
game.play(r, c)
return game
def result(game: Game) -> str:
return f"{game.winner.value} wins" if game.status is Status.WON else "draw"
if __name__ == "__main__":
print("1) Scripted 3x3 game")
g = run(Game(3), {Symbol.X: ScriptedPlayer([(0, 2), (1, 1), (2, 0)]),
Symbol.O: ScriptedPlayer([(0, 0), (2, 2)])})
print(g.board.render())
print("result:", result(g), "after", len(g.history), "moves")
print("\n2) Invalid moves are rejected without changing state")
g = Game(3)
g.play(1, 1)
for r, c in [(1, 1), (3, 0)]:
try:
g.play(r, c)
except InvalidMove as e:
print("rejected:", e)
print("turn is still", g.turn.value, "| moves:", len(g.history))
print("\n3) Undo a winning move")
g = Game(3)
for r, c in [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2)]:
g.play(r, c)
print("before undo:", result(g))
print("undid", g.undo(), "| status:", g.status.value, "| turn:", g.turn.value)
g.play(2, 2)
print("replayed (2,2):", g.status.value)
print("\n4) 4x4 board, column win")
g = Game(4)
for r, c in [(0, 3), (0, 0), (1, 3), (1, 1), (2, 3), (2, 2), (3, 3)]:
g.play(r, c)
print(g.board.render())
print("result:", result(g))
print("\n5) Gomoku-style: 4 in a row on 6x6 with LineScanWinRule")
g = Game(6, LineScanWinRule(4))
for r, c in [(2, 1), (0, 0), (3, 2), (0, 5), (4, 3), (5, 0), (5, 4)]:
g.play(r, c)
print("result:", result(g), "after", len(g.history), "moves")
print("\n6) Cross-check: counters vs line scan on 2,000 random 3x3 games")
rng, mismatches = Lcg(42), 0
for _ in range(2000):
a, b = Game(3, CounterWinRule(3)), Game(3, LineScanWinRule(3))
while a.status is Status.IN_PROGRESS:
r, c = RandomPlayer(rng).choose(a)
a.play(r, c)
b.play(r, c)
mismatches += a.status is not b.status
print("mismatches:", mismatches)
print("\n7) Minimax vs minimax")
bot_x, bot_o = MinimaxPlayer(), MinimaxPlayer()
g = run(Game(3), {Symbol.X: bot_x, Symbol.O: bot_o})
print(g.board.render())
print("result:", result(g), "| positions searched:", bot_x.nodes + bot_o.nodes)
print("\n8) Minimax vs random, 100 games each way")
rng, bot = Lcg(7), MinimaxPlayer()
for label, bot_side in (("minimax X, random O", Symbol.X), ("random X, minimax O", Symbol.O)):
tally = {"X wins": 0, "O wins": 0, "draw": 0}
for _ in range(100):
players = {bot_side: bot, bot_side.other(): RandomPlayer(rng)}
tally[result(run(Game(3), players))] += 1
print(f"{label}: " + ", ".join(f"{k} {v}" for k, v in tally.items()))
Java
// Tic-tac-toe low-level design: N x N board, O(1) win check, undo, pluggable players.
// Run: javac TicTacToe.java && java TicTacToe
import java.util.*;
public class TicTacToe {
enum Symbol {
X, O;
Symbol other() { return this == X ? O : X; }
}
enum Status { IN_PROGRESS, WON, DRAW }
static class InvalidMove extends RuntimeException {
InvalidMove(String msg) { super(msg); }
}
record Move(int row, int col, Symbol symbol) {
@Override public String toString() { return symbol + "@(" + row + "," + col + ")"; }
}
static class Board {
final int n;
final Symbol[][] cells;
int filled = 0;
Board(int n) { this.n = n; this.cells = new Symbol[n][n]; }
void place(int row, int col, Symbol s) {
if (row < 0 || row >= n || col < 0 || col >= n)
throw new InvalidMove("(" + row + "," + col + ") is off a " + n + "x" + n + " board");
if (cells[row][col] != null)
throw new InvalidMove("(" + row + "," + col + ") is taken by " + cells[row][col]);
cells[row][col] = s;
filled++;
}
void clear(int row, int col) { cells[row][col] = null; filled--; }
boolean isFull() { return filled == n * n; }
List<int[]> emptyCells() {
List<int[]> out = new ArrayList<>();
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
if (cells[r][c] == null) out.add(new int[]{r, c});
return out;
}
String render() {
StringJoiner rows = new StringJoiner("\n");
for (Symbol[] row : cells) {
StringJoiner line = new StringJoiner(" ");
for (Symbol s : row) line.add(s == null ? "." : s.name());
rows.add(line.toString());
}
return rows.toString();
}
}
/** Decides whether the move just played wins. revert() keeps it correct across undo. */
interface WinRule {
boolean record(Board board, Move m);
void revert(Board board, Move m);
}
/** Full row/column/diagonal on N x N. X adds 1, O subtracts 1; |sum| == n is a win. O(1) per move. */
static class CounterWinRule implements WinRule {
private final int n;
private final int[] rows, cols;
private int diag, anti;
CounterWinRule(int n) { this.n = n; rows = new int[n]; cols = new int[n]; }
private boolean apply(Move m, int sign) {
int d = (m.symbol() == Symbol.X ? 1 : -1) * sign;
rows[m.row()] += d;
cols[m.col()] += d;
if (m.row() == m.col()) diag += d;
if (m.row() + m.col() == n - 1) anti += d;
return Math.abs(rows[m.row()]) == n || Math.abs(cols[m.col()]) == n
|| Math.abs(diag) == n || Math.abs(anti) == n;
}
public boolean record(Board b, Move m) { return apply(m, +1); }
public void revert(Board b, Move m) { apply(m, -1); }
}
/** k in a row anywhere (Gomoku-style). Walks the 4 lines through the last move: O(k). */
static class LineScanWinRule implements WinRule {
private final int k;
LineScanWinRule(int k) { this.k = k; }
public boolean record(Board b, Move m) {
int[][] dirs = {{0, 1}, {1, 0}, {1, 1}, {1, -1}};
for (int[] d : dirs) {
int run = 1;
for (int sign : new int[]{1, -1}) {
int r = m.row() + d[0] * sign, c = m.col() + d[1] * sign;
while (r >= 0 && r < b.n && c >= 0 && c < b.n && b.cells[r][c] == m.symbol()) {
run++;
r += d[0] * sign;
c += d[1] * sign;
}
}
if (run >= k) return true;
}
return false;
}
public void revert(Board b, Move m) { } // stateless: it reads the board
}
static class Game {
final Board board;
final WinRule rule;
Symbol turn = Symbol.X;
Status status = Status.IN_PROGRESS;
Symbol winner = null;
final Deque<Move> history = new ArrayDeque<>();
Game(int n) { this(n, new CounterWinRule(n)); }
Game(int n, WinRule rule) { this.board = new Board(n); this.rule = rule; }
Status play(int row, int col) {
if (status != Status.IN_PROGRESS) throw new InvalidMove("game is over (" + statusText() + ")");
Move m = new Move(row, col, turn);
board.place(row, col, m.symbol()); // validates before any state changes
history.push(m);
if (rule.record(board, m)) { status = Status.WON; winner = m.symbol(); }
else if (board.isFull()) status = Status.DRAW;
turn = turn.other();
return status;
}
Move undo() {
if (history.isEmpty()) throw new InvalidMove("nothing to undo");
Move m = history.pop();
rule.revert(board, m);
board.clear(m.row(), m.col());
status = Status.IN_PROGRESS;
winner = null;
turn = m.symbol();
return m;
}
String statusText() { return status.name().toLowerCase().replace('_', ' '); }
String result() { return status == Status.WON ? winner + " wins" : "draw"; }
}
interface PlayerStrategy { int[] choose(Game game); }
/** Stands in for console or network input in the demo. */
static class ScriptedPlayer implements PlayerStrategy {
private final Iterator<int[]> moves;
ScriptedPlayer(int[]... moves) { this.moves = Arrays.asList(moves).iterator(); }
public int[] choose(Game g) { return moves.next(); }
}
/** Same LCG as the Python version, so both demos print the same games. */
static class Lcg {
private long state;
Lcg(long seed) { state = seed; }
int nextInt(int bound) {
state = (state * 1103515245L + 12345L) % (1L << 31);
return (int) ((state >> 16) % bound); // high bits: the low bits of an LCG cycle quickly
}
}
static class RandomPlayer implements PlayerStrategy {
private final Lcg rng;
RandomPlayer(Lcg rng) { this.rng = rng; }
public int[] choose(Game g) {
List<int[]> cells = g.board.emptyCells();
return cells.get(rng.nextInt(cells.size()));
}
}
/** Perfect play with alpha-beta pruning. Uses play/undo, so it never copies the board. */
static class MinimaxPlayer implements PlayerStrategy {
long nodes = 0;
public int[] choose(Game g) {
int[] best = null;
int bestScore = Integer.MIN_VALUE;
for (int[] cell : g.board.emptyCells()) {
g.play(cell[0], cell[1]);
int score = -negamax(g, -1_000_000_000, 1_000_000_000, 1);
g.undo();
if (score > bestScore) { bestScore = score; best = cell; }
}
return best;
}
private int negamax(Game g, int alpha, int beta, int depth) {
nodes++;
if (g.status == Status.WON) return -(100 - depth); // previous mover won
if (g.status == Status.DRAW) return 0;
int best = -1_000_000_000;
for (int[] cell : g.board.emptyCells()) {
g.play(cell[0], cell[1]);
best = Math.max(best, -negamax(g, -beta, -alpha, depth + 1));
g.undo();
alpha = Math.max(alpha, best);
if (alpha >= beta) break;
}
return best;
}
}
static Game run(Game g, Map<Symbol, PlayerStrategy> players) {
while (g.status == Status.IN_PROGRESS) {
int[] mv = players.get(g.turn).choose(g);
g.play(mv[0], mv[1]);
}
return g;
}
static void playAll(Game g, int[][] moves) { for (int[] m : moves) g.play(m[0], m[1]); }
public static void main(String[] args) {
System.out.println("1) Scripted 3x3 game");
Game g = run(new Game(3), Map.of(
Symbol.X, new ScriptedPlayer(new int[]{0, 2}, new int[]{1, 1}, new int[]{2, 0}),
Symbol.O, new ScriptedPlayer(new int[]{0, 0}, new int[]{2, 2})));
System.out.println(g.board.render());
System.out.println("result: " + g.result() + " after " + g.history.size() + " moves");
System.out.println("\n2) Invalid moves are rejected without changing state");
g = new Game(3);
g.play(1, 1);
for (int[] m : new int[][]{{1, 1}, {3, 0}}) {
try { g.play(m[0], m[1]); }
catch (InvalidMove e) { System.out.println("rejected: " + e.getMessage()); }
}
System.out.println("turn is still " + g.turn + " | moves: " + g.history.size());
System.out.println("\n3) Undo a winning move");
g = new Game(3);
playAll(g, new int[][]{{0, 0}, {1, 0}, {0, 1}, {1, 1}, {0, 2}});
System.out.println("before undo: " + g.result());
Move undone = g.undo();
System.out.println("undid " + undone + " | status: " + g.statusText() + " | turn: " + g.turn);
g.play(2, 2);
System.out.println("replayed (2,2): " + g.statusText());
System.out.println("\n4) 4x4 board, column win");
g = new Game(4);
playAll(g, new int[][]{{0, 3}, {0, 0}, {1, 3}, {1, 1}, {2, 3}, {2, 2}, {3, 3}});
System.out.println(g.board.render());
System.out.println("result: " + g.result());
System.out.println("\n5) Gomoku-style: 4 in a row on 6x6 with LineScanWinRule");
g = new Game(6, new LineScanWinRule(4));
playAll(g, new int[][]{{2, 1}, {0, 0}, {3, 2}, {0, 5}, {4, 3}, {5, 0}, {5, 4}});
System.out.println("result: " + g.result() + " after " + g.history.size() + " moves");
System.out.println("\n6) Cross-check: counters vs line scan on 2,000 random 3x3 games");
Lcg rng = new Lcg(42);
int mismatches = 0;
for (int i = 0; i < 2000; i++) {
Game a = new Game(3, new CounterWinRule(3)), b = new Game(3, new LineScanWinRule(3));
while (a.status == Status.IN_PROGRESS) {
int[] mv = new RandomPlayer(rng).choose(a);
a.play(mv[0], mv[1]);
b.play(mv[0], mv[1]);
if (a.status != b.status) mismatches++;
}
}
System.out.println("mismatches: " + mismatches);
System.out.println("\n7) Minimax vs minimax");
MinimaxPlayer botX = new MinimaxPlayer(), botO = new MinimaxPlayer();
g = run(new Game(3), Map.of(Symbol.X, botX, Symbol.O, botO));
System.out.println(g.board.render());
System.out.println("result: " + g.result() + " | positions searched: " + (botX.nodes + botO.nodes));
System.out.println("\n8) Minimax vs random, 100 games each way");
rng = new Lcg(7);
MinimaxPlayer bot = new MinimaxPlayer();
for (Symbol botSide : new Symbol[]{Symbol.X, Symbol.O}) {
Map<String, Integer> tally = new LinkedHashMap<>();
tally.put("X wins", 0); tally.put("O wins", 0); tally.put("draw", 0);
for (int i = 0; i < 100; i++) {
Game game = run(new Game(3), Map.of(botSide, bot, botSide.other(), new RandomPlayer(rng)));
tally.merge(game.result(), 1, Integer::sum);
}
String label = botSide == Symbol.X ? "minimax X, random O" : "random X, minimax O";
StringJoiner sj = new StringJoiner(", ");
tally.forEach((k, v) -> sj.add(k + " " + v));
System.out.println(label + ": " + sj);
}
}
}
Output
1) Scripted 3x3 game
O . X
. X .
X . O
result: X wins after 5 moves
2) Invalid moves are rejected without changing state
rejected: (1,1) is taken by X
rejected: (3,0) is off a 3x3 board
turn is still O | moves: 1
3) Undo a winning move
before undo: X wins
undid X@(0,2) | status: in progress | turn: X
replayed (2,2): in progress
4) 4x4 board, column win
O . . X
. O . X
. . O X
. . . X
result: X wins
5) Gomoku-style: 4 in a row on 6x6 with LineScanWinRule
result: X wins after 7 moves
6) Cross-check: counters vs line scan on 2,000 random 3x3 games
mismatches: 0
7) Minimax vs minimax
X X O
O O X
X O X
result: draw | positions searched: 42503
8) Minimax vs random, 100 games each way
minimax X, random O: X wins 99, O wins 0, draw 1
random X, minimax O: X wins 0, O wins 79, draw 21
Reading it back:
- Demo 2: both bad moves are rejected and it is still O’s turn with one move in the history. If your version prints “turn is still X” here, it flipped the turn before validating.
- Demo 3: X completes the top row, the move is undone, and the game is back in progress with X to move. X then plays
(2,2)instead, and nobody has won. If the counters had not been reverted, the top-row counter would still read 3 from the undone move, and depending on how you check it you would get a phantom win. - Demo 4: same
Gameclass,n=4, no other change. The column counter for column 3 reached 4. - Demo 5: swap in
LineScanWinRule(4)and the same engine plays 4-in-a-row on a 6x6 board. X’s four moves run diagonally from(2,1)to(5,4). - Demo 7: two perfect players always draw. That is the known result for tic-tac-toe, and a quick sanity check for any minimax you write.
- Demo 8: the bot never loses. Playing first, it won 99 of 100 games against the random player and drew one. Playing second, it won 79 and drew 21, which makes sense: moving second is the weaker seat, and a random opponent sometimes stumbles into the right replies.
How big is the search, really?
Numbers worth having in your head if the conversation turns to the AI player. I counted these by walking the full game tree with the same Game class:
- 255,168 possible complete games of 3x3 tic-tac-toe.
- 549,946 nodes in the full game tree (every position reached by every move order, including the empty board).
- 5,478 distinct positions, or 765 if you treat rotations and reflections as the same.
Plain minimax from the empty board visits all 549,946 nodes. With alpha-beta pruning, the bot’s first move searched 34,202 positions, and the whole bot-vs-bot game in demo 7 searched 42,503 across both players. That is fast enough that nobody needs to optimise further for 3x3.
4x4 is a different story. The same Java bot, asked for the first move on an empty 4x4 board, searched 1,204,474,213 positions and took 49 seconds on this box. The fixes, in the order I would mention them: a transposition table (cache scores by board state, since many move orders reach the same position; on 3x3 that collapses 549,946 nodes to at most 5,478 positions), symmetry reduction, and for anything larger a depth limit with a heuristic score instead of searching to the end. Gomoku bots on 15x15 do not search to the end at all.
Follow-up questions and how to answer them
“Make it N x N.” Already done: N is a constructor argument, the board is an N x N array, and the counters are arrays of size N. The thing to avoid is any literal 3 or a hardcoded list of the eight winning lines.
“Can the win check be O(1)?” Row, column and two diagonal counters, +1 for X and -1 for O, win at plus or minus N. Explain why a mixed line can never reach N. Memory is 2N + 2 integers.
“Three players on a bigger board.” The +1/-1 trick only works for two symbols. Keep a separate count per player per line instead (rows[player][r]), which is O(P x N) memory and still O(1) per move. Or use the line-scan rule, which never cared how many players there are.
“Add redo.” A second stack. undo pushes the popped move onto it, redo replays from it, and any fresh play clears it. Forgetting that last part lets someone redo a move into a cell that is now taken.
“Make the computer player unbeatable.” Minimax with alpha-beta, as above. Mention the depth-adjusted score, or the bot will sometimes delay a win it already has.
“Let two people play over the network.” The server owns the Game and is the only one allowed to call play; clients send (row, col) and receive the new status. Never trust a client to report that it won. Store the move list per match so a dropped player can reconnect and the board can be rebuilt.
“Who goes first in the next round?” Make the starting symbol a constructor parameter and let a Match (best of five, say) alternate it. Do not put round logic inside Game; one game is one game.
“How would you test this?” Scripted players for exact sequences: every winning line on 3x3 and on 4x4, a win on the very last cell, every kind of illegal move, undo after a win, undo on an empty game. Then a cross-check like demo 6, where two independent implementations must agree over thousands of random games.
Mistakes I see in mock interviews
- Checking for a draw before checking for a win. If the ninth move completes a line, a full-board check that runs first reports a draw. Win first, then draw.
elifbetween the two diagonal checks. The centre of an odd board is on both diagonals. Withelif, a win through the centre on the anti-diagonal goes unnoticed whenever the move also satisfiesrow == col.- Flipping the turn or recording the move before validating it. A rejected move then hands the turn to the other player or leaves a ghost entry in the history.
- Undo that clears the cell but forgets the derived state. Counters, status, winner and whose turn it is all have to go back. Demo 3 exists to catch this.
- Claiming O(1) while scanning the board. If
checkWinner()loops over all rows and columns, it is O(N²) no matter how short the code looks. Interviewers notice. - Printing and reading input inside
BoardorGame. AScannerinside the engine means you cannot test it, cannot add a bot and cannot put it behind an API. Keep I/O at the edge. if player.isComputer()branches inside the game loop. Every new player type adds another branch. That is what thePlayerStrategyinterface removes.- Building ten classes before writing any logic.
Cell,Row,Column,Diagonal,GameManager,MoveValidator… The interviewer wants the win check and undo working. Start with the six classes above and add more only when a follow-up needs them.
The next case study, snake and ladder, is another board game, but the dice make every move for you, so the design work shifts from checking wins to testing code built on randomness. If you want one more grid game first, try Connect Four: it is K-in-a-row with gravity, so LineScanWinRule carries over and only Board.place changes.
Key takeaways
- Ask for N up front. An N x N design costs nothing extra and makes the first follow-up trivial.
- Row, column and diagonal counters give an O(1) win check; a line scan through the last move handles K-in-a-row.
- Validate before mutating, and check for a win before checking for a draw.
- Store moves on a stack. Undo must revert every piece of derived state, including the win counters.
- Keep players outside the engine behind a strategy interface; a minimax bot can then search using the same
playandundo.
Exercises
- Add
redo()to both versions. Write a test where a fresh move after an undo makes redo impossible. - Add a transposition table to
MinimaxPlayerkeyed on the board contents and the side to move. How many positions does the first move on 3x3 search now? - Change
CounterWinRuleto support three players on a 5x5 board with full-line wins, without changingGame. - Write a
ConsolePlayerthat readsrow colfrom standard input and re-prompts on anInvalidMove, again without changingGame.
Quiz
- Why can a row counter never reach +3 on a 3x3 board unless all three cells are X?
- The last empty cell is filled and it completes a column. What does your game report if the full-board check runs first?
- Why does
WinRuleneed arevertmethod, and why isLineScanWinRule.revertempty? - Why does the minimax score use
100 - depthinstead of a flat +1 for a win?
Show answers
- Each cell contributes +1 (X), -1 (O) or 0 (empty). Three cells can only sum to +3 if every one is +1. Any O or empty cell keeps the sum at 2 or below.
- A draw, which is wrong: the player who filled that cell won. Check the win first.
CounterWinRulekeeps derived state (the counters), so undo has to subtract what the move added or later checks are wrong.LineScanWinRulekeeps no state; it reads the board, and the board is restored byBoard.clear.- With a flat score, a win in 3 moves and a win in 7 look the same, so the bot may pick the slower one and seem to miss obvious wins. Subtracting depth makes faster wins worth more and slower losses less bad.