Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
Undo and replay
Redo, sharing, and what the truth is
The point: the list of moves is the truth. Board, counts, turn and status are conveniences that can be computed again.
Redo
Two stacks
Python
class History: """Moves done, and moves taken back.""" def __init__(self) -> None: self._done: list[str] = [] self._undone: list[str] = [] def do(self, move: str) -> None: self._done.append(move) self._undone.clear() # a new move ends the old future def undo(self) -> str: move = self._done.pop() self._undone.append(move) return move def redo(self) -> str: move = self._undone.pop() self._done.append(move) return moveh = History()for move in ["X 1,1", "O 0,0", "X 0,2"]: h.do(move)print(h.undo(), "|", h.undo(), "|", h.redo()) # X 0,2 | O 0,0 | O 0,0h.do("X 2,2")try: h.redo()except IndexError: print("nothing to redo: X went another way")do clears the second stack. Without that line a redo would put back a move that belongs to another game.The two stacks
Truth
What is stored
| Stored | Size for a finished game | Can answer | Cannot answer |
|---|---|---|---|
| The last board | 9 letters | Who has won | Who began, in which order |
| The moves | 9 pairs | Everything | Nothing is missing |
| A board for each move | 90 letters | Everything, at once | Nothing, but it can contradict itself |
4 0 2 6 3 8 5 is the game on the sand. A link to a game can contain the whole game.Python
def replay(text: str, size: int = 3) -> Game: """Rebuild a game from its squares. Illegal text is refused by the rules themselves.""" game = Game(size) for square in map(int, text.split()): game.play(game.turn, *divmod(square, size)) return gameprint(replay("4 0 2 6 3 8 5").status.value) # X wonplay.Rule
Who may undo?
Two people play. Who may take back what?
BreaksAnybody, any time
- How
- A button for
undo. - Limit
- Noor can take back Asha's winning move.
- Choose when
- One person at one screen.
WorksOnly your own move, before the other answers
- How
- Allowed if
moves[-1].markis yours. - Limit
- The other may be thinking already. Their screen must follow.
- Choose when
- Friendly play.
StrongAsk, and the other agrees
- How
- A request with the number of the move. Agreed: undo to that number. Any new move ends the request.
- Limit
- Two more messages.
- Choose when
- Two phones. The request needs the number, or it may undo another move than the one that was meant.
Failure walk
Stop it between two lines
| If undo stops after | State | Repair |
|---|---|---|
moves.pop() | The board has a mark that the history does not know | Build everything from the moves |
board.clear | The counts are one too high | The same |
lines.remove | Turn and status are old | The same |