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

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.
Edit and run it in your browser

The two stacks

Truth

What is stored

StoredSize for a finished gameCan answerCannot answer
The last board9 lettersWho has wonWho began, in which order
The moves9 pairsEverythingNothing is missing
A board for each move90 lettersEverything, at onceNothing, but it can contradict itself
Nine moves fit into nine digits: 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 won
Loading and checking are the same code. A link that somebody has edited cannot produce an impossible board, because it runs through play.

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].mark is 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 afterStateRepair
moves.pop()The board has a mark that the history does not knowBuild everything from the moves
board.clearThe counts are one too highThe same
lines.removeTurn and status are oldThe same
In one thread and in memory it cannot stop there. On a server it can, if the parts are stored apart. So store the moves only.