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

New rules

Larger, inverted, three players, boards in boards

The point: for each wish name the class that changes. If it is more than one, the design has a seam in the wrong place.

List

Eight wishes, and the blast radius

WishChangesDoes not change
4 by 4, whole lineOne argumentEverything
Whoever completes a line losesTwo words in play: who has wonBoard, counts
No diagonals_linesThe rest
Three playersMark, and other becomes next. Status gets a winnerBoard, counts
k in a rowLineCounts is replaced by a walkBoard, turn, undo
Only three marks each, the oldest disappearsplay removes the oldest move of this markCounts: remove exists
Three dimensionsSquares with three numbers, 49 lines for size 3The referee
Boards in boardsA board of small gamesThe small game
The disappearing mark is the nice one: it was impossible in the bad design, and here the needed operation has been built for undo. But then the game can go on for ever, so a limit on moves is needed.

Seam

A rule as a value

Python
class WinRule(Protocol):    def add(self, move: Move) -> bool: ...          # did this move meet the rule?    def remove(self, move: Move) -> None: ...class Game:    def __init__(self, size: int, rule: WinRule, line_wins: bool = True) -> None:        self._rule, self._line_wins = rule, line_wins    def _result(self, mover: Mark) -> Mark:        return mover if self._line_wins else mover.other
Two changes, and only when the second rule arrives. WinRule has the two methods LineCounts already has: the seam was found, not invented.

Nested

Boards in boards

Nine small boards form a big one. Winning a small board puts your mark on the big one. And the square you choose sends the other player to the small board in the same place.

Python
LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]class Small:    """One three by three board. It does not know that it is part of something."""    def __init__(self) -> None:        self.cells = ["."] * 9    def put(self, i: int, mark: str) -> str | None:        if self.cells[i] != ".":            raise ValueError("taken")        self.cells[i] = mark        return mark if any(all(self.cells[k] == mark for k in ln) for ln in LINES) else None    @property    def full(self) -> bool:        return "." not in self.cellsclass Big:    """Nine small boards. Winning a small one puts a mark on the outer one."""    def __init__(self) -> None:        self.small = [Small() for _ in range(9)]        self.outer = Small()        self.next: int | None = None          # the small board that must be used, or any    def play(self, b: int, i: int, mark: str) -> str | None:        if self.next not in (None, b) or self.outer.cells[b] != "." or self.small[b].full:            raise ValueError("not this board")        won_small = self.small[b].put(i, mark)        winner = self.outer.put(b, mark) if won_small else None        open_ = self.outer.cells[i] == "." and not self.small[i].full        self.next = i if open_ else None        return winnerbig = Big()big.play(4, 4, "X")try:    big.play(0, 0, "O")except ValueError as no:    print("refused:", no, "- must play in board", big.next)print(big.play(4, 0, "O"), big.next)
The outer board is the same class as the inner ones. If the board one is sent to is finished, any board may be used: the one rule that people forget.
Edit and run it in your browser

Where must the next move go?