{"id":"6b093dc191bd8fbaf2a0c8c8","slug":"game-checkpoint-memento","title":"Game checkpoints","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"easy","topics":["memento"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["memento","snapshots","undo","immutability","behavioral"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Memento: a snapshot of the hero. Others (the caretaker) only need `label`. */\nclass HeroSnapshot {\n  constructor(\n    readonly label: string,\n    readonly heroName: string,\n    readonly hp: number,\n    readonly x: number,\n    readonly y: number,\n    readonly inventory: readonly string[],\n  ) {\n    // TODO: the snapshot must be read-only – the object and its inventory\n  }\n}\n\n/** Originator. Gameplay methods are ready; save() and restore() are missing. */\nclass Hero {\n  hp = 100;\n  x = 0;\n  y = 0;\n  private items: string[] = [];\n\n  constructor(readonly name: string) {}\n\n  get inventory(): string[] {\n    return [...this.items];\n  }\n\n  move(dx: number, dy: number): void {\n    this.x += dx;\n    this.y += dy;\n  }\n\n  takeDamage(amount: number): void {\n    this.hp = Math.max(0, this.hp - amount);\n  }\n\n  pick(item: string): void {\n    this.items.push(item);\n  }\n\n  /** Removes the first occurrence of the item – in place. */\n  drop(item: string): void {\n    const i = this.items.indexOf(item);\n    if (i >= 0) this.items.splice(i, 1);\n  }\n\n  save(label: string): HeroSnapshot {\n    // TODO\n    throw new Error('Not implemented');\n  }\n\n  /** Restores the state; a snapshot of another hero → Error('Snapshot belongs to <name>'). */\n  restore(snapshot: HeroSnapshot): void {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\n/** Caretaker: keeps at most `capacity` snapshots (the oldest drop out) and never looks inside them. */\nclass Checkpoints {\n  constructor(private readonly capacity = 3) {}\n\n  push(snapshot: HeroSnapshot): void {\n    throw new Error('Not implemented');\n  }\n\n  /** The newest snapshot, removed from the stack; null when empty. */\n  pop(): HeroSnapshot | null {\n    throw new Error('Not implemented');\n  }\n\n  size(): number {\n    throw new Error('Not implemented');\n  }\n\n  /** Labels from the oldest to the newest. */\n  labels(): string[] {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"function adventurer() {\n  const hero = new Hero('Bob');\n  hero.takeDamage(30);\n  hero.move(2, 3);\n  hero.pick('sword');\n  hero.pick('potion');\n  return hero;\n}\n\nconst stateOf = (hero) => ({ hp: hero.hp, x: hero.x, y: hero.y, inventory: hero.inventory });\n\ntest('restore() brings back hp, position and inventory', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('before the boss');\n  hero.takeDamage(50);\n  hero.move(10, 10);\n  hero.pick('key');\n  hero.restore(snapshot);\n  expect(stateOf(hero)).toEqual({ hp: 70, x: 2, y: 3, inventory: ['sword', 'potion'] });\n});\n\ntest('a snapshot is not affected by later changes to the hero', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('camp');\n  hero.drop('sword');\n  hero.pick('shield');\n  expect(snapshot.inventory).toEqual(['sword', 'potion']);\n  hero.restore(snapshot);\n  expect(hero.inventory).toEqual(['sword', 'potion']);\n});\n\ntest('the same snapshot can be restored many times', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('camp');\n  hero.restore(snapshot);\n  hero.drop('sword');\n  hero.pick('apple');\n  hero.restore(snapshot);\n  expect(hero.inventory).toEqual(['sword', 'potion']);\n});\n\ntest('a knocked-out hero can be brought back', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('camp');\n  hero.takeDamage(500);\n  expect(hero.hp).toBe(0);\n  hero.restore(snapshot);\n  expect(hero.hp).toBe(70);\n});\n\ntest('checkpoints work as a stack', () => {\n  const hero = adventurer();\n  const checkpoints = new Checkpoints();\n  checkpoints.push(hero.save('village'));\n  hero.move(5, 0);\n  checkpoints.push(hero.save('forest'));\n  expect(checkpoints.size()).toBe(2);\n  expect(checkpoints.pop().label).toBe('forest');\n  expect(checkpoints.pop().label).toBe('village');\n  expect(checkpoints.pop()).toBeNull();\n  expect(checkpoints.size()).toBe(0);\n});\n\ntest('checkpoints keep only the newest snapshots', () => {\n  const hero = adventurer();\n  const checkpoints = new Checkpoints(2);\n  checkpoints.push(hero.save('village'));\n  checkpoints.push(hero.save('forest'));\n  checkpoints.push(hero.save('castle'));\n  expect(checkpoints.labels()).toEqual(['forest', 'castle']);\n  expect(checkpoints.size()).toBe(2);\n});\n\ntest('a snapshot cannot be restored into another hero', () => {\n  const snapshot = adventurer().save('camp');\n  const ann = new Hero('Ann');\n  expect(() => ann.restore(snapshot)).toThrow('Snapshot belongs to Bob');\n  expect(ann.hp).toBe(100);\n});\n\ntest('the snapshot is read-only', () => {\n  const snapshot = adventurer().save('camp');\n  expect(snapshot.label).toBe('camp');\n  expect(() => { snapshot.hp = 999; }).toThrow();\n  expect(() => snapshot.inventory.push('cheat')).toThrow();\n  expect(snapshot.hp).toBe(70);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/** Memento: a snapshot of the hero. Others (the caretaker) only need `label`. */\nclass HeroSnapshot {\n  constructor(label, heroName, hp, x, y, inventory) {\n    this.label = label;\n    this.heroName = heroName;\n    this.hp = hp;\n    this.x = x;\n    this.y = y;\n    this.inventory = inventory;\n    // TODO: the snapshot must be read-only – the object and its inventory\n  }\n}\n\n/** Originator. Gameplay methods are ready; save() and restore() are missing. */\nclass Hero {\n  hp = 100;\n  x = 0;\n  y = 0;\n  #items = [];\n\n  constructor(name) {\n    this.name = name;\n  }\n\n  get inventory() {\n    return [...this.#items];\n  }\n\n  move(dx, dy) {\n    this.x += dx;\n    this.y += dy;\n  }\n\n  takeDamage(amount) {\n    this.hp = Math.max(0, this.hp - amount);\n  }\n\n  pick(item) {\n    this.#items.push(item);\n  }\n\n  /** Removes the first occurrence of the item – in place. */\n  drop(item) {\n    const i = this.#items.indexOf(item);\n    if (i >= 0) this.#items.splice(i, 1);\n  }\n\n  save(label) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n\n  /** Restores the state; a snapshot of another hero → Error('Snapshot belongs to <name>'). */\n  restore(snapshot) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\n/** Caretaker: keeps at most `capacity` snapshots (the oldest drop out) and never looks inside them. */\nclass Checkpoints {\n  constructor(capacity = 3) {\n    this.capacity = capacity;\n  }\n\n  push(snapshot) {\n    throw new Error('Not implemented');\n  }\n\n  /** The newest snapshot, removed from the stack; null when empty. */\n  pop() {\n    throw new Error('Not implemented');\n  }\n\n  size() {\n    throw new Error('Not implemented');\n  }\n\n  /** Labels from the oldest to the newest. */\n  labels() {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"function adventurer() {\n  const hero = new Hero('Bob');\n  hero.takeDamage(30);\n  hero.move(2, 3);\n  hero.pick('sword');\n  hero.pick('potion');\n  return hero;\n}\n\nconst stateOf = (hero) => ({ hp: hero.hp, x: hero.x, y: hero.y, inventory: hero.inventory });\n\ntest('restore() brings back hp, position and inventory', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('before the boss');\n  hero.takeDamage(50);\n  hero.move(10, 10);\n  hero.pick('key');\n  hero.restore(snapshot);\n  expect(stateOf(hero)).toEqual({ hp: 70, x: 2, y: 3, inventory: ['sword', 'potion'] });\n});\n\ntest('a snapshot is not affected by later changes to the hero', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('camp');\n  hero.drop('sword');\n  hero.pick('shield');\n  expect(snapshot.inventory).toEqual(['sword', 'potion']);\n  hero.restore(snapshot);\n  expect(hero.inventory).toEqual(['sword', 'potion']);\n});\n\ntest('the same snapshot can be restored many times', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('camp');\n  hero.restore(snapshot);\n  hero.drop('sword');\n  hero.pick('apple');\n  hero.restore(snapshot);\n  expect(hero.inventory).toEqual(['sword', 'potion']);\n});\n\ntest('a knocked-out hero can be brought back', () => {\n  const hero = adventurer();\n  const snapshot = hero.save('camp');\n  hero.takeDamage(500);\n  expect(hero.hp).toBe(0);\n  hero.restore(snapshot);\n  expect(hero.hp).toBe(70);\n});\n\ntest('checkpoints work as a stack', () => {\n  const hero = adventurer();\n  const checkpoints = new Checkpoints();\n  checkpoints.push(hero.save('village'));\n  hero.move(5, 0);\n  checkpoints.push(hero.save('forest'));\n  expect(checkpoints.size()).toBe(2);\n  expect(checkpoints.pop().label).toBe('forest');\n  expect(checkpoints.pop().label).toBe('village');\n  expect(checkpoints.pop()).toBeNull();\n  expect(checkpoints.size()).toBe(0);\n});\n\ntest('checkpoints keep only the newest snapshots', () => {\n  const hero = adventurer();\n  const checkpoints = new Checkpoints(2);\n  checkpoints.push(hero.save('village'));\n  checkpoints.push(hero.save('forest'));\n  checkpoints.push(hero.save('castle'));\n  expect(checkpoints.labels()).toEqual(['forest', 'castle']);\n  expect(checkpoints.size()).toBe(2);\n});\n\ntest('a snapshot cannot be restored into another hero', () => {\n  const snapshot = adventurer().save('camp');\n  const ann = new Hero('Ann');\n  expect(() => ann.restore(snapshot)).toThrow('Snapshot belongs to Bob');\n  expect(ann.hp).toBe(100);\n});\n\ntest('the snapshot is read-only', () => {\n  const snapshot = adventurer().save('camp');\n  expect(snapshot.label).toBe('camp');\n  expect(() => { snapshot.hp = 999; }).toThrow();\n  expect(() => snapshot.inventory.push('cheat')).toThrow();\n  expect(snapshot.hp).toBe(70);\n});\n"},{"lang":"python","runner":"browser","starter":"from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass HeroSnapshot:\n    \"\"\"Memento: a read-only snapshot of the hero. Others (the caretaker) only need `label`.\n    The inventory must not be shared with the hero (a tuple is a good choice).\"\"\"\n\n    label: str\n    hero_name: str\n    hp: int\n    x: int\n    y: int\n    inventory: tuple\n\n\nclass Hero:\n    \"\"\"Originator. Gameplay methods are ready; save() and restore() are missing.\"\"\"\n\n    def __init__(self, name: str):\n        self.name = name\n        self.hp = 100\n        self.x = 0\n        self.y = 0\n        self._items: list[str] = []\n\n    @property\n    def inventory(self) -> list[str]:\n        return list(self._items)\n\n    def move(self, dx: int, dy: int) -> None:\n        self.x += dx\n        self.y += dy\n\n    def take_damage(self, amount: int) -> None:\n        self.hp = max(0, self.hp - amount)\n\n    def pick(self, item: str) -> None:\n        self._items.append(item)\n\n    def drop(self, item: str) -> None:\n        \"\"\"Removes the first occurrence of the item – in place.\"\"\"\n        if item in self._items:\n            self._items.remove(item)\n\n    def save(self, label: str) -> HeroSnapshot:\n        raise NotImplementedError  # TODO\n\n    def restore(self, snapshot: HeroSnapshot) -> None:\n        \"\"\"Restores the state; a snapshot of another hero → ValueError('Snapshot belongs to <name>').\"\"\"\n        raise NotImplementedError  # TODO\n\n\nclass Checkpoints:\n    \"\"\"Caretaker: keeps at most `capacity` snapshots (the oldest drop out) and never looks inside them.\"\"\"\n\n    def __init__(self, capacity: int = 3):\n        self.capacity = capacity\n\n    def push(self, snapshot: HeroSnapshot) -> None:\n        raise NotImplementedError\n\n    def pop(self) -> HeroSnapshot | None:\n        \"\"\"The newest snapshot, removed from the stack; None when empty.\"\"\"\n        raise NotImplementedError\n\n    def size(self) -> int:\n        raise NotImplementedError\n\n    def labels(self) -> list[str]:\n        \"\"\"Labels from the oldest to the newest.\"\"\"\n        raise NotImplementedError\n","testCount":8,"tests":"def adventurer():\n    hero = Hero(\"Bob\")\n    hero.take_damage(30)\n    hero.move(2, 3)\n    hero.pick(\"sword\")\n    hero.pick(\"potion\")\n    return hero\n\n\ndef state_of(hero):\n    return {\"hp\": hero.hp, \"x\": hero.x, \"y\": hero.y, \"inventory\": hero.inventory}\n\n\ndef test_restore_brings_back_hp_position_and_inventory():\n    hero = adventurer()\n    snapshot = hero.save(\"before the boss\")\n    hero.take_damage(50)\n    hero.move(10, 10)\n    hero.pick(\"key\")\n    hero.restore(snapshot)\n    got = state_of(hero)\n    assert got == {\"hp\": 70, \"x\": 2, \"y\": 3, \"inventory\": [\"sword\", \"potion\"]}, f\"got {got}\"\n\n\ndef test_a_snapshot_is_not_affected_by_later_changes_to_the_hero():\n    hero = adventurer()\n    snapshot = hero.save(\"camp\")\n    hero.drop(\"sword\")\n    hero.pick(\"shield\")\n    assert list(snapshot.inventory) == [\"sword\", \"potion\"], f\"snapshot changed: {snapshot.inventory}\"\n    hero.restore(snapshot)\n    assert hero.inventory == [\"sword\", \"potion\"], f\"got {hero.inventory}\"\n\n\ndef test_the_same_snapshot_can_be_restored_many_times():\n    hero = adventurer()\n    snapshot = hero.save(\"camp\")\n    hero.restore(snapshot)\n    hero.drop(\"sword\")\n    hero.pick(\"apple\")\n    hero.restore(snapshot)\n    assert hero.inventory == [\"sword\", \"potion\"], f\"got {hero.inventory}\"\n\n\ndef test_a_knocked_out_hero_can_be_brought_back():\n    hero = adventurer()\n    snapshot = hero.save(\"camp\")\n    hero.take_damage(500)\n    assert hero.hp == 0\n    hero.restore(snapshot)\n    assert hero.hp == 70, f\"got {hero.hp}\"\n\n\ndef test_checkpoints_work_as_a_stack():\n    hero = adventurer()\n    checkpoints = Checkpoints()\n    checkpoints.push(hero.save(\"village\"))\n    hero.move(5, 0)\n    checkpoints.push(hero.save(\"forest\"))\n    assert checkpoints.size() == 2\n    assert checkpoints.pop().label == \"forest\"\n    assert checkpoints.pop().label == \"village\"\n    assert checkpoints.pop() is None\n    assert checkpoints.size() == 0\n\n\ndef test_checkpoints_keep_only_the_newest_snapshots():\n    hero = adventurer()\n    checkpoints = Checkpoints(capacity=2)\n    for label in (\"village\", \"forest\", \"castle\"):\n        checkpoints.push(hero.save(label))\n    assert checkpoints.labels() == [\"forest\", \"castle\"], f\"got {checkpoints.labels()}\"\n    assert checkpoints.size() == 2\n\n\ndef test_a_snapshot_cannot_be_restored_into_another_hero():\n    snapshot = adventurer().save(\"camp\")\n    ann = Hero(\"Ann\")\n    with raises(ValueError, match=\"Snapshot belongs to Bob\"):\n        ann.restore(snapshot)\n    assert ann.hp == 100\n\n\ndef test_the_snapshot_is_read_only():\n    snapshot = adventurer().save(\"camp\")\n    assert snapshot.label == \"camp\"\n    with raises(AttributeError):\n        snapshot.hp = 999\n    with raises(AttributeError):\n        snapshot.inventory.append(\"cheat\")\n    assert snapshot.hp == 70\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n/// <summary>Memento: a read-only snapshot of the hero. Others (the caretaker) only need Label.</summary>\npublic sealed class HeroSnapshot\n{\n    internal HeroSnapshot(string label, string heroName, int hp, int x, int y, IReadOnlyList<string> inventory)\n    {\n        Label = label;\n        HeroName = heroName;\n        Hp = hp;\n        X = x;\n        Y = y;\n        Inventory = inventory;\n    }\n\n    public string Label { get; }\n    public string HeroName { get; }\n    internal int Hp { get; }\n    internal int X { get; }\n    internal int Y { get; }\n    internal IReadOnlyList<string> Inventory { get; }\n}\n\n/// <summary>Originator. Gameplay methods are ready; Save and Restore are missing.</summary>\npublic class Hero\n{\n    private List<string> items = new List<string>();\n\n    public Hero(string name) { Name = name; }\n\n    public string Name { get; }\n    public int Hp { get; private set; } = 100;\n    public int X { get; private set; }\n    public int Y { get; private set; }\n    public IReadOnlyList<string> Inventory { get { return items.ToList(); } }\n\n    public void Move(int dx, int dy) { X += dx; Y += dy; }\n    public void TakeDamage(int amount) { Hp = Math.Max(0, Hp - amount); }\n    public void Pick(string item) { items.Add(item); }\n\n    /// <summary>Removes the first occurrence of the item – in place.</summary>\n    public void Drop(string item) { items.Remove(item); }\n\n    public HeroSnapshot Save(string label)\n    {\n        // TODO: the snapshot must not share the inventory list with the hero\n        throw new NotImplementedException();\n    }\n\n    /// <summary>Restores the state; a snapshot of another hero → InvalidOperationException(\"Snapshot belongs to name\").</summary>\n    public void Restore(HeroSnapshot snapshot)\n    {\n        // TODO\n        throw new NotImplementedException();\n    }\n}\n\n/// <summary>Caretaker: keeps at most capacity snapshots (the oldest drop out) and never looks inside them.</summary>\npublic class Checkpoints\n{\n    private readonly int capacity;\n\n    public Checkpoints(int capacity = 3) { this.capacity = capacity; }\n\n    public int Count { get { throw new NotImplementedException(); } }\n\n    public void Push(HeroSnapshot snapshot) { throw new NotImplementedException(); }\n\n    /// <summary>The newest snapshot, removed from the stack; null when empty.</summary>\n    public HeroSnapshot Pop() { throw new NotImplementedException(); }\n\n    /// <summary>Labels from the oldest to the newest.</summary>\n    public IReadOnlyList<string> Labels() { throw new NotImplementedException(); }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Memento: a read-only snapshot of the hero. Others (the caretaker) only need label(). */\nfinal class HeroSnapshot {\n    private final String label;\n    private final String heroName;\n    private final int hp;\n    private final int x;\n    private final int y;\n    private final List<String> inventory;\n\n    HeroSnapshot(String label, String heroName, int hp, int x, int y, List<String> inventory) {\n        this.label = label;\n        this.heroName = heroName;\n        this.hp = hp;\n        this.x = x;\n        this.y = y;\n        this.inventory = inventory; // TODO: must not share the list with the hero and must be read-only\n    }\n\n    String label() { return label; }\n    String heroName() { return heroName; }\n    int hp() { return hp; }\n    int x() { return x; }\n    int y() { return y; }\n    List<String> inventory() { return inventory; }\n}\n\n/** Originator. Gameplay methods are ready; save() and restore() are missing. */\nclass Hero {\n    private final String name;\n    private int hp = 100;\n    private int x;\n    private int y;\n    private List<String> items = new ArrayList<>();\n\n    Hero(String name) { this.name = name; }\n\n    String name() { return name; }\n    int hp() { return hp; }\n    int x() { return x; }\n    int y() { return y; }\n    List<String> inventory() { return new ArrayList<>(items); }\n\n    void move(int dx, int dy) { x += dx; y += dy; }\n    void takeDamage(int amount) { hp = Math.max(0, hp - amount); }\n    void pick(String item) { items.add(item); }\n\n    /** Removes the first occurrence of the item – in place. */\n    void drop(String item) { items.remove(item); }\n\n    HeroSnapshot save(String label) {\n        throw new UnsupportedOperationException(\"Not implemented\"); // TODO\n    }\n\n    /** Restores the state; a snapshot of another hero → IllegalStateException(\"Snapshot belongs to name\"). */\n    void restore(HeroSnapshot snapshot) {\n        throw new UnsupportedOperationException(\"Not implemented\"); // TODO\n    }\n}\n\n/** Caretaker: keeps at most capacity snapshots (the oldest drop out) and never looks inside them. */\nclass Checkpoints {\n    private final int capacity;\n\n    Checkpoints(int capacity) { this.capacity = capacity; }\n    Checkpoints() { this(3); }\n\n    void push(HeroSnapshot snapshot) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** The newest snapshot, removed from the stack; empty when there is none. */\n    Optional<HeroSnapshot> pop() { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    int size() { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** Labels from the oldest to the newest. */\n    List<String> labels() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// Snapshot is the memento: unexported fields, only Label is visible to the caretaker.\ntype Snapshot struct {\n\tlabel     string\n\theroName  string\n\thp, x, y  int\n\tinventory []string\n}\n\n// Label names the checkpoint.\nfunc (s Snapshot) Label() string { return s.label }\n\n// Hero is the originator. Gameplay methods are ready; Save and Restore are missing.\ntype Hero struct {\n\tname     string\n\thp, x, y int\n\titems    []string\n}\n\n// NewHero starts with 100 HP at (0, 0).\nfunc NewHero(name string) *Hero { return &Hero{name: name, hp: 100} }\n\nfunc (h *Hero) Name() string             { return h.name }\nfunc (h *Hero) HP() int                  { return h.hp }\nfunc (h *Hero) Position() (int, int)     { return h.x, h.y }\nfunc (h *Hero) Inventory() []string      { return append([]string{}, h.items...) }\nfunc (h *Hero) Move(dx, dy int)          { h.x += dx; h.y += dy }\nfunc (h *Hero) Pick(item string)         { h.items = append(h.items, item) }\nfunc (h *Hero) TakeDamage(amount int) {\n\th.hp -= amount\n\tif h.hp < 0 {\n\t\th.hp = 0\n\t}\n}\n\n// Drop removes the first occurrence of the item – in place (it shifts the backing array).\nfunc (h *Hero) Drop(item string) {\n\tfor i, it := range h.items {\n\t\tif it == item {\n\t\t\th.items = append(h.items[:i], h.items[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// Save creates a snapshot that must not share memory with the hero.\nfunc (h *Hero) Save(label string) Snapshot {\n\t// TODO\n\treturn Snapshot{label: label}\n}\n\n// Restore brings the state back; a snapshot of another hero → error \"snapshot belongs to <name>\".\nfunc (h *Hero) Restore(s Snapshot) error {\n\t// TODO\n\treturn nil\n}\n\n// Checkpoints is the caretaker: at most capacity snapshots (the oldest drop out), never looks inside them.\ntype Checkpoints struct {\n\tcapacity int\n}\n\n// NewCheckpoints creates an empty stack.\nfunc NewCheckpoints(capacity int) *Checkpoints { return &Checkpoints{capacity: capacity} }\n\nfunc (c *Checkpoints) Push(s Snapshot)       {}                         // TODO\nfunc (c *Checkpoints) Pop() (Snapshot, bool) { return Snapshot{}, false } // TODO: the newest; false when empty\nfunc (c *Checkpoints) Len() int              { return 0 }               // TODO\nfunc (c *Checkpoints) Labels() []string      { return nil }             // TODO: oldest → newest\n","testCount":8}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.224Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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. "},{"type":"text","text":"Memento","marks":[{"type":"bold"}]},{"type":"text","text":" solves this properly: the hero (the originator) creates a snapshot of its own state, and the caretaker only stores it without looking inside."}]},{"type":"paragraph","content":[{"type":"text","text":"The hero's gameplay methods are ready: "},{"type":"text","text":"move","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"takeDamage","marks":[{"type":"code"}]},{"type":"text","text":" (hit points never drop below zero), "},{"type":"text","text":"pick","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"drop","marks":[{"type":"code"}]},{"type":"text","text":" – the latter removes an item "},{"type":"text","text":"in place","marks":[{"type":"bold"}]},{"type":"text","text":", modifying the internal list."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"save(label)","marks":[{"type":"code"}]},{"type":"text","text":" returns a snapshot with the label, the hero's name, hit points, position and inventory. The snapshot:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"does not share the item list with the hero – later "},{"type":"text","text":"drop","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"pick","marks":[{"type":"code"}]},{"type":"text","text":" calls do not change it;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"is read-only (its inventory too)."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"restore(snapshot)","marks":[{"type":"code"}]},{"type":"text","text":" 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 error "},{"type":"text","text":"Snapshot belongs to <name>","marks":[{"type":"code"}]},{"type":"text","text":" (in Go "},{"type":"text","text":"snapshot belongs to <name>","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Checkpoints(capacity = 3)","marks":[{"type":"code"}]},{"type":"text","text":" – a caretaker working as a stack: "},{"type":"text","text":"push","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"pop","marks":[{"type":"code"}]},{"type":"text","text":" (the newest snapshot or \"nothing\"), "},{"type":"text","text":"size","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"labels()","marks":[{"type":"code"}]},{"type":"text","text":" (from the oldest to the newest). Beyond the capacity the oldest snapshot drops out."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Language details: TypeScript/JavaScript – "},{"type":"text","text":"Object.freeze","marks":[{"type":"code"}]},{"type":"text","text":" for the snapshot and its inventory, "},{"type":"text","text":"pop()","marks":[{"type":"code"}]},{"type":"text","text":" returns "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":"; Python – "},{"type":"text","text":"@dataclass(frozen=True)","marks":[{"type":"code"}]},{"type":"text","text":" with the inventory as a tuple, "},{"type":"text","text":"take_damage","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"ValueError","marks":[{"type":"code"}]},{"type":"text","text":"; C# – the snapshot's data members are "},{"type":"text","text":"internal","marks":[{"type":"code"}]},{"type":"text","text":" and the inventory is a read-only collection ("},{"type":"text","text":"ReadOnlyCollection","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"Count","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"InvalidOperationException","marks":[{"type":"code"}]},{"type":"text","text":"; Java – "},{"type":"text","text":"List.copyOf","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"pop()","marks":[{"type":"code"}]},{"type":"text","text":" returns an "},{"type":"text","text":"Optional","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"IllegalStateException","marks":[{"type":"code"}]},{"type":"text","text":"; Go – unexported snapshot fields, "},{"type":"text","text":"Restore","marks":[{"type":"code"}]},{"type":"text","text":" returns an "},{"type":"text","text":"error","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Pop() (Snapshot, bool)","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"callout","attrs":{"variant":"warning","title":"A Go trap"},"content":[{"type":"paragraph","content":[{"type":"text","text":"snapshot.inventory = h.items","marks":[{"type":"code"}]},{"type":"text","text":" copies only the slice header – the backing array is shared and "},{"type":"text","text":"Drop","marks":[{"type":"code"}]},{"type":"text","text":" shifts elements inside it. The snapshot \"changes by itself\" although nobody touched it."}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3a80884893657cc9b4","slug":"memento","title":"Memento: a state snapshot without breaking encapsulation"},{"id":"6b08bd3c80884893657cc9f1","slug":"prototype","title":"Prototype – a new object as a copy of a ready-made template"}],"topicsInfo":[{"slug":"memento","title":"Memento","group":"behavioral","icon":"save"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:25.226Z","updatedAt":"2026-11-27T08:22:25.226Z"}