AlgoViz

Design tic-tac-toe

easy 70 min

Model 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

  1. Interviewer

    Design tic-tac-toe.

  2. 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?
  3. Interviewer

    Any size, whole lines. Undo, yes. The computer we may discuss at the end. One game.

  4. 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.

  5. Interviewer

    Why not simply check the board?

  6. 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

PartHereElsewhere
State that only legal moves changeBoard and turnBank account, order, document
A refereeGame.playAn aggregate that guards its rules
Incremental questionIs a line full?Running totals, a search index
HistoryMovesEvent log, undo stack
That is why a toy is asked. The same four parts appear in systems with money in them.

From the sentence to the code

  1. 1

    List the rules

    Alternate, only empty squares, full line wins, full board draws, nothing after the end.

  2. 2

    Give each rule an owner

    Say aloud who can know it. Only the board knows empty, only the game knows turns.

  3. 3

    Write the verbs

    play, undo, and two questions.

  4. 4

    Order the checks

    All questions before all changes.

  5. 5

    Trace

    A draw, a win with the last square, a refused move.