Design tic-tac-toe
easy 70 minModel 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
| Wish | Changes | Does not change |
|---|---|---|
| 4 by 4, whole line | One argument | Everything |
| Whoever completes a line loses | Two words in play: who has won | Board, counts |
| No diagonals | _lines | The rest |
| Three players | Mark, and other becomes next. Status gets a winner | Board, counts |
| k in a row | LineCounts is replaced by a walk | Board, turn, undo |
| Only three marks each, the oldest disappears | play removes the oldest move of this mark | Counts: remove exists |
| Three dimensions | Squares with three numbers, 49 lines for size 3 | The referee |
| Boards in boards | A board of small games | The small game |
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.otherWinRule 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)Where must the next move go?