Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
Verify
Trace, edges, and all 255,168 games
The point: this is one of the few programs for which every possible run can be checked. Do it.
Trace
The game on the sand
| Call | Board | Lines that grow | Status | Turn after |
|---|---|---|---|---|
| X (1,1) | ... .X. ... | row 1, col 1, down, up | playing | O |
| O (0,0) | O.. .X. ... | row 0, col 0, down | playing | X |
| X (0,2) | O.X .X. ... | row 0, col 2, up | playing | O |
| O (1,1) | unchanged | none | refused: taken | O |
| O (2,0) | O.X .X. O.. | row 2, col 0, up | playing | X |
| X (1,0) | O.X XX. O.. | row 1 is 2, col 0 | playing | O |
| O (2,2) | O.X XX. O.O | row 2 is 2, col 2, down is 2 | playing | X |
| X (1,2) | O.X XXX O.O | row 1 is 3 | X won | X |
Edges
Small inputs
| Input | Result | Why |
|---|---|---|
| Size 1, X plays (0,0) | X won | One square is four full lines. add must not return at the first one, or undo is wrong |
| Size 2 | The first player wins with the third move | Any two squares are a line |
| Ninth move completes a line | X won, not a draw | Order of checks |
| A move that completes two lines | X won once | Both counters are right |
| Undo after a win, then another square | Play goes on | turn = move.mark |
| (-1, 0), (0, 3) | Refused | Both ends |
| Size 0 | The constructor should refuse | Ask: is it our job? One line |
Everything
All games, against a slow judge
Walk through all games of size 3. After each move compare the status with a judge that simply reads all eight lines. After each undo compare the whole state with a picture taken before. If both agree everywhere, the counters and the undo are right, for this size, without any argument.
Python
from itertools import productN = 3LINES = ([[(r, c) for c in range(N)] for r in range(N)] + [[(r, c) for r in range(N)] for c in range(N)] + [[(i, i) for i in range(N)], [(i, N - 1 - i) for i in range(N)]])def slow(rows): """So simple that it can be believed.""" for line, mark in product(LINES, "XO"): if all(rows[r][c] == mark for r, c in line): return f"{mark} won" return "draw" if not any("." in row for row in rows) else "playing"def every_game(game): """Play all games, compare after each move, and take each move back.""" ends = 0 for row, col in game.legal(): before = (game.rows(), game.turn, game.status) status = game.play(game.turn, row, col) assert status.value == slow(game.rows()) ends += 1 if status is not Status.PLAYING else every_game(game) game.undo() assert (game.rows(), game.turn, game.status) == before return endsprint(every_game(Game())) # 255168, the number everybody can look upWhat the two comparisons prove