Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
API and data
The contract first, then the data that serves it.
Class API
The public surface
Python
class Game: turn: Mark # read only status: Status # read only def play(self, mark: Mark, row: int, col: int) -> Status: ... # raises IllegalMove def undo(self) -> Move: ... # raises IllegalMove def legal(self) -> list[tuple[int, int]]: ... # empty after the end def rows(self) -> list[str]: ... # a copy, as text| Method | Cost | Why this shape |
|---|---|---|
play | O(1) | The mark says who calls. The status comes back, so nobody must ask again |
undo | O(1) | Returns the move, so a screen knows which square to clear |
legal | O(n squared) | For programs that choose. Keep a set of empty squares if it must be faster |
rows | O(n squared) | A copy in a form that tests can compare |
How does play say no?
BreaksIt ignores the move
- How
- Returns as if nothing had been asked.
- Limit
- The caller thinks that the move was made. The next bug is far from the cause.
- Choose when
- Never.
WorksIt returns false
- How
bool.- Limit
- Four reasons become one, and a caller can forget to look. Then the status needs a second call.
- Choose when
- Very hot loops that check legality first.
StrongIt raises, with a reason
- How
IllegalMove("taken").- Limit
- Somebody must catch it. In languages with result types, return one of those.
- Choose when
- Wrong moves are rare and are a mistake of the caller.