Game checkpoints
Saving and restoring a hero's state with Memento – immutable snapshots without shared lists, a caretaker with limited capacity and protection against loading someone else's save.
In a browser RPG the player saves progress before the boss fight and returns to the checkpoint after a defeat. The first version simply stored a reference to the item list – and players reported that after loading a save they still had the sword they sold only after saving. Memento solves this properly: the hero (the originator) creates a snapshot of its own state, and the caretaker only stores it without looking inside.
The hero's gameplay methods are ready: move, takeDamage (hit points never drop below zero), pick and drop – the latter removes an item in place, modifying the internal list.
Task
save(label)returns a snapshot with the label, the hero's name, hit points, position and inventory. The snapshot:- does not share the item list with the hero – later
dropandpickcalls do not change it; - is read-only (its inventory too).
- does not share the item list with the hero – later
restore(snapshot)brings the state back. The same snapshot can be restored many times – after restoring, the hero must not modify a list that belongs to the snapshot. A snapshot of another hero ends with the errorSnapshot belongs to <name>(in Gosnapshot belongs to <name>).Checkpoints(capacity = 3)– a caretaker working as a stack:push,pop(the newest snapshot or "nothing"),size,labels()(from the oldest to the newest). Beyond the capacity the oldest snapshot drops out.
Language details: TypeScript/JavaScript – Object.freeze for the snapshot and its inventory, pop() returns null; Python – @dataclass(frozen=True) with the inventory as a tuple, take_damage, ValueError; C# – the snapshot's data members are internal and the inventory is a read-only collection (ReadOnlyCollection), Count, InvalidOperationException; Java – List.copyOf, pop() returns an Optional, IllegalStateException; Go – unexported snapshot fields, Restore returns an error, Pop() (Snapshot, bool).
Topics: Memento
Related articles
- Memento: a state snapshot without breaking encapsulation
The Memento pattern through a menu editor: Halina saves versions of the menu and returns to them with one click, while the history keeps snapshots without seeing what is inside. Copies instead of references, memory costs and code in five…