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

Testing

Exhaustive, random, and the bugs to plant

The point: test the fast code against slow code that is obviously right, and then check that the test can fail.

Levels

Four tests, four kinds of bug

TestFindsSize
Every game of size 3Wrong lines, wrong undo, wrong order of checks255,168 games, some seconds
Random games of sizes 1 to 8Things that are true only for 3Thousands
RefusalsA check after a changeCompare the state before and after
Names of casesNothing new, but they explainA handful

Plant

Would the test notice?

A green test proves little until it has been red. Change one thing in the code and see which test fails.

Planted bugFirst test that fails
elif for the second diagonalEvery game: the middle square
Draw is checked before the winEvery game: a win with the ninth move
Undo switches the turn instead of move.markEvery game: the state after undoing a win
add returns at the first full lineEvery game: a double line, then undo
Size 3 written into the up diagonalRandom sizes
Move stored before putRefusals: undo after a refused move
The fifth is why the second test exists. The sixth is not found by the first, because it plays legal moves only.

Refusals

A refused move is free

Python
def state(game):    return (game.rows(), game.turn, game.status, len(game._moves), dict(game._lines._count))def check_refusals(game):    before = state(game)    n = len(game.rows())    squares = [(r, c) for r in range(-1, n + 1) for c in range(-1, n + 1)]    for mark in Mark:        for row, col in squares:            if mark is game.turn and (row, col) in game.legal():                continue            try:                game.play(mark, row, col)                assert False, (mark, row, col)            except IllegalMove:                assert state(game) == before
Run it in each position of some random games. It tries everything that should be refused, also from outside the board.

Computer

Testing the player who never loses

  1. 1

    Never loses

    Play it against all possible answers, as both marks. Not random ones: all.

  2. 2

    Takes a win in one, blocks a win in one

    For every position where there is one.

  3. 3

    Symmetric

    The value of a turned board is the same. A cheap test that finds typing errors in the list of lines.

  4. 4

    Known number

    The value of the empty board is 0: a draw.

Choose a test

This game is in the first box for size 3, in the second for larger boards, and in the third for a player with estimates.