Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
The referee at work: questions first, then one square, four counters, and the verdict.
Operations
The winning move
Three questions, a square, a count, a verdict.
Step 1 of 5
Asha asks
X, row 1, column 2. The caller says who they are.
Step 1: Asha asks
def play(self, mark, row, col): if self._status is not Status.PLAYING: raise IllegalMove("the game is over") if mark is not self._turn: raise IllegalMove("not your turn") if not self._board.holds(row, col): raise IllegalMove("outside") move = Move(row, col, mark) self._board.put(move) self._moves.append(move) if self._lines.add(move): self._status = won_by(mark) elif self._board.full: self._status = Status.DRAW else: self._turn = mark.other return self._status- Cost
- O(1)
- Guarantee
- One move in the list
- Whole board, n = 100
- 20,200 looks
Everything above the store is a question. Everything below cannot fail.
In the real world
The same tic-tac-toe doing real jobs. Pick one and step through it.
It fills the board and it wins.
Step 1 of 3
One square left
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | X | O | X |
| 1 | O | X | X |
| 2 | O | O |
X moves. The right column already has two X, and so has the down diagonal.
Step 1: One square left
if self._lines.add(move): self._status = won_by(mark)elif self._board.full: self._status = Status.DRAWCommon mistakes
The bugs interviewers watch for, with the fix beside each.
One row, three times
criticalThe same list is used for all rows. A mark appears in each of them.
Wrongboard = [[None] * 3] * 3Rightboard = [[None] * 3 for _ in range(3)]Full before win
criticalA win with the last square becomes a draw.
Wrongif board.full: status = DRAWelif lines.add(move): status = wonRightif lines.add(move): status = wonelif board.full: status = DRAWelif for the second diagonal
criticalThe middle is on both. One of them never counts it.
Wrongif r == c: ...elif r + c == n - 1: ...Rightif r == c: ...if r + c == n - 1: ...Switching the turn in undo
majorAfter a win the turn had not passed. Now the other one moves twice.
Wrongself._turn = self._turn.otherRightself._turn = move.markHalf of an index check
major-1 is the last row in Python, and an accident in C++.
Wrongif row < size and col < size:Rightif 0 <= row < size and 0 <= col < size:Input inside the rules
majorNo test without a keyboard, and no second screen without a copy of the rules.
Wrongrow, col = map(int, input().split())Rightdef play(self, mark, row, col): ...
Interview tips
Open with
- Any size?
- Full line, or k in a row?
- Undo, computer, network?
Reject aloud
- A cell is a value.
- A player is a caller.
- A row is a number.
Prove it
- The ninth move.
- Undo after a win.
- All 255,168 games.
Never
- Print in a rule.
- The real board for players.
- A look at all lines for any n.