Tiny Shelf 18 · Undo a move or a trade

Tiny Shelf Studio · Lesson 18 of 50 · Beginner to intermediate · About 27 min

Designers compare several layouts before choosing one. Undo lets them test a different arrangement or reverse the exchange without losing their work.

Tiny fictional paper cartons, jars and tins displayed on a handmade wooden shelf.
What you’ll make Restore shelf, stock, the chosen stock design and exchange status together after an accepted edit.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/17 when the lesson builds on prior work, or copy the checkpoints/18 folder to try this lesson on its own. Read the file names in the steps before editing.

Copy the old values. Store shelf, stock, chosen stock design and deal status. → Apply a legal edit. Leave refused requests out of history. → Undo one edit. Restore the newest state and refresh.
Copy the old values → Apply a legal edit → Undo one edit
Godot checkpoint window for Undo a move or a trade
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Typed history array, Dictionary snapshots, duplicate(), Array.append(), Array.pop_back().

  1. Open a practice copy

    Extract the course. In the Godot Project Manager, import checkpoints/18/project.godot. Open main.gd in the Script workspace. Use the previous checkpoint if you want to apply the lesson to existing code.

    Why it works The checkpoint is a complete working example. Copy it before editing so you can return to a tested version.

  2. Create a short history of edits

    Find the typed empty history array and the _remember helper. Read the four fields in each saved record.

    var history: Array[Dictionary] = []

    Why it works A snapshot records live state before a successful edit. It contains the values needed to reverse both an ordinary placement and a trade.

  3. Copy both collections

    Inspect the duplicate calls in _remember. Add the record only after the action's guards and before applying placement, return or swap.

    "display": display.duplicate(),
            "stock": stock.duplicate(),

    Why it works A copied dictionary keeps the old quantities and placements. Recording refused actions would replay an identical screen and hide which edit actually changed it.

  4. Pop the latest saved state

    Find _undo. Try Undo on a fresh run and observe the message. Then perform the first trade and tap Undo.

    var last: Dictionary = history.pop_back()

    Why it works pop_back gives you the newest entry and removes it from history. The editor rolls back only one accepted change at a time.

  5. Restore the exchanged flag as well

    Read where the four fields are assigned back. After undoing a valid trade, press Swap 2 Fizz again.

    exchanged = last["exchanged"]

    Why it works Restoring numbers and the used flag together means the trade can be replayed under the original rules.

  6. Press F5 and test the three examples

    Compare the card quantities, selected slot and status after each action in the trace. Close and reopen the project window to start a separate experiment.

    Why it works Matching a visible result to the rule gives you a way to explain and debug your program.

Watch the values change

  1. Swap two Fizz minis History saves the four field values before the exchange.
    What you see. Jam Toast stock becomes 1 and exchanged becomes true.
  2. Tap Undo The newest record is removed.
    What you see. Both original counts return and exchanged becomes false.
  3. Tap Swap 2 Fizz again The trade is unused and the copies are back.
    What you see. Jam Toast returns to stock through a fresh valid exchange.

Predict before you run If Undo restored the stock but forgot exchanged, could you replay the undone trade?

Reveal the answer

No. The flag would still say the deal is used. It must be restored with the copies.

Complete checkpoint

Undo reverses an accepted place, return or trade. No-change guards leave history alone.

main.gd

extends Control

const COLUMNS := 4
const ROWS := 3
const PREVIEW := {0: "lemon_fizz", 1: "honey_hoops", 5: "mint_paste"}
const START_STOCK := {"lemon_fizz": 2, "honey_hoops": 1, "mint_paste": 1, "jam_toast": 0}
const CATALOGUE := {
    "lemon_fizz": {"name": "Lemon Fizz", "family": "Drinks", "ink": Color("#f1c55e"), "mark": "LEMON", "note": "A tiny sunshine-yellow can."},
    "honey_hoops": {"name": "Honey Hoops", "family": "Snacks", "ink": Color("#8fc8df"), "mark": "HONEY", "note": "A cereal carton with a hoop motif."},
    "mint_paste": {"name": "Mint Paste", "family": "Care", "ink": Color("#93c4a0"), "mark": "MINT", "note": "A miniature toothpaste carton with a leaf design."},
    "jam_toast": {"name": "Jam Toast", "family": "Snacks", "ink": Color("#eea197"), "mark": "JAM", "note": "A tiny jar from the studio exchange."},
}
const PAPER := Color("#fff5e1")
const INK := Color("#26374e")
const MUTED := Color("#506277")
const NAVY := Color("#1e344a")
const EDGE := Color("#9bafaf")

var selected := Vector2i.ZERO
var display := PREVIEW.duplicate()
var stock := START_STOCK.duplicate()
var held_id := ""
var message := "Select a product from the stock room."
var status: Label
var detail: Label
var held_label: Label
var set_label: Label
var shelf_buttons: Array[Button] = []
var stock_buttons: Array[Button] = []


const PICNIC := ["lemon_fizz", "honey_hoops", "mint_paste"]


var exchanged := false


var history: Array[Dictionary] = []


func _ready() -> void:
    _label("TINY SHELF STUDIO", Vector2(31, 21), Vector2(575, 47), 34)
    _label("MINIATURES LAB  /  STOCK & DISPLAY", Vector2(34, 72), Vector2(510, 25), 15, MUTED)
    _label("THE PICNIC CABINET", Vector2(54, 123), Vector2(485, 31), 20)
    _label("STOCK ROOM", Vector2(588, 123), Vector2(308, 31), 20)
    for row in range(ROWS):
        for column in range(COLUMNS):
            var cell := Vector2i(column, row)
            var point := Vector2(52 + column * 125, 171 + row * 94)
            var slot := _button("", point, Vector2(111, 76), _select_cell.bind(cell))
            shelf_buttons.append(slot)
    for index in range(CATALOGUE.size()):
        var item: String = CATALOGUE.keys()[index]
        var point := Vector2(587 + (index % 2) * 164, 170 + (index >> 1) * 64)
        var card := _button("", point, Vector2(154, 55), _choose_stock.bind(item))
        card.add_theme_font_size_override("font_size", 13)
        stock_buttons.append(card)
    held_label = _label("", Vector2(588, 299), Vector2(330, 24), 14)
    set_label = _label("", Vector2(588, 322), Vector2(330, 25), 13, MUTED)
    detail = _label("", Vector2(53, 459), Vector2(482, 36), 15, MUTED)
    status = _label("", Vector2(588, 451), Vector2(327, 52), 15)
    status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
    _button("Place", Vector2(587, 356), Vector2(100, 41), _place)
    _button("Return", Vector2(699, 356), Vector2(100, 41), _return_item)
    _button("Swap 2 Fizz", Vector2(811, 356), Vector2(100, 41), _swap)
    _button("Undo", Vector2(587, 403), Vector2(100, 38), _undo)
    _refresh()


func _label(words: String, point: Vector2, extent: Vector2, font_size: int, colour: Color = INK) -> Label:
    var label := Label.new()
    label.text = words
    label.position = point
    label.size = extent
    label.add_theme_font_size_override("font_size", font_size)
    label.add_theme_color_override("font_color", colour)
    add_child(label)
    return label


func _button(words: String, point: Vector2, extent: Vector2, action: Callable) -> Button:
    var card := Button.new()
    card.text = words
    card.position = point
    card.size = extent
    card.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
    card.pressed.connect(action)
    card.add_theme_font_size_override("font_size", 15)
    for key in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color"]:
        card.add_theme_color_override(key, NAVY)
    add_child(card)
    _palette(card, Color("#fff2db"), false)
    return card


func _palette(card: Button, tint: Color, highlight: bool) -> void:
    var face := StyleBoxFlat.new()
    face.bg_color = tint
    face.border_color = NAVY if highlight else EDGE
    face.set_border_width_all(3 if highlight else 1)
    face.set_corner_radius_all(11)
    for key in ["normal", "hover", "pressed"]:
        card.add_theme_stylebox_override(key, face)


func cell_to_index(cell: Vector2i) -> int:
    return cell.y * COLUMNS + cell.x


func _select_cell(cell: Vector2i) -> void:
    selected = cell
    _refresh()


func _count_in_stock(item: String) -> int:
    return int(stock.get(item, 0))


func _choose_stock(item: String) -> void:
    if _count_in_stock(item) <= 0:
        _say("No copies in stock. Return a shelf item or use a different product.")
        return
    held_id = item
    _say("Selected " + str(CATALOGUE[item]["name"]) + ".")


func _place() -> void:
    var slot := cell_to_index(selected)
    if held_id.is_empty():
        _say("Select an item in the stock room first.")
        return
    if display.has(slot):
        _say("This slot already has a mini. Choose an empty slot.")
        return
    if _count_in_stock(held_id) <= 0:
        _say("That mini is out of stock.")
        return
    _remember()
    display[slot] = held_id
    stock[held_id] = _count_in_stock(held_id) - 1
    _say("Placed " + str(CATALOGUE[held_id]["name"]) + ".")


func _return_item() -> void:
    var slot := cell_to_index(selected)
    var item: String = display.get(slot, "")
    if item.is_empty():
        _say("This slot is already empty.")
        return
    _remember()
    display.erase(slot)
    stock[item] = _count_in_stock(item) + 1
    _say("Returned one " + str(CATALOGUE[item]["name"]) + " to stock.")


func _picnic_unique() -> int:
    var seen := {}
    for item: String in display.values():
        if item in PICNIC:
            seen[item] = true
    return seen.size()


func _swap() -> void:
    if exchanged:
        _say("The studio special has already been claimed.")
        return
    if _count_in_stock("lemon_fizz") < 2:
        _say("You need two spare Lemon Fizz minis in stock.")
        return
    _remember()
    stock["lemon_fizz"] = _count_in_stock("lemon_fizz") - 2
    stock["jam_toast"] = _count_in_stock("jam_toast") + 1
    exchanged = true
    _say("Two Lemon Fizz minis traded for one Jam Toast.")


func _picnic_row() -> bool:
    for column in range(PICNIC.size()):
        if display.get(column, "") != PICNIC[column]:
            return false
    return true


func _remember() -> void:
    history.append({
        "display": display.duplicate(),
        "stock": stock.duplicate(),
        "held_id": held_id,
        "exchanged": exchanged,
    })


func _undo() -> void:
    if history.is_empty():
        _say("There is no display change to undo.")
        return
    var last: Dictionary = history.pop_back()
    display = last["display"]
    stock = last["stock"]
    held_id = last["held_id"]
    exchanged = last["exchanged"]
    _say("Restored the previous shelf and stock room.")


func _say(words: String) -> void:
    message = words
    _refresh()


func _refresh() -> void:
    for slot in range(shelf_buttons.size()):
        var card := shelf_buttons[slot]
        var item: String = display.get(slot, "")
        card.text = ("%02d\n%s" % [slot, CATALOGUE[item]["mark"]]) if not item.is_empty() else ("%02d\nEmpty" % slot)
        var tint: Color = CATALOGUE[item]["ink"] if not item.is_empty() else PAPER
        _palette(card, tint, slot == cell_to_index(selected))
    for index in range(stock_buttons.size()):
        var item: String = CATALOGUE.keys()[index]
        var card := stock_buttons[index]
        card.text = "%s\n%d in stock" % [CATALOGUE[item]["name"], _count_in_stock(item)]
        _palette(card, CATALOGUE[item]["ink"], item == held_id)
    var selected_item: String = display.get(cell_to_index(selected), "")
    detail.text = "Slot %02d  /  %s" % [cell_to_index(selected), "Empty" if selected_item.is_empty() else CATALOGUE[selected_item]["name"]]
    held_label.text = "Selected stock: " + ("None" if held_id.is_empty() else str(CATALOGUE[held_id]["name"]))
    status.text = message
    set_label.text = "Picnic designs: %d/%d" % [_picnic_unique(), PICNIC.size()]
    set_label.text += "  ·  " + ("ROW READY" if _picnic_row() else "Row 0: LEMON / HONEY / MINT")


func _draw() -> void:
    draw_rect(Rect2(Vector2.ZERO, size), PAPER)
    draw_rect(Rect2(0, 0, 960, 111), Color("#d5e7e4"))
    draw_rect(Rect2(32, 157, 527, 288), Color("#b78365"))
    for row in range(ROWS):
        draw_rect(Rect2(36, 243 + row * 94, 519, 12), Color("#90604f"))
    draw_rect(Rect2(575, 157, 346, 352), Color("#e9edda"))
    draw_rect(Rect2(32, 512, 889, 2), EDGE)

GDScript line by line

Follow the line numbers, including the indent at the start of each line. Find the code the game will run first, then look for the function that reacts when you tap or change something.

Read main.gd line by line
  1. extends ControlUse a screen node as the scene root. It owns the cabinet background and all its labels and buttons.
  2. const COLUMNS := 4Keep the horizontal shelf limit in one name. Column values run from zero through three.
  3. const ROWS := 3The practice cabinet has three shelf levels. Row numbers run from zero through two.
  4. const PREVIEW := {0: "lemon_fizz", 1: "honey_hoops", 5: "mint_paste"}Declare only the three occupied start slots. The other nine indexes are absent and count as empty.
  5. const START_STOCK := {"lemon_fizz": 2, "honey_hoops": 1, "mint_paste": 1, "jam_toast": 0}The storage counts exclude the display pieces. There are two spare Lemon Fizz minis plus the one already displayed.
  6. const CATALOGUE := {Collect fictional miniature records by ID. Button labels can change without changing the key that a puzzle recognises.
  7. "lemon_fizz": {"name": "Lemon Fizz", "family": "Drinks", "ink": Color("#f1c55e"), "mark": "LEMON", "note": "A tiny sunshine-yellow can."},Connect the stable product ID to its fictional name, packaging family, colour, short mark and descriptive note.
  8. "honey_hoops": {"name": "Honey Hoops", "family": "Snacks", "ink": Color("#8fc8df"), "mark": "HONEY", "note": "A cereal carton with a hoop motif."},Connect the stable product ID to its fictional name, packaging family, colour, short mark and descriptive note.
  9. "mint_paste": {"name": "Mint Paste", "family": "Care", "ink": Color("#93c4a0"), "mark": "MINT", "note": "A miniature toothpaste carton with a leaf design."},Connect the stable product ID to its fictional name, packaging family, colour, short mark and descriptive note.
  10. "jam_toast": {"name": "Jam Toast", "family": "Snacks", "ink": Color("#eea197"), "mark": "JAM", "note": "A tiny jar from the studio exchange."},Connect the stable product ID to its fictional name, packaging family, colour, short mark and descriptive note.
  11. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  12. const PAPER := Color("#fff5e1")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  13. const INK := Color("#26374e")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value.
  14. const MUTED := Color("#506277")Creates a constant named MUTED. The expression builds a colour from these values. Godot infers the type from the first value.
  15. const NAVY := Color("#1e344a")Creates a constant named NAVY. The expression builds a colour from these values. Godot infers the type from the first value.
  16. const EDGE := Color("#9bafaf")Creates a constant named EDGE. The expression builds a colour from these values. Godot infers the type from the first value.
  17. var selected := Vector2i.ZEROStart the cursor at column zero, row zero. It selects a position even before a stock design is chosen.
  18. var display := PREVIEW.duplicate()Working display holds integer slot keys and product IDs. duplicate gives each attempt its own mutable copy.
  19. var stock := START_STOCK.duplicate()Working stock keeps product IDs and counts in a separate dictionary. Changes here leave the named starting counts intact.
  20. var held_id := ""The empty string represents no product selected. Choosing a product stores its ID without spending a copy.
  21. var message := "Select a product from the stock room."Creates a variable named message. The expression uses the text inside the quotes. Godot infers the type from the first value.
  22. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  23. var detail: LabelDeclares detail for later use. A colon followed by a type says which kind of value belongs here.
  24. var held_label: LabelDeclares held_label for later use. A colon followed by a type says which kind of value belongs here.
  25. var set_label: LabelDeclares set_label for later use. A colon followed by a type says which kind of value belongs here.
  26. var shelf_buttons: Array[Button] = []Keep the twelve cabinet controls in flat slot order so the refresh loop can redraw the correct tile for each occupied slot.
  27. var stock_buttons: Array[Button] = []Keep stock controls in the same order as the catalogue keys. Refresh the text and quantities on the existing controls.
  28. const PICNIC := ["lemon_fizz", "honey_hoops", "mint_paste"]Record the three practice set IDs. From Lesson 17, the order here also gives the clue's exact shelf positions.
  29. var exchanged := falseThe practice exchange has not been claimed. There are only two flag states.
  30. var history: Array[Dictionary] = []Keep earlier accepted edits as dictionaries, newest last. The type brackets require every member to be a dictionary.
  31. func _ready() -> void:Godot calls this scene method when the scene is ready. It creates one practice room and paints the current state.
  32. _label("TINY SHELF STUDIO", Vector2(31, 21), Vector2(575, 47), 34)Calls _label with the values in its parentheses.
  33. _label("MINIATURES LAB / STOCK & DISPLAY", Vector2(34, 72), Vector2(510, 25), 15, MUTED)Calls _label with the values in its parentheses.
  34. _label("THE PICNIC CABINET", Vector2(54, 123), Vector2(485, 31), 20)Calls _label with the values in its parentheses.
  35. _label("STOCK ROOM", Vector2(588, 123), Vector2(308, 31), 20)Calls _label with the values in its parentheses.
  36. for row in range(ROWS):Run the inner loop for the shelves at rows zero, one and two.
  37. for column in range(COLUMNS):Within one row, create buttons for columns zero through three, just as the displayed flat index is calculated.
  38. var cell := Vector2i(column, row)Package the two grid coordinates together. These are positions on the shelf grid rather than positions in pixels.
  39. var point := Vector2(52 + column * 125, 171 + row * 94)Creates a variable named point. The expression packs x and y into one value. Godot infers the type from the first value.
  40. var slot := _button("", point, Vector2(111, 76), _select_cell.bind(cell))Make a tile button and attach a callback carrying this tile's coordinate. The display text is filled in by refresh.
  41. shelf_buttons.append(slot)Save this Button reference at the next available flat index.
  42. for index in range(CATALOGUE.size()):Use one pass per product record so a catalogue change also changes how many stock controls are created.
  43. var item: String = CATALOGUE.keys()[index]Read the product ID for this index. Its record holds the friendly name and colour.
  44. var point := Vector2(587 + (index % 2) * 164, 170 + (index >> 1) * 64)The remainder after dividing the index by two picks the left or right card. Shifting one binary place right groups indexes 0–1 into row 0 and 2–3 into row 1.
  45. var card := _button("", point, Vector2(154, 55), _choose_stock.bind(item))This card sends its product code to the chooser when pressed.
  46. card.add_theme_font_size_override("font_size", 13)Calls card.add_theme_font_size_override with the values in its parentheses.
  47. stock_buttons.append(card)Keep each card for later quantity updates.
  48. held_label = _label("", Vector2(588, 299), Vector2(330, 24), 14)Stores the new value in held_label. The expression calls _label with the values in its parentheses.
  49. set_label = _label("", Vector2(588, 322), Vector2(330, 25), 13, MUTED)Stores the new value in set_label. The expression calls _label with the values in its parentheses.
  50. detail = _label("", Vector2(53, 459), Vector2(482, 36), 15, MUTED)Stores the new value in detail. The expression calls _label with the values in its parentheses.
  51. status = _label("", Vector2(588, 451), Vector2(327, 52), 15)Stores the new value in status. The expression calls _label with the values in its parentheses.
  52. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTWrap long explanatory messages within the stock panel at word boundaries when possible.
  53. _button("Place", Vector2(587, 356), Vector2(100, 41), _place)Place a reusable control and give it the named function to call on a click or tap.
  54. _button("Return", Vector2(699, 356), Vector2(100, 41), _return_item)Place a reusable control and give it the named function to call on a click or tap.
  55. _button("Swap 2 Fizz", Vector2(811, 356), Vector2(100, 41), _swap)Place a reusable control and give it the named function to call on a click or tap.
  56. _button("Undo", Vector2(587, 403), Vector2(100, 38), _undo)Place a reusable control and give it the named function to call on a click or tap.
  57. _refresh()Calls _refresh with the values in its parentheses.
  58. func _label(words: String, point: Vector2, extent: Vector2, font_size: int, colour: Color = INK) -> Label:Defines label, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  59. var label := Label.new()Create a Godot text node that can be added to the visible scene.
  60. label.text = wordsGive the label its starting content. Some labels begin blank and receive current values in refresh.
  61. label.position = pointPlace the label in pixel coordinates inside the parent Control.
  62. label.size = extentSet the label's intended width and height. The width is used when wrapping the report.
  63. label.add_theme_font_size_override("font_size", font_size)Calls label.add_theme_font_size_override with the values in its parentheses.
  64. label.add_theme_color_override("font_color", colour)Calls label.add_theme_color_override with the values in its parentheses.
  65. add_child(label)Attach the newly created label to this Control so Godot can draw it.
  66. return labelHand the actual node back to the caller so it can change the text later.
  67. func _button(words: String, point: Vector2, extent: Vector2, action: Callable) -> Button:Defines button, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  68. var card := Button.new()Create a reusable pressable control.
  69. card.text = wordsUpdates card.text, which controls the words a player sees. The expression reads words.
  70. card.position = pointUpdates card.position, which controls the node's local x and y location. The expression reads point.
  71. card.size = extentUpdates card.size, which controls the control's width and height. The expression reads extent.
  72. card.mouse_default_cursor_shape = Control.CURSOR_POINTING_HANDStores the new value in card.mouse_default_cursor_shape. The expression reads Control.CURSOR_POINTING_HAND.
  73. card.pressed.connect(action)When this button emits its pressed signal, call the function passed to the helper.
  74. card.add_theme_font_size_override("font_size", 15)Calls card.add_theme_font_size_override with the values in its parentheses.
  75. for key in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color"]:Repeats the indented instructions for each value in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color"].
  76. card.add_theme_color_override(key, NAVY)Calls card.add_theme_color_override with the values in its parentheses.
  77. add_child(card)Attach the control to the cabinet interface so it can receive input.
  78. _palette(card, Color("#fff2db"), false)Calls _palette with the values in its parentheses.
  79. return cardReturn the Button so the caller can store it or change its appearance.
  80. func _palette(card: Button, tint: Color, highlight: bool) -> void:Defines palette, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  81. var face := StyleBoxFlat.new()Build a configuration object for a rounded card face. It describes how Godot should draw the control.
  82. face.bg_color = tintMatch the card background to the miniature's packaging or the neutral empty shade.
  83. face.border_color = NAVY if highlight else EDGEUse a dark outline for the selected design or slot. The selection stays visible even if two products have similar colours.
  84. face.set_border_width_all(3 if highlight else 1)Make the active outline three pixels thick. Other cards get a one-pixel line.
  85. face.set_corner_radius_all(11)Round every corner with the same radius.
  86. for key in ["normal", "hover", "pressed"]:Repeats the indented instructions for each value in ["normal", "hover", "pressed"].
  87. card.add_theme_stylebox_override(key, face)Calls card.add_theme_stylebox_override with the values in its parentheses.
  88. func cell_to_index(cell: Vector2i) -> int:Defines cell to index, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  89. return cell.y * COLUMNS + cell.xSkip a full set of four slots for each earlier row, then add the column. For example, row 1 and column 1 becomes flat index 5.
  90. func _select_cell(cell: Vector2i) -> void:Defines select cell, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  91. selected = cellMove the shelf selector to the supplied coordinate. The same event leaves inventory and placements alone.
  92. _refresh()Calls _refresh with the values in its parentheses.
  93. func _count_in_stock(item: String) -> int:Defines count in stock, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  94. return int(stock.get(item, 0))Read the requested storage count. Use zero for a missing key and convert the result to a whole number.
  95. func _choose_stock(item: String) -> void:Defines choose stock, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  96. if _count_in_stock(item) <= 0:Refuse to select a stock card with no copies. The currently selected design remains available to inspect.
  97. _say("No copies in stock. Return a shelf item or use a different product.")Calls _say with the values in its parentheses.
  98. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  99. held_id = itemRemember just the stock design ID. The Place button will use it later with the active shelf coordinate.
  100. _say("Selected " + str(CATALOGUE[item]["name"]) + ".")Calls _say with the values in its parentheses.
  101. func _place() -> void:Defines place, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  102. var slot := cell_to_index(selected)Convert the active two-coordinate selection into a dictionary key before reading or editing the shelf.
  103. if held_id.is_empty():Stop if the player pressed Place before choosing a designed package from storage.
  104. _say("Select an item in the stock room first.")Calls _say with the values in its parentheses.
  105. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  106. if display.has(slot):Check whether the key exists. The practice Place action only fills a gap and refuses to overwrite occupied slots.
  107. _say("This slot already has a mini. Choose an empty slot.")Calls _say with the values in its parentheses.
  108. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  109. if _count_in_stock(held_id) <= 0:Even an already selected design can run out. Check the quantity again at the moment of placement.
  110. _say("That mini is out of stock.")Calls _say with the values in its parentheses.
  111. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  112. _remember()Save the current state before applying this accepted edit. The earlier guards have already returned for invalid actions.
  113. display[slot] = held_idNow that the checks passed, add the product key to the selected shelf slot.
  114. stock[held_id] = _count_in_stock(held_id) - 1Reduce storage by exactly one to match the copy just placed on the shelf.
  115. _say("Placed " + str(CATALOGUE[held_id]["name"]) + ".")Calls _say with the values in its parentheses.
  116. func _return_item() -> void:Defines return item, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  117. var slot := cell_to_index(selected)Convert the active two-coordinate selection into a dictionary key before reading or editing the shelf.
  118. var item: String = display.get(slot, "")Read the current shelf item before erasing it. An absent slot returns an empty ID.
  119. if item.is_empty():An empty slot has no item to refund. Leave both collections as they are.
  120. _say("This slot is already empty.")Calls _say with the values in its parentheses.
  121. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  122. _remember()Save the current state before applying this accepted edit. The earlier guards have already returned for invalid actions.
  123. display.erase(slot)Remove the key entirely. A subsequent has test will now see a genuine gap.
  124. stock[item] = _count_in_stock(item) + 1Return one copy to the stock bin that matches the removed ID.
  125. _say("Returned one " + str(CATALOGUE[item]["name"]) + " to stock.")Calls _say with the values in its parentheses.
  126. func _picnic_unique() -> int:Defines picnic unique, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  127. var seen := {}Start a fresh dictionary so each audit of distinct designs uses only the currently visible minis.
  128. for item: String in display.values():Read product IDs because position does not matter for the unique-design count.
  129. if item in PICNIC:Count only IDs that appear on the practice set's list.
  130. seen[item] = trueA repeat writes to the same key. The dictionary records knowledge of a design rather than the number of copies.
  131. return seen.size()Return the number of unique matching designs.
  132. func _swap() -> void:Defines swap, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  133. if exchanged:Stop a second use of this exchange, even after more copies have been returned to stock.
  134. _say("The studio special has already been claimed.")Calls _say with the values in its parentheses.
  135. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  136. if _count_in_stock("lemon_fizz") < 2:Confirm two spare copies are currently available. Displayed copies are in another dictionary.
  137. _say("You need two spare Lemon Fizz minis in stock.")Calls _say with the values in its parentheses.
  138. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  139. _remember()Save the current state before applying this accepted edit. The earlier guards have already returned for invalid actions.
  140. stock["lemon_fizz"] = _count_in_stock("lemon_fizz") - 2Spend the two exact spare minis named by the deal.
  141. stock["jam_toast"] = _count_in_stock("jam_toast") + 1Give the announced item, Jam Toast, with no random roll.
  142. exchanged = trueRecord that the one-time deal has been applied.
  143. _say("Two Lemon Fizz minis traded for one Jam Toast.")Calls _say with the values in its parentheses.
  144. func _picnic_row() -> bool:Defines picnic row, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  145. for column in range(PICNIC.size()):Check each of the first three slots in row zero. The column can also serve as a flat slot key because the row is zero.
  146. if display.get(column, "") != PICNIC[column]:Compare the stored mini and required mini at the same position. One wrong or missing item is enough to fail.
  147. return falseStop as soon as one required slot has the wrong ID.
  148. return trueReturn success only after checking every requested slot.
  149. func _remember() -> void:Defines remember, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  150. history.append({Add a snapshot just before a legal edit changes the working state.
  151. "display": display.duplicate(),Save a separate copy of the slot-to-product mapping. Later shelf edits leave this record undisturbed.
  152. "stock": stock.duplicate(),Copy counts too. A reference to the same dictionary would follow later edits.
  153. "held_id": held_id,Remember the selected design. It may explain which piece was placed or swapped.
  154. "exchanged": exchanged,Remember the used-deal flag so undo can reverse an exchange completely.
  155. })Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  156. func _undo() -> void:Defines undo, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  157. if history.is_empty():If there are no accepted edits to reverse, leave the shelf alone and explain why.
  158. _say("There is no display change to undo.")Calls _say with the values in its parentheses.
  159. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  160. var last: Dictionary = history.pop_back()Remove and retrieve the latest snapshot. Earlier snapshots wait for a later Undo.
  161. display = last["display"]Make the snapshot's saved cabinet your live one again.
  162. stock = last["stock"]Restore storage at the same time as the cabinet to avoid losing or duplicating a copy.
  163. held_id = last["held_id"]Restore the selected stock design from the moment before the edited action.
  164. exchanged = last["exchanged"]Restore the trade flag so reversing the deal restores its availability as well.
  165. _say("Restored the previous shelf and stock room.")Calls _say with the values in its parentheses.
  166. func _say(words: String) -> void:Defines say, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  167. message = wordsStores the new value in message. The expression reads words.
  168. _refresh()Calls _refresh with the values in its parentheses.
  169. func _refresh() -> void:Defines refresh, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  170. for slot in range(shelf_buttons.size()):Repeats the indented instructions for each value in range(shelf_buttons.size()).
  171. var card := shelf_buttons[slot]Creates a variable named card. The expression looks up the item or key written between the square brackets. Godot infers the type from the first value.
  172. var item: String = display.get(slot, "")Read the current shelf item before erasing it. An absent slot returns an empty ID.
  173. card.text = ("%02d\n%s" % [slot, CATALOGUE[item]["mark"]]) if not item.is_empty() else ("%02d\nEmpty" % slot)Updates card.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  174. var tint: Color = CATALOGUE[item]["ink"] if not item.is_empty() else PAPERCreates a variable named tint. The expression chooses one of two values by checking the condition in the middle. The type after the colon says what kind of value it can hold.
  175. _palette(card, tint, slot == cell_to_index(selected))Calls _palette with the values in its parentheses.
  176. for index in range(stock_buttons.size()):Repeats the indented instructions for each value in range(stock_buttons.size()).
  177. var item: String = CATALOGUE.keys()[index]Read the product ID for this index. Its record holds the friendly name and colour.
  178. var card := stock_buttons[index]Creates a variable named card. The expression looks up the item or key written between the square brackets. Godot infers the type from the first value.
  179. card.text = "%s\n%d in stock" % [CATALOGUE[item]["name"], _count_in_stock(item)]Updates card.text, which controls the words a player sees. The expression uses the text inside the quotes.
  180. _palette(card, CATALOGUE[item]["ink"], item == held_id)Calls _palette with the values in its parentheses.
  181. var selected_item: String = display.get(cell_to_index(selected), "")Creates a variable named selected_item. The expression looks up a named or indexed value, using a fallback when the call gives one. The type after the colon says what kind of value it can hold.
  182. detail.text = "Slot %02d / %s" % [cell_to_index(selected), "Empty" if selected_item.is_empty() else CATALOGUE[selected_item]["name"]]Updates detail.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  183. held_label.text = "Selected stock: " + ("None" if held_id.is_empty() else str(CATALOGUE[held_id]["name"]))Updates held_label.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  184. status.text = messageShow the latest result or refusal. The visible explanation makes a guard understandable to the player.
  185. set_label.text = "Picnic designs: %d/%d" % [_picnic_unique(), PICNIC.size()]Fill the two whole-number placeholders with the distinct-design count and required number.
  186. set_label.text += " · " + ("ROW READY" if _picnic_row() else "Row 0: LEMON / HONEY / MINT")Join a separate order clue status to the distinct-design count. The row can be incomplete while the tally is full.
  187. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  188. draw_rect(Rect2(Vector2.ZERO, size), PAPER)Draw part of the room on its background layer. Rendering describes the room and leaves the current shelf data alone.
  189. draw_rect(Rect2(0, 0, 960, 111), Color("#d5e7e4"))Draw part of the room on its background layer. Rendering describes the room and leaves the current shelf data alone.
  190. draw_rect(Rect2(32, 157, 527, 288), Color("#b78365"))Draw part of the room on its background layer. Rendering describes the room and leaves the current shelf data alone.
  191. for row in range(ROWS):Run the inner loop for the shelves at rows zero, one and two.
  192. draw_rect(Rect2(36, 243 + row * 94, 519, 12), Color("#90604f"))Draw part of the room on its background layer. Rendering describes the room and leaves the current shelf data alone.
  193. draw_rect(Rect2(575, 157, 346, 352), Color("#e9edda"))Draw part of the room on its background layer. Rendering describes the room and leaves the current shelf data alone.
  194. draw_rect(Rect2(32, 512, 889, 2), EDGE)Draw part of the room on its background layer. Rendering describes the room and leaves the current shelf data alone.

Find and fix a bug

If Undo appears to restore the same modified stock, check that _remember calls stock.duplicate() rather than storing stock directly.

Try a change

Make two accepted placements with a refused action in between. Undo twice and verify which placements disappear and in what order.