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

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

CallBoardLines that growStatusTurn after
X (1,1)... .X. ...row 1, col 1, down, upplayingO
O (0,0)O.. .X. ...row 0, col 0, downplayingX
X (0,2)O.X .X. ...row 0, col 2, upplayingO
O (1,1)unchangednonerefused: takenO
O (2,0)O.X .X. O..row 2, col 0, upplayingX
X (1,0)O.X XX. O..row 1 is 2, col 0playingO
O (2,2)O.X XX. O.Orow 2 is 2, col 2, down is 2playingX
X (1,2)O.X XXX O.Orow 1 is 3X wonX
Counts belong to a mark. Down has one X and two O, and that is no contradiction.

Edges

Small inputs

InputResultWhy
Size 1, X plays (0,0)X wonOne square is four full lines. add must not return at the first one, or undo is wrong
Size 2The first player wins with the third moveAny two squares are a line
Ninth move completes a lineX won, not a drawOrder of checks
A move that completes two linesX won onceBoth counters are right
Undo after a win, then another squarePlay goes onturn = move.mark
(-1, 0), (0, 3)RefusedBoth ends
Size 0The constructor should refuseAsk: 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 up
Paste it under the Code tab without its demo. It takes some seconds and prints 255168. That number is an independent check that the rules are right.

What the two comparisons prove