AlgoViz

Design tic-tac-toe

easy 70 min

Model a game everybody knows: marks on a grid, turns, a full line wins.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:32

Tic-tac-toe LLD in 90 seconds

1:27Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Tic-tac-toe in a low-level design round is a referee: an object that stores a grid, allows legal moves in turn, and says when the game is won or drawn. Screens, players and scores are around it.

It is a small state machine with a history. Its state changes only through one method, which first asks whether it may. Orders, documents and accounts have the same shape.

The technical idea in it is incremental checking: do not ask whether there is a winner somewhere, ask what the last move can have changed.

Why it exists

It needs no explanation, so an interviewer sees your habits at once: where input goes, where rules go, what is checked before what.

It is small enough to be proved by trying everything. Few programs give you the chance to check all runs, and using it says much about a person.

It grows in every direction: size, players, rules, opponents, networks. Each wish presses on another seam of the design.

A short history

  1. 1858

    The name noughts and crosses is found in print, in an issue of Notes and Queries. The game itself is much older.

  2. 1952

    Sandy Douglas writes OXO, a program that plays the game on the EDSAC computer in Cambridge: one of the first games with a screen.

  3. 1961

    Donald Michie builds MENACE with Roger Chambers: matchboxes with beads that learn the game. One box for each position, up to turning and mirroring.

  4. 1994

    The book Design Patterns describes Command, with undo as its example of use.

Words to know

Mark
X or O. Not the player: the player is whoever uses it.
Line
A row, a column or one of two diagonals: 2n + 2 of them.
Incremental check
Looking only at what the last change can have affected.
Legal move
The game goes on, it is your turn, the square is inside and empty.
Invariant
A sentence that is true after every call, such as: a count is the number of marks on a line.
Opposite or inverse
The operation that brings back the state before another one.
Replay
Building the state again by playing the stored moves.
Minimax
The value of a position is the best of what the opponent leaves, seen from each side in turn.
Position
What lies where and who moves. Many games lead to one position.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

A move is asked for. Going on, right turn, inside, empty

Understand it

Start here

Pebbles and shells on the sand

Two children, nine squares in the sand, and the sea behind them. Asha has pebbles, Noor has shells. Watch four things: who is allowed to play, what a move changes, how somebody notices a win, and what is left when the water comes.

One game, one tide

The board stores, the sticks see, the children take turns, and the tide shows what should have been kept elsewhere.

What an interviewer looks for here

  • Where is the turn checked?

    In the game, for every caller. Not in the screen and not in the player.

  • What does a move change?

    One square and at most four lines. A win check that knows this is O(1).

  • Is a refused move free?

    After an error the state is exactly what it was.

  • Can it grow?

    Size, players and undo arrive as follow-ups. None of them should open Board and Game at the same time.

Questions

Six questions, and what each answer changes

AskIf the answer isThen
Only 3 by 3, or any size?Any size nNo constants, and a win check that does not grow with n
Is a win always a full line?YesCounting works. If k in a row is enough, it does not: see four in a row
Two people, or a computer?Perhaps bothA player is whoever calls. An interface when the computer arrives
May a move be taken back?YesMoves are stored, and each change has an opposite
One game, or many at the same time?One, for nowNo lock. A game has no global state, so many are easy later
Screen, saving, scores?OutNothing in the game prints or reads
The second question is the most expensive one to forget. It decides whether the clever win check is right at all.

States

The life of a game

Four states, three of them final

The order of the two checks matters. A last move can fill the board and win. Ask for the win first.

A call, from the outside to the squares

Each question is asked by the object that knows the answer. Only the board knows whether a square is taken.

Design, first try

The design most people write first

The design to avoid: the game is inside the screen, and the winner is inside the board

TicTacToe- board: char[3][3]- player1, player2: Player- moveCount: int+ run()- readInput(): int[2]- printBoard()- checkWinner(): char- switchPlayer()

1/4One class from keyboard to verdict

Reading, printing, turns and winning in one class. There is no way to ask who has won without somebody typing.

owns (dies together)extends (is a)

Python
class TicTacToe:    def __init__(self):        self.board = [[" "] * 3] * 3                      # one row, seen three times        self.player = "X"    def run(self):        while True:            r, c = map(int, input().split())            self.board[r][c] = self.player                # taken? outside? -1 is a place in Python            if self.check_winner():                print(self.player, "won")                return            self.player = "O" if self.player == "X" else "X"    def check_winner(self):        for p in ["X", "O"]:            for i in range(3):                if all(self.board[i][j] == p for j in range(3)): return True                if all(self.board[j][i] == p for j in range(3)): return True        return False                                      # diagonals? a draw?
Before. Five bugs in twenty lines: three rows that are one list, no check for taken or outside, a negative index that silently works, no diagonals and no draw, and no way to test any of it without a keyboard.

What each bug teaches

  1. 1

    [[" "] * 3] * 3

    Three references to one row. A mark appears in all three. Build each row by itself.

  2. 2

    Minus one

    board[-1][0] is the last row in Python. Checking "too large" only is half a check.

  3. 3

    Input inside the rules

    A test must fake a keyboard. A second screen must copy the rules.

  4. 4

    Two marks in the check

    Only the mark that has just been played can have completed a line. Looking for the other one is wasted and confusing.

  5. 5

    No end

    A full board without a line loops for ever, asking for a place that is not there.

Design, better

The design to reach

The design to reach: the board stores, the counts see wins, the game enforces

Game- moves: List<Move>- turn: Mark- status: Status+ play(mark, row, col): Status+ undo(): Move+ legal(): List<Square>+ rows(): List<String>«enum»StatusPLAYING, DRAWX_WON, O_WON

1/5The referee

Game knows whose turn it is and whether the game goes on. It is the only way to change anything, so a rule checked here is a rule.

owns (dies together)uses

Python
game = Game()game.play(Mark.X, 1, 1)         # Status.PLAYINGgame.play(Mark.X, 0, 0)         # IllegalMove: not your turngame.undo()                     # the middle is empty, and it is X's turn again
After. The caller says who they are, and the game decides whether they may. Why pass the mark at all? Because "whoever calls is next" cannot notice a double click.

Roles

What each class owns

ClassKnowsDoesDoes not know
GameTurn, status, movesAllows or refuses, in orderHow a win is found, how squares are stored
BoardWhat lies where, how many are emptyStores and clears, refuses a taken squareWhose turn it is, what a line is
LineCountsMarks on each lineSays whether a move completed oneThe squares
MoveRow, column, markNothing: a recordWhether it was legal
A playerIts own plansCalls playThe inside of the game

Winning

What can one move change?

A pebble in row 1, column 2 can complete row 1 or column 2. If it lies on a diagonal, also that one. It can complete nothing else. So four looks are enough, if each line remembers how full it is.

Counts for X in the game on the sand

Moverow 0row 1row 2col 0col 1col 2downup
X (1,1)01001011
X (0,2)11001112
X (1,0)12011112
X (1,2)13011212
"down" goes from top left to bottom right, "up" from bottom left to top right. Only X's counts are shown; O has its own.

Which lines does a square belong to?

The middle of an odd board is on four lines, a corner on three, an edge on two. On an even board no square is on four.

How do you find out that somebody has won?

BreaksRead the whole board after each move
How
For each of 2n + 2 lines, look at n squares.
Limit
n = 3: 24 looks. n = 1,000: two million for each move. It also checks the mark that has not moved.
Choose when
As the slow, believable version in a test.
WorksRead only the lines through the last move
How
Row, column, and diagonals if the square is on them: at most 4n looks.
Limit
Grows with n. Correct, stores nothing, and undo is free.
Choose when
A fine answer for small boards, and the one that survives k in a row.
StrongCount marks on each line
How
2n + 2 counters for each mark. A move adds to at most four. Equal to n is a win.
Limit
Counters must be taken back on undo. Works only when a win is a full line.
Choose when
The base design here, because the answer to question two was yes.

Taking back

Every change has an opposite

play doesundo does
Append the movePop the move
Put the mark, one empty square fewerClear the square, one more
Add one to its linesTake one from its lines
Pass the turn, unless the game endedGive the turn to whoever made the move
Set the statusSet PLAYING: before a legal move the game was always going on
The fourth row is the subtle one. After a win the turn did not pass, so "switch the player" would be wrong. move.mark is always right.

Summary

The whole topic in one minute.

The game enforces turns and the end, the board stores squares and refuses taken ones, counters see a full line in at most four steps. All questions come before all changes, the win before the draw.

A move is an object, so it can be taken back by opposites, replayed, stored and sent. Counting works because a win is a full line; for k in a row walk from the last move. A computer can know all 5,478 positions.

  • The game enforces, the board stores, the counts see, the players only wish.
  • One move touches at most four lines. Count them.
  • Win first, then full. The last square can do both.
  • A refused move changes nothing.
  • Ask whether a win is a full line. If not, counting is wrong.

Sources