Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
Problem
What is asked when the rules are known to all
The point: the game is trivial, so every mark is earned by where the rules live.
The prompt
The first minute
Opening
Interviewer
Design tic-tac-toe.
You
Two players alternate on a grid, a full line wins. Before I write, some questions that change the code:
- Is the board always 3 by 3?
- Is a win always a whole line, or k in a row on a larger board?
- Will there be a computer player, or undo?
- One game in one process, or a server with many?
Interviewer
Any size, whole lines. Undo, yes. The computer we may discuss at the end. One game.
You
Then I separate the squares, the win check and the referee. No input or output inside. I will make the win check independent of the size, because a move only touches four lines.
Interviewer
Why not simply check the board?
You
For size 3 it would be fine, and I would use it in my tests. With any size it is n squared work for a question that four counters answer. If you change the rule to k in a row, I go back to looking along the lines of the last move.
Shape
What kind of problem it is
| Part | Here | Elsewhere |
|---|---|---|
| State that only legal moves change | Board and turn | Bank account, order, document |
| A referee | Game.play | An aggregate that guards its rules |
| Incremental question | Is a line full? | Running totals, a search index |
| History | Moves | Event log, undo stack |
From the sentence to the code
- 1
List the rules
Alternate, only empty squares, full line wins, full board draws, nothing after the end.
- 2
Give each rule an owner
Say aloud who can know it. Only the board knows empty, only the game knows turns.
- 3
Write the verbs
play,undo, and two questions. - 4
Order the checks
All questions before all changes.
- 5
Trace
A draw, a win with the last square, a refused move.