LLD

Full Designs

Tic-Tac-Toe

Everyone can play tic-tac-toe, so the interview is not about the rules. It is about a board of any size, a win check that does not rescan the board, moves that are refused without changing anything, a bot that never loses, undo, and two players whose taps arrive on two threads.

"Design tic-tac-toe" sounds like a warm-up. A weak answer draws a 3 × 3 array of chars, a Player class with a getMove() that reads the console, and a checkWinner() that tests the eight lines. All of that works for exactly one board, one kind of player and one thread.

The interviewer is checking whether the design holds up past the toy. The follow-ups push in a few directions. The board grows to 15 × 15 with five in a row. A computer plays one side. Undo is added. Two people play from two phones, and their moves reach the server on different threads. Each push breaks a different part of the weak answer, and a good design survives all of them with small, local changes.

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

One move at a glance
The caller, a screen or a server, sends Asha's tap as play(X, 1, 1) (1). Inside the game's lock, Game checks the move, puts it on the board, and asks the WinRule whether a line passes through (1, 1) (2). The caller gets back a MoveResult (3). For the computer's turn, the caller asks a MoveChooser for a cell, giving it a copy of the board (4), and plays that cell like any other move (5).The caller, a screen or a server, sends Asha's tap as play(X, 1, 1) (1). Inside the game's lock, Game checks the move, puts it on the board, and asks the WinRule whether a line passes through (1, 1) (2). The caller gets back a MoveResult (3). For the computer's turn, the caller asks a MoveChooser for a cell, giving it a copy of the board (4), and plays that cell like any other move (5).
A move arrives as a call. The game checks it under one lock, and asks a rule whether it wins. The caller, a screen or a server, sends Asha's tap as play(X, 1, 1) (1). Inside the game's lock, Game checks the move, puts it on the board, and asks the WinRule whether a line passes through (1, 1) (2). The caller gets back a MoveResult (3). For the computer's turn, the caller asks a MoveChooser for a cell, giving it a copy of the board (4), and plays that cell like any other move (5).

Ask before you design

The question is vague on purpose, and each answer below changes the code. The right-hand column says how.

QuestionWhat we assumeWhat it changes
Only 3 × 3?Any square board from 3 × 3 to 100 × 100The board size is a constructor argument, not a constant
Three in a row, always?A line length K, from 3 up to the board's sizeThe win check must work when K is smaller than the board
Who plays?Two players, X and O, and X moves firstA Mark enum with two values
Can a computer play?Yes, either side, at more than one strengthAn interface for choosing a move
How do moves arrive?From a screen or a server, as callsThe game waits for calls instead of asking players
Can two moves arrive at once?Yes: two phones, and a phone may send one tap twiceThe game must be safe when called from many threads
What happens to a bad move?It is refused with a reason, and nothing changesA result type that names the reason
Is there undo?Yes, one move at a time, as far back as the startThe game keeps its moves in order
A score across many games?Not in this versionNo match or scoreboard class

The first two rows matter most. "Any board, any line length" decides the win check. A design that tests eight fixed lines has nothing left once the board is 15 × 15 and five in a row wins.

Requirements

Functional:

  1. A game is played on an N × N board, and the first player with K of their marks in a straight line wins: across, down or on either diagonal.
  2. X moves first, and the players take turns.
  3. A move on a taken cell, off the board, out of turn, or after the game has ended is refused with its reason, and the game is left exactly as it was.
  4. A full board with no line is a draw.
  5. A computer can play either side, choosing its own cell.
  6. The last move can be taken back, repeatedly, back to the start. Taking back a winning move reopens the game.

Out of scope: more than two players, time limits, scores across games, spectators, and saving games. We come back to these at the end as follow-ups.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Two threads at once. play and undo will be called from several threads together.
  • Rules that change. The way a win is found and the way a computer chooses a move both have more than one good answer.
  • Testable. A random computer player must be repeatable in a test.

Finding the classes

From nouns to classes
Game, board, cell, mark, move, win, computer player, the game's status and the answer to a move are kept. Player, turn, referee, screen and score are crossed out. A player is a mark plus whoever calls play(). A turn is one field of Game. The game itself is the referee. The screen is outside the code, and a score across games is out of scope.Game, board, cell, mark, move, win, computer player, the game's status and the answer to a move are kept. Player, turn, referee, screen and score are crossed out. A player is a mark plus whoever calls play(). A turn is one field of Game. The game itself is the referee. The screen is outside the code, and a score across games is out of scope.
Most nouns become classes, records or enums. The player is the one to think about. Game, board, cell, mark, move, win, computer player, the game's status and the answer to a move are kept. Player, turn, referee, screen and score are crossed out. A player is a mark plus whoever calls play(). A turn is one field of Game. The game itself is the referee. The screen is outside the code, and a score across games is out of scope.

Two kept nouns are rules, not data. Deciding whether a move wins and choosing a computer's move both have more than one good answer, so each one gets an interface: WinRule and MoveChooser.

Decision

Should a player be a class?

A Player class with getMove(), and the game loop asks each player in turn

This is the textbook shape. A HumanPlayer reads the console and a BotPlayer computes. The game loop calls getMove() and waits. The game now owns the waiting, so it is tied to how input arrives: a console, a screen or a network. Two remote players cannot both be waited on by one loop without threads inside the game.

No player class. A move arrives as a call to play(mark, row, col)Our pick

The screen or the server already knows when a person taps. It calls play, and the game answers at once. A computer player becomes a MoveChooser that the caller asks for a cell, and the caller plays that cell like any other. The game never waits for anyone, which is what makes two remote players simple.

Data or behaviour?

Some classes only carry data: a cell, a move, and the answer to a move. In Java these are records: classes whose fields are fixed when they are created, with equals, hashCode and toString written for us. Fixed sets of values are enums: Mark, GameStatus and Outcome.

board/Move.javalines 5–11 of 11
/** One mark placed on one cell. */public record Move(Mark mark, Cell cell) {    public Move {        Objects.requireNonNull(mark, "mark");        Objects.requireNonNull(cell, "cell");    }}

The class diagram

The classes and how they connect
Game owns its Board and its list of moves, and uses a WinRule. ScanAroundMove and LineCounters implement WinRule. PerfectBot and RandomBot implement MoveChooser, which the caller uses, not the game. Board implements BoardView, and both interfaces read the board only through it. Game creates a MoveResult for every attempted move. Mark, Cell and the enums are drawn without arrows to keep the figure readable.Game owns its Board and its list of moves, and uses a WinRule. ScanAroundMove and LineCounters implement WinRule. PerfectBot and RandomBot implement MoveChooser, which the caller uses, not the game. Board implements BoardView, and both interfaces read the board only through it. Game creates a MoveResult for every attempted move. Mark, Cell and the enums are drawn without arrows to keep the figure readable.
Game coordinates. Rules and bots read the board only through BoardView. Game owns its Board and its list of moves, and uses a WinRule. ScanAroundMove and LineCounters implement WinRule. PerfectBot and RandomBot implement MoveChooser, which the caller uses, not the game. Board implements BoardView, and both interfaces read the board only through it. Game creates a MoveResult for every attempted move. Mark, Cell and the enums are drawn without arrows to keep the figure readable.

The classes fall into three groups:

  • Data: Mark, Cell, Move, MoveResult, GameStatus and Outcome. These are records and enums.
  • The core: Game and its Board. These hold the changing state and keep it correct under many threads.
  • Rules: WinRule with two implementations, MoveChooser with two, and BoardView, the read-only side of the board that both kinds of rule see.

Building it

Marks, cells and moves

A mark is X or O, and each mark knows its opponent. That one method replaces every turn == 'X' ? 'O' : 'X' that would otherwise be scattered around the code.

board/Mark.javalines 3–11 of 11
/** The two marks. X always moves first. */public enum Mark {    X,    O;     public Mark opponent() {        return this == X ? O : X;    }}

A Cell is a row and a column, counted from 0 at the top left. A Move is a mark on a cell. Neither checks that the cell is on the board, because only the game knows the board's size.

The board, and what others may see of it

Board keeps the marks in a 2D array and counts the filled cells, so isFull() is one comparison instead of a scan.

game/Board.javalines 16–53 of 89
final class Board implements BoardView {    private final Mark[][] cells;    private int filled;     Board(int size) {        cells = new Mark[size][size];    }    @Override    public boolean isFull() {        return filled == cells.length * cells.length;    }

Only Game should change a board, so the class and its changing methods are package-private. place and clear refuse a cell in the wrong state, so a bug in the game shows up at once instead of as a quietly wrong board. copy() builds the separate board that bots read, which the next Decision explains.

game/Board.javalines 68–88 of 89
    void place(Move move) {        Cell cell = move.cell();        if (cells[cell.row()][cell.col()] != null) {            throw new IllegalStateException(cell + " is already taken");        }        cells[cell.row()][cell.col()] = move.mark();        filled++;    }     void clear(Cell cell) {        if (cells[cell.row()][cell.col()] == null) {            throw new IllegalStateException(cell + " is already empty");        }        cells[cell.row()][cell.col()] = null;        filled--;    }     /** A copy that later moves do not change. */    Board copy() {        return new Board(this);    }

Everything outside the game reads a board through BoardView: its size, whether a cell is on it, the mark on a cell, whether it is full, and its empty cells.

board/BoardView.javalines 6–19 of 19
/** What a rule or a bot may read about a board. Nothing here changes it. */public interface BoardView {    int size();     boolean contains(int row, int col);     /** The mark on a cell, or empty. Throws IllegalArgumentException for a cell off the board. */    Optional<Mark> markAt(int row, int col);     boolean isFull();     /** The empty cells, row by row from the top left. */    List<Cell> emptyCells();}
Decision

What does a bot get to read?

The live Board object

A bot holding the game's own board can call place on it, by accident or on purpose. The mark would skip every check play makes, and the turn would not change.

A read-only view of the live board

The bot can no longer change anything. But on a server, the other player's move can land while the bot is still reading. The bot would see half of one position and half of the next, and it would be reading the array with no lock.

A copy of the board, through BoardViewOur pick

game.board() copies the board under the game's lock and hands back the copy as a BoardView. The bot reads one position, and nothing changes under it. The copy costs one pass over the cells, which is 10,000 cells on the largest board, once per bot move.

Starting a game

Game takes the board's size, the line length and the rule that finds a win. It checks the first two before it builds anything.

game/Game.javalines 35–46 of 151
    public Game(int size, int lineToWin, WinRule winRule) {        if (size < MIN_SIZE || size > MAX_SIZE) {            throw new IllegalArgumentException("A board is " + MIN_SIZE + " to " + MAX_SIZE + " cells wide, not " + size);        }        if (lineToWin < MIN_SIZE || lineToWin > size) {            throw new IllegalArgumentException("A winning line is " + MIN_SIZE + " to " + size + " long, not " + lineToWin);        }        this.winRule = Objects.requireNonNull(winRule, "winRule");        winRule.attach(size, lineToWin);        this.board = new Board(size);        this.lineToWin = lineToWin;    }

A board from 3 × 3 to 100 × 100 is accepted, and the line must be at least 3 long and no longer than the board. The game checks both limits itself, even when the rule it was given would accept more. The upper limit also keeps each copy of the board that a bot receives at 10,000 cells or fewer. Then the game calls the rule's attach, which we come back to when we meet the rules.

Playing a move

play is the one way a mark reaches the board. It checks the move in a fixed order, puts it on the board, asks the rule whether it wins, and records it.

game/Game.javalines 48–86 of 151
    public MoveResult play(Mark mark, int row, int col) {        Objects.requireNonNull(mark, "mark");        synchronized (lock) {            refuseCallsFromTheRule();            if (status != GameStatus.IN_PROGRESS) {                return refuse(Outcome.GAME_OVER);            }            if (mark != turn) {                return refuse(Outcome.NOT_YOUR_TURN);            }            if (!board.contains(row, col)) {                return refuse(Outcome.OUT_OF_RANGE);            }            if (board.markAt(row, col).isPresent()) {                return refuse(Outcome.CELL_TAKEN);            }            Move move = new Move(mark, new Cell(row, col));            board.place(move);            boolean won;            judging = true;            try {                won = winRule.placed(board, move);            } catch (Throwable e) {                board.clear(move.cell());                throw e;            } finally {                judging = false;            }            moves.add(move);            if (won) {                status = GameStatus.wonBy(mark);            } else if (board.isFull()) {                status = GameStatus.DRAW;            } else {                turn = mark.opponent();            }            return new MoveResult(Outcome.PLACED, status);        }    }

The four checks run in this order: the game is still on, it is this mark's turn, the cell is on the board, and the cell is free. Each failure returns before anything is written, so a refused move leaves the board, the turn and the move list exactly as they were.

The order also decides which reason a player sees when more than one applies. A tap after the game has ended gets GAME_OVER even if it is also out of turn, because the game being over is what the screen should say.

The win rule is code the game was given, and it runs after the mark is already on the board. If it throws, the catch takes the mark off again before the exception goes on, so a broken rule cannot leave a mark that no move list knows about. The catch takes any Throwable, so an Error, or a checked exception a rule throws by a trick, also leaves the board as it was. The judging flag and the first line of the block guard against a rule calling back into the game; we come back to them with the lock.

Decision

A refused move: an exception, or an answer?

Throw an exception for every bad move

A tap on a taken cell is something a person does every few games. Treating it as an exception makes the screen wrap every tap in a try, and it mixes these ordinary refusals with real bugs such as a null mark.

Return an answer for what a person does, and throw only for programmer errorsOur pick

play returns a MoveResult with an Outcome: PLACED, GAME_OVER, NOT_YOUR_TURN, OUT_OF_RANGE or CELL_TAKEN. The screen shows the reason. Mistakes only a programmer can make throw instead: a null mark, a board of 2 × 2, a line longer than the board, or a rule that throws.

Who has won

A move can only complete a line that passes through it. The WinRule interface is built around that: the game calls placed once for each move, after it lands, and the rule says whether it wins. The board it receives is the game's live board, valid only during the call. removed is called when undo takes a move back.

win/WinRule.javalines 6–32 of 32
/** * Decides whether a move wins. A rule object belongs to one game, because a * rule may keep counts about that game's board. */public interface WinRule {    /**     * Called once, by the game that will use this rule. Throws     * IllegalArgumentException if the rule cannot judge this board, and     * IllegalStateException if the rule already belongs to a game.     */    void attach(int size, int lineToWin);     /**     * Called once for each move, after it is on the board. True if it gives     * its mark a winning line. The board is the live one and is valid only     * during this call; a rule must not keep it or call back into the game.     * If this throws, the rule leaves its own counts as they were; the game     * restores only the board.     */    boolean placed(BoardView board, Move move);     /**     * Called when undo takes a move back, before it leaves the board. If this     * throws, the rule leaves its own counts as they were.     */    void removed(Move move);}

The first rule, ScanAroundMove, looks along the four lines through the new mark. On each line it counts matching marks outwards in both directions, and stops at the first cell that is empty, the other player's, or off the board.

win/ScanAroundMove.javalines 29–58 of 64
    @Override    public boolean placed(BoardView board, Move move) {        if (lineToWin == 0) {            throw new IllegalStateException("This rule is not attached to a game");        }        for (int[] direction : DIRECTIONS) {            int inLine = 1                    + countFrom(board, move, direction[0], direction[1])                    + countFrom(board, move, -direction[0], -direction[1]);            if (inLine >= lineToWin) {                return true;            }        }        return false;    }     /** The same marks next to the move in one direction, stopping once a line is certain. */    private int countFrom(BoardView board, Move move, int rowStep, int colStep) {        int count = 0;        int row = move.cell().row() + rowStep;        int col = move.cell().col() + colStep;        while (count < lineToWin - 1                && board.contains(row, col)                && board.markAt(row, col).filter(mark -> mark == move.mark()).isPresent()) {            count++;            row += rowStep;            col += colStep;        }        return count;    }

countFrom also stops once it has found lineToWin - 1 marks, because a line is already certain then. So a move reads at most 2 × (K − 1) cells on each of the four lines. That is at most 32 cells for five in a row, whatever the size of the board. Five in a row also counts when four wins, because inLine >= lineToWin accepts a longer line.

The second rule, LineCounters, keeps a count of each player's marks on every row, every column and the two long diagonals. A move adds one to at most four counts, and wins when one of them reaches the board's size.

win/LineCounters.javalines 46–65 of 66
    private boolean change(Move move, int by) {        if (rows == null) {            throw new IllegalStateException("This rule is not attached to a game");        }        int mark = move.mark().ordinal();        int row = move.cell().row();        int col = move.cell().col();        rows[mark][row] += by;        columns[mark][col] += by;        if (row == col) {            diagonal[mark] += by;        }        if (row + col == size - 1) {            antiDiagonal[mark] += by;        }        return rows[mark][row] == size                || columns[mark][col] == size                || (row == col && diagonal[mark] == size)                || (row + col == size - 1 && antiDiagonal[mark] == size);    }

removed calls the same method with -1, so undo takes the counts back. The counts only mean "a line" when the line is the whole row, so LineCounters refuses a game whose line is shorter than the board.

Two ways to find a win
On the left, X's mark at (2, 2) adds one to row 2, column 2 and the diagonal, and the diagonal reaches 3, the size of the board, so X wins. On the right, on a 6 × 6 board where four wins, the scan reads outwards from (3, 3) along four lines. The dashed cells are the ones it may read, and it finds four X from (1, 1) to (4, 4).On the left, X's mark at (2, 2) adds one to row 2, column 2 and the diagonal, and the diagonal reaches 3, the size of the board, so X wins. On the right, on a 6 × 6 board where four wins, the scan reads outwards from (3, 3) along four lines. The dashed cells are the ones it may read, and it finds four X from (1, 1) to (4, 4).
Counters change a few numbers per move. A scan reads a few cells per move. On the left, X's mark at (2, 2) adds one to row 2, column 2 and the diagonal, and the diagonal reaches 3, the size of the board, so X wins. On the right, on a 6 × 6 board where four wins, the scan reads outwards from (3, 3) along four lines. The dashed cells are the ones it may read, and it finds four X from (1, 1) to (4, 4).
Decision

Count each line, or scan around the last move?

Rescan the whole board after every move

Checking every row, column and diagonal costs time in proportion to the whole board, after every move. On 3 × 3 nobody would notice. On 100 × 100 it reads 10,000 cells to learn about one.

Counters per row, column and diagonal

Each move changes at most four counts, so the check takes the same time on any board. But the counts only work when the line is as long as the board, which rules out five in a row on 15 × 15. They are also state that undo must reverse exactly.

A scan around the last move by default; counters only when the line is the whole boardOur pick

The scan reads at most 2 × (K − 1) cells on each of four lines, whatever the board size, and works for any line length. It stores nothing, so undo has nothing to reverse. When the line is the whole board, as in the demo's 3 × 3 game, LineCounters is a fine choice too, and the interface makes the choice a constructor argument.

A rule that keeps counts belongs to one game. attach enforces that: the game calls it once in its constructor, and a rule that already belongs to a game throws IllegalStateException. Without that check, two games sharing one LineCounters would add up each other's marks.

A win, a draw, or neither

After the move is recorded, play decides what happens next. A win ends the game, a full board with no line is a draw, and otherwise the turn passes.

game/Game.javalines 76–84 of 151
            moves.add(move);            if (won) {                status = GameStatus.wonBy(mark);            } else if (board.isFull()) {                status = GameStatus.DRAW;            } else {                turn = mark.opponent();            }            return new MoveResult(Outcome.PLACED, status);

The order matters. The last free cell can complete a line, and checking for a win first makes that a win, not a draw. When the game ends, the turn does not change, and turn() answers empty.

Decision

When is a game a draw?

As soon as no line can be won by either player

On a big board this ends a hopeless game early. But knowing that no line can still be won means checking every possible line after each move, which is the whole-board scan we just avoided.

When the board is full and nobody has a lineOur pick

board.isFull() compares one counter with the board's area, so the check costs one comparison per move. An early draw can be added later as its own check, without changing anything else.

Computer players

A computer player is anything that picks a free cell for a mark. The caller asks a MoveChooser, then plays the cell through play, so a bot's move gets the same checks as a person's.

bot/MoveChooser.javalines 7–11 of 11
/** Picks a computer player's next cell. The caller then plays it with Game.play. */public interface MoveChooser {    /** A free cell for `me`. Throws IllegalStateException if the board has none. */    Cell choose(BoardView board, Mark me);}

PerfectBot tries every way the rest of a 3 × 3 game can go. For each free cell, it scores what happens if both players then play their best, and it picks the highest score.

bot/PerfectBot.javalines 60–78 of 112
    private static int score(Mark[] cells, Mark toMove, int depth) {        Mark winner = winner(cells);        if (winner != null) {            int value = 10 - depth;            return winner == toMove ? value : -value;        }        if (isFull(cells)) {            return 0;        }        int best = Integer.MIN_VALUE;        for (int i = 0; i < cells.length; i++) {            if (cells[i] == null) {                cells[i] = toMove;                best = Math.max(best, -score(cells, toMove.opponent(), depth + 1));                cells[i] = null;            }        }        return best;    }

choose first checks that it was asked for the side whose turn it is, by counting the Xs and Os, and throws IllegalArgumentException if not. The score is for the player about to move: positive if they can force a win, negative if they will lose, and 0 for a draw. A win scores 10 - depth, where depth counts the moves played since the bot's turn, so a quicker win scores higher. Without that, a bot that can win now might choose a slower win, which wins all the same but takes longer.

How the perfect bot chooses
O is to move with four free cells. Playing (1, 2) wins at once and scores +9. Playing (0, 2) blocks X and still wins two moves later, so it scores +7. Playing (2, 0) or (2, 1) lets X win next move, so both score −8. The bot plays (1, 2).O is to move with four free cells. Playing (1, 2) wins at once and scores +9. Playing (0, 2) blocks X and still wins two moves later, so it scores +7. Playing (2, 0) or (2, 1) lets X win next move, so both score −8. The bot plays (1, 2).
Each free cell gets a score, and the bot plays the highest. O is to move with four free cells. Playing (1, 2) wins at once and scores +9. Playing (0, 2) blocks X and still wins two moves later, so it scores +7. Playing (2, 0) or (2, 1) lets X win next move, so both score −8. The bot plays (1, 2).
Decision

How should the perfect bot choose its move?

A list of rules: win if you can, block if you must, take the centre, then a corner

Short rule lists are easy to read and fast. But a few positions need a move no simple rule names, and finding the gaps means testing every game anyway. A rule list that misses one position can lose.

Try every way the game can go, on 3 × 3 onlyOur pick

From an empty 3 × 3 board the search visits about 550,000 positions, and its answer is exact, so it never loses. On a bigger board the number of positions explodes, so PerfectBot refuses any board that is not 3 × 3 with an IllegalArgumentException. A bot for big boards would search a few moves deep and guess the rest, which is a different class behind the same interface.

Undo

The game keeps its moves in order, so undo can reverse the last one: take its mark off the board, give the turn back, and reopen the game if that move had ended it.

game/Game.javalines 89–108 of 151
    public Optional<Move> undo() {        synchronized (lock) {            refuseCallsFromTheRule();            if (moves.isEmpty()) {                return Optional.empty();            }            Move last = moves.get(moves.size() - 1);            judging = true;            try {                winRule.removed(last);            } finally {                judging = false;            }            board.clear(last.cell());            moves.remove(moves.size() - 1);            turn = last.mark();            status = GameStatus.IN_PROGRESS;            return Optional.of(last);        }    }

undo reads the last move without removing it, tells the rule with judging set, clears the cell, and only then removes the move from the list. If removed throws, the move is still in the list and still on the board, so the game's own state is unchanged; a rule that keeps counts must likewise leave them as they were.

undo takes back the last move, whoever made it. In a game against the bot, a player who wants their own move back calls it twice: once for the bot's reply and once for their move. On a server, deciding who may ask for an undo is the server's job, and the game only keeps the order right.

Decision

Undo: reverse the last move, or keep a copy of the board?

Save a copy of the board before every move

Undo becomes "put the old copy back", which is hard to get wrong. But every move copies the whole board: 10,000 cells per move on 100 × 100. The rule's counts would need copies too.

Keep the moves, and reverse the last oneOur pick

A move is a mark and a cell, so reversing it means clearing one cell and giving the turn back. The move list is also the game's history, ready for a replay, at the cost of one small record per move.

Two players, two threads

On a server, Asha's tap and Ravi's tap arrive on different threads, and a phone can send one tap twice. Every method of Game that touches changing state takes one private lock, so the four checks, the placement and the turn change in play happen as one step.

The race the lock prevents is a check-then-act race. Two copies of Asha's tap at (0, 1) both read "X's turn" and "(0, 1) is free". Without the lock, the second copy either crashes on the board's "already taken" check or writes the same cell again, and the move list gains two moves for one tap.

One tap, sent twice
On the left, with no lock, both copies of Asha's tap at (0, 1) see that it is X's turn and that the cell is free before either places a mark. The second copy then writes the same cell again, or crashes on the board's 'already taken' check. On the right, the first copy holds the game's lock while it checks and places. The second copy waits, then finds it is O's turn and is refused with NOT_YOUR_TURN.On the left, with no lock, both copies of Asha's tap at (0, 1) see that it is X's turn and that the cell is free before either places a mark. The second copy then writes the same cell again, or crashes on the board's 'already taken' check. On the right, the first copy holds the game's lock while it checks and places. The second copy waits, then finds it is O's turn and is refused with NOT_YOUR_TURN.
Without the lock, the turn check and the placement are two steps. With it, they are one. On the left, with no lock, both copies of Asha's tap at (0, 1) see that it is X's turn and that the cell is free before either places a mark. The second copy then writes the same cell again, or crashes on the board's 'already taken' check. On the right, the first copy holds the game's lock while it checks and places. The second copy waits, then finds it is O's turn and is refused with NOT_YOUR_TURN.

demo/RaceCheck.java plays 2,000 games on a 4 × 4 board, with four threads per game: two tap for X and two for O, each picking its own random free cells, like a player with the game open on two phones. After each game it checks that the moves alternate X, O, X, that no cell is used twice, and that the board holds exactly the moves in the list.

$ java demo.RaceCheck
games played:         2000
moves placed:         29035
taps refused:         93933
taps that crashed:    0
games breaking rules: 0

With the lock, the last two lines are 0. We also ran it with the lock removed from play. In every run, around a hundred of the 2,000 games broke a rule, and thousands of taps crashed. Almost all of those crashes came from the re-entry guard below: without the lock, one thread reads the judging flag another thread has set, and takes its own move for a call back. A few taps crashed on the board's own "already taken" check.

Decision

Where does the lock go?

No lock: one thread per game, with moves queued

A server can give each game its own queue and one worker thread. That works, but Game would then be unsafe to use any other way, and the rule would live in server code far from the class it protects.

Lock the board, not the game

The board's methods could be synchronized. But the turn check, the placement and the turn change would still be separate steps, and the double tap would still get through.

One private lock per game, around each public methodOur pick

The lock is a private object, so outside code cannot hold it and stall a game. play holds it for a few array reads and writes, plus the win rule's call, which reads at most 8 × (K − 1) cells. board() holds it longer, while it copies up to 10,000 cells. Different games never share a lock, so a server can run thousands of games side by side.

The win rule runs under the lock, so a slow rule would hold up both players. Java's synchronized lock is reentrant, so a rule that held the Game could call play from inside placed and get straight in, making a second move in the middle of judging the first. play sets judging while the rule runs, and every method that changes the game starts by refusing such a call:

game/Game.javalines 141–146 of 151
    /** The lock is re-entrant, so without this a rule could make a move in the middle of judging one. */    private void refuseCallsFromTheRule() {        if (judging) {            throw new IllegalStateException("A win rule must not call back into the game");        }    }

The nested call throws IllegalStateException, and the nested move never happens. If the rule lets that exception out, the catch in play takes the judged mark off. A rule that keeps counts must leave them as they were when it throws, because the game restores only the board. A bot, by contrast, runs outside the lock: the caller asks it for a cell using a copy, and only the final play takes the lock.

The final design

Game is the core. It owns the board, the move list, the turn, the status and the one lock, and it reaches the rule that finds a win only through WinRule. Computer players stay outside it: the caller asks a MoveChooser for a cell and plays it like any other move.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 1, 7 and 8. BoardView carries 2, MoveResult carries 3, ScanAroundMove carries 4, GameStatus carries 5 and PerfectBot carries 6. WinRule and MoveChooser each carry a Strategy tag.The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 1, 7 and 8. BoardView carries 2, MoveResult carries 3, ScanAroundMove carries 4, GameStatus carries 5 and PerfectBot carries 6. WinRule and MoveChooser each carry a Strategy tag.
Each decision lands on one class. Two interfaces carry a pattern. The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 1, 7 and 8. BoardView carries 2, MoveResult carries 3, ScanAroundMove carries 4, GameStatus carries 5 and PerfectBot carries 6. WinRule and MoveChooser each carry a Strategy tag.
S.No.The questionWhat we choseWhy
1Should a player be a class?No player class. A move arrives as a call to play(mark, row, col)The game never waits for anyone, so remote players are simple
2What does a bot get to read?A copy of the board, through BoardViewThe bot reads one position that nothing changes under it
3A refused move: an exception, or an answer?Return an answer for what a person does, and throw only for programmer errorsThe screen shows the reason, and bugs stay loud
4Count each line, or scan around the last move?A scan around the last move by default; counters only when the line is the whole boardThe scan works for any line length and stores nothing to undo
5When is a game a draw?When the board is full and nobody has a lineIt costs one comparison per move
6How should the perfect bot choose its move?Try every way the game can go, on 3 × 3 onlyThe search is exact, so it never loses
7Undo: reverse the last move, or keep a copy of the board?Keep the moves, and reverse the last oneOne cell changes per undo, and the list is the history
8Where does the lock go?One private lock per game, around each public methodThe checks, the placement and the turn change happen as one step

Here is Asha's first move against the bot, end to end:

  1. The screen calls play(X, 1, 1). play checks that the mark is not null, then takes the game's lock with synchronized (lock).
  2. Under the lock, play checks that the game is on, that it is X's turn, that board.contains(1, 1), and that board.markAt(1, 1) is empty. All four pass.
  3. board.place puts X on (1, 1). Then winRule.placed runs with judging set: this is the outside call, code the game was given, and it runs under the lock. If it throws, board.clear takes the mark off before the exception goes on.
  4. play adds the move to moves. There is no line and the board is not full, so it sets the turn to O and returns MoveResult(PLACED, IN_PROGRESS). The lock is released as the block ends.
  5. For the bot's turn, the caller gets a copy from game.board(), asks PerfectBot.choose for a cell, and plays it with play(O, 0, 0), which repeats steps 1 to 4.

Undo follows the same path backwards. undo takes the same lock, tells the rule with removed, clears the cell, and only then drops the move from the list and gives the turn back.

The complete code

Click a class name in any file to open it, or use the tree. Find searches every file.

gameGame.java
package game; import java.util.ArrayList;import java.util.List;import java.util.Objects;import java.util.Optional; import board.BoardView;import board.Cell;import board.Mark;import board.Move;import win.WinRule; /** * One game on a size × size board, won by lineToWin marks in a row. * Players are not objects here: a move arrives as a call to play(), from a * screen, a server or a bot. Every method that reads or changes the game's * state takes one lock, so two players' moves arriving on two threads are * handled one at a time. */public class Game {    public static final int MIN_SIZE = 3;    public static final int MAX_SIZE = 100;     private final Object lock = new Object();    private final Board board;    private final int lineToWin;    private final WinRule winRule;    private final List<Move> moves = new ArrayList<>();    private Mark turn = Mark.X;    private GameStatus status = GameStatus.IN_PROGRESS;    /** True while the win rule runs, so a rule that calls back into the game is refused. */    private boolean judging;     public Game(int size, int lineToWin, WinRule winRule) {        if (size < MIN_SIZE || size > MAX_SIZE) {            throw new IllegalArgumentException("A board is " + MIN_SIZE + " to " + MAX_SIZE + " cells wide, not " + size);        }        if (lineToWin < MIN_SIZE || lineToWin > size) {            throw new IllegalArgumentException("A winning line is " + MIN_SIZE + " to " + size + " long, not " + lineToWin);        }        this.winRule = Objects.requireNonNull(winRule, "winRule");        winRule.attach(size, lineToWin);        this.board = new Board(size);        this.lineToWin = lineToWin;    }     public MoveResult play(Mark mark, int row, int col) {        Objects.requireNonNull(mark, "mark");        synchronized (lock) {            refuseCallsFromTheRule();            if (status != GameStatus.IN_PROGRESS) {                return refuse(Outcome.GAME_OVER);            }            if (mark != turn) {                return refuse(Outcome.NOT_YOUR_TURN);            }            if (!board.contains(row, col)) {                return refuse(Outcome.OUT_OF_RANGE);            }            if (board.markAt(row, col).isPresent()) {                return refuse(Outcome.CELL_TAKEN);            }            Move move = new Move(mark, new Cell(row, col));            board.place(move);            boolean won;            judging = true;            try {                won = winRule.placed(board, move);            } catch (Throwable e) {                board.clear(move.cell());                throw e;            } finally {                judging = false;            }            moves.add(move);            if (won) {                status = GameStatus.wonBy(mark);            } else if (board.isFull()) {                status = GameStatus.DRAW;            } else {                turn = mark.opponent();            }            return new MoveResult(Outcome.PLACED, status);        }    }     /** Takes back the last move, whoever made it. Empty if there is none. */    public Optional<Move> undo() {        synchronized (lock) {            refuseCallsFromTheRule();            if (moves.isEmpty()) {                return Optional.empty();            }            Move last = moves.get(moves.size() - 1);            judging = true;            try {                winRule.removed(last);            } finally {                judging = false;            }            board.clear(last.cell());            moves.remove(moves.size() - 1);            turn = last.mark();            status = GameStatus.IN_PROGRESS;            return Optional.of(last);        }    }     public GameStatus status() {        synchronized (lock) {            return status;        }    }     /** Whose move it is, or empty once the game is over. */    public Optional<Mark> turn() {        synchronized (lock) {            return status == GameStatus.IN_PROGRESS ? Optional.of(turn) : Optional.empty();        }    }     /** The moves so far, first to last. */    public List<Move> moves() {        synchronized (lock) {            return List.copyOf(moves);        }    }     /** A copy of the board as it is now. Later moves do not change it. */    public BoardView board() {        synchronized (lock) {            return board.copy();        }    }     public int lineToWin() {        return lineToWin;    }     /** The lock is re-entrant, so without this a rule could make a move in the middle of judging one. */    private void refuseCallsFromTheRule() {        if (judging) {            throw new IllegalStateException("A win rule must not call back into the game");        }    }     private MoveResult refuse(Outcome outcome) {        return new MoveResult(outcome, status);    }}
Click a class name in the code to open its fileJava · 151 lines · 893 in the project

The demo plays two games and then shows one programming mistake being refused:

$ java demo.Main
== 3 x 3, three in a row. Asha is X, PerfectBot is O ==
Asha plays (1, 1): PLACED, IN_PROGRESS
Asha taps (0, 0) before the bot moves: NOT_YOUR_TURN, IN_PROGRESS
PerfectBot plays (0, 0): PLACED, IN_PROGRESS
Asha taps the bot's cell (0, 0): CELL_TAKEN, IN_PROGRESS
Asha taps (3, 0): OUT_OF_RANGE, IN_PROGRESS
Asha plays (2, 2): PLACED, IN_PROGRESS
Asha takes it back: X at (2, 2), turn X
Asha plays (0, 2): PLACED, IN_PROGRESS
PerfectBot plays (2, 0): PLACED, IN_PROGRESS
Asha plays (2, 1): PLACED, IN_PROGRESS
PerfectBot plays (1, 0): PLACED, O_WON
  O . X
  O X .
  O X .
Asha taps (0, 0) after the end: GAME_OVER, O_WON

== 5 x 5, four in a row. Ravi is X, Meera is O ==
Ravi plays (0, 1): PLACED, IN_PROGRESS
Meera plays (4, 0): PLACED, IN_PROGRESS
Ravi plays (1, 2): PLACED, IN_PROGRESS
Meera plays (4, 1): PLACED, IN_PROGRESS
Ravi plays (2, 3): PLACED, IN_PROGRESS
Meera plays (4, 2): PLACED, IN_PROGRESS
Ravi plays (3, 4): PLACED, X_WON
  . X . . .
  . . X . .
  . . . X .
  . . . . X
  O O O . .
Ravi takes back the winning move X at (3, 4): IN_PROGRESS, turn X
Meera's late tap at (4, 3) is still refused: NOT_YOUR_TURN, IN_PROGRESS

== A rule belongs to one game ==
Second game refused: This rule already belongs to a game

Notice four things in the output:

  • Every kind of refusal appears once in the first game, and each one leaves the game as it was. Asha taps out of turn, on the bot's cell, off the board, and after the end.
  • The bot blocks, then wins. After Asha's (0, 2), PerfectBot takes (2, 0), which blocks her diagonal and gives it two Os in the left column. Asha does not block (1, 0), and the bot wins there.
  • Undoing a win reopens the game. Ravi's four on a diagonal of the 5 × 5 board ends the game. After undo, the status is IN_PROGRESS and it is X's turn again, so Meera's tap is refused as NOT_YOUR_TURN, not as GAME_OVER.
  • A rule object cannot serve two games. The second Game built with the same ScanAroundMove is refused when it calls attach.

Follow-up questions

The interviewer asksWhat changesWhat does not
Fifteen by fifteen, five in a row?Nothing in the game: new Game(15, 5, new ScanAroundMove()). PerfectBot cannot play itGame, the board, the win rules
Five in a row, but six does not count?A new WinRule that needs exactly KGame, the board, the bots
A computer player for big boards?A new MoveChooser that searches a few moves deep and scores the restGame, the win rules
Three players?Mark gains a value and opponent() becomes "next". GameStatus needs a win per mark, because wonBy maps only X and O. PerfectBot works only for two playersScanAroundMove, the board
A time limit per move?Game takes a Clock and refuses a late move with a new OutcomeThe board, the rules, the bots
Show the game live to spectators?Game tells listeners after each placed move: the Observer patternThe rules, the bots
Save a game and replay it?Store the move list; a replay calls play for each moveGame's logic
Undo only when both players agree?The server asks the other player before calling undoGame

Most of these change one class or add one. Saying that in the interview, with the class named, is the point of the follow-up. It shows that each rule that changes has its own place to change.

What the interviewer looks for

Mid-level

A mid-level candidate builds a working 3 × 3 game: a board, turns, refused moves and a correct check for all eight lines. They can explain the code and fix a bug when one is pointed out.

Senior

A senior candidate makes the board size and the line length parameters from the start. They check only the lines through the last move, keep the reasons for a refused move separate from real errors, and add undo without copying the board. They put the win check behind an interface and can name the cost of each option.

Staff+

A staff candidate also sees the game as a server's object: moves arriving on many threads, a double-sent tap, a bot reading a board that changes under it. They put one lock around each check-and-place, hand bots a copy, and explain why the perfect bot is limited to 3 × 3 and what replaces it on a big board.

Common mistakes

  • Hard-coding 3 × 3. A checkWinner() that tests eight fixed lines has to be thrown away for any other board.
  • Rescanning the board after every move. It works, and it reads every cell to learn about one.
  • A Player with a blocking getMove(). The game ends up owning input and waiting, and two remote players need threads inside it.
  • Throwing for a taken cell. A person does it every few games, and the screen ends up catching exceptions for ordinary taps.
  • Checking for a draw before the win. The last free cell can complete a line, and that game is a win.
  • Letting a bot read the live board. It can change the board, or read it while the other player's move lands.
  • Checking the turn and placing the mark as two steps with no lock. A tap sent twice can record two moves for one tap.

Summary

  • A move arrives as a call to play, so the game never waits for a player and works the same for a screen, a server or a bot.
  • Refused moves return an Outcome with the reason and change nothing; programmer errors throw.
  • A move can only complete a line through itself, so ScanAroundMove reads at most 2 × (K − 1) cells on each of four lines, for any board and any K.
  • LineCounters is the faster choice when the line is the whole board, and the WinRule interface makes it a constructor argument.
  • PerfectBot searches every way a 3 × 3 game can go and never loses; it refuses bigger boards.
  • Undo reverses the last move from the move list, and reverses the rule's counts with it.
  • One private lock per game turns the checks, the placement and the turn change into one step, so a tap sent twice cannot record two moves.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.