Tiny Shelf 13 · Return a displayed mini to stock

Tiny Shelf Studio · Lesson 13 of 50 · Beginner to intermediate · About 22 min

One shelf slot needs to make room for another design. Return puts a miniature back in storage, ready for another layout.

Tiny fictional paper cartons, jars and tins displayed on a handmade wooden shelf.
What you’ll make Free a display slot and refund the copy to the correct stock bin.

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/12 when the lesson builds on prior work, or copy the checkpoints/13 folder to try this lesson on its own. Read the file names in the steps before editing.

Read the mini ID. Get the item in the selected spot. → Erase its shelf entry. Leave a real gap in the cabinet. → Refund one. Increase the corresponding stock count.
Read the mini ID → Erase its shelf entry → Refund one
Godot checkpoint window for Return a displayed mini to stock
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Dictionary.erase(), Dictionary.get() with a fallback, Typed local variable, Return and refund.

  1. Open a practice copy

    Extract the course. In the Godot Project Manager, import checkpoints/13/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. Add a separate Return action

    Find the Return button in _ready. Trace its callback to _return_item, then compare it with _place.

    _button("Return", Vector2(699, 356), Vector2(100, 41), _return_item)

    Why it works Both actions use selected, but Return first reads what is actually in that display slot.

  3. Read the occupied slot safely

    Inside _return_item, look up the selected key and supply an empty string for a gap. The local item variable stores the item ID.

    var item: String = display.get(slot, "")

    Why it works Keeping the ID in a local variable lets you refer to the product after its key has been removed from display.

  4. Remove the key

    Find display.erase(slot). Select slot 05 and press Return. Check that the tile now says Empty.

    display.erase(slot)

    Why it works erase removes the key and its value. If an empty string were assigned to the key instead, display.has(slot) would still call the slot occupied.

  5. Refund one copy and refresh

    Read the stock addition. Compare Mint Paste before and after its return. Then try to Return at the very same slot again.

    stock[item] = _count_in_stock(item) + 1

    Why it works The early return on an empty slot stops repeated refunds. A legitimate return adds exactly one.

  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. Select slot 05 Mint Paste is on display and stock has 1 more.
    What you see. The inspector shows Mint Paste.
  2. Press Return The slot entry is erased and Mint stock increases.
    What you see. Slot 05 reads Empty. Mint stock becomes 2.
  3. Press Return again The slot lookup supplies an empty ID.
    What you see. The studio refuses and Mint stock remains 2.

Predict before you run Could a player repeatedly return an empty tile to create more copies?

Reveal the answer

No. The missing item check stops the action before stock is increased.

Complete checkpoint

Returning one mini clears the slot and increments that product's stock exactly once.

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] = []


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)
    _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
    display[slot] = held_id
    stock[held_id] = _count_in_stock(held_id) - 1
    var name_before_clear: String = held_id
    held_id = ""
    _say("Placed " + str(CATALOGUE[name_before_clear]["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
    display.erase(slot)
    stock[item] = _count_in_stock(item) + 1
    _say("Returned one " + str(CATALOGUE[item]["name"]) + " to stock.")


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


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. func _ready() -> void:Godot calls this scene method when the scene is ready. It creates one practice room and paints the current state.
  29. _label("TINY SHELF STUDIO", Vector2(31, 21), Vector2(575, 47), 34)Calls _label with the values in its parentheses.
  30. _label("MINIATURES LAB / STOCK & DISPLAY", Vector2(34, 72), Vector2(510, 25), 15, MUTED)Calls _label with the values in its parentheses.
  31. _label("THE PICNIC CABINET", Vector2(54, 123), Vector2(485, 31), 20)Calls _label with the values in its parentheses.
  32. _label("STOCK ROOM", Vector2(588, 123), Vector2(308, 31), 20)Calls _label with the values in its parentheses.
  33. for row in range(ROWS):Run the inner loop for the shelves at rows zero, one and two.
  34. for column in range(COLUMNS):Within one row, create buttons for columns zero through three, just as the displayed flat index is calculated.
  35. var cell := Vector2i(column, row)Package the two grid coordinates together. These are positions on the shelf grid rather than positions in pixels.
  36. 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.
  37. 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.
  38. shelf_buttons.append(slot)Save this Button reference at the next available flat index.
  39. for index in range(CATALOGUE.size()):Use one pass per product record so a catalogue change also changes how many stock controls are created.
  40. var item: String = CATALOGUE.keys()[index]Read the product ID for this index. Its record holds the friendly name and colour.
  41. 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.
  42. var card := _button("", point, Vector2(154, 55), _choose_stock.bind(item))This card sends its product code to the chooser when pressed.
  43. card.add_theme_font_size_override("font_size", 13)Calls card.add_theme_font_size_override with the values in its parentheses.
  44. stock_buttons.append(card)Keep each card for later quantity updates.
  45. 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.
  46. 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.
  47. 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.
  48. 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.
  49. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTWrap long explanatory messages within the stock panel at word boundaries when possible.
  50. _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.
  51. _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.
  52. _refresh()Calls _refresh with the values in its parentheses.
  53. 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.
  54. var label := Label.new()Create a Godot text node that can be added to the visible scene.
  55. label.text = wordsGive the label its starting content. Some labels begin blank and receive current values in refresh.
  56. label.position = pointPlace the label in pixel coordinates inside the parent Control.
  57. label.size = extentSet the label's intended width and height. The width is used when wrapping the report.
  58. label.add_theme_font_size_override("font_size", font_size)Calls label.add_theme_font_size_override with the values in its parentheses.
  59. label.add_theme_color_override("font_color", colour)Calls label.add_theme_color_override with the values in its parentheses.
  60. add_child(label)Attach the newly created label to this Control so Godot can draw it.
  61. return labelHand the actual node back to the caller so it can change the text later.
  62. 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.
  63. var card := Button.new()Create a reusable pressable control.
  64. card.text = wordsUpdates card.text, which controls the words a player sees. The expression reads words.
  65. card.position = pointUpdates card.position, which controls the node's local x and y location. The expression reads point.
  66. card.size = extentUpdates card.size, which controls the control's width and height. The expression reads extent.
  67. 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.
  68. card.pressed.connect(action)When this button emits its pressed signal, call the function passed to the helper.
  69. card.add_theme_font_size_override("font_size", 15)Calls card.add_theme_font_size_override with the values in its parentheses.
  70. 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"].
  71. card.add_theme_color_override(key, NAVY)Calls card.add_theme_color_override with the values in its parentheses.
  72. add_child(card)Attach the control to the cabinet interface so it can receive input.
  73. _palette(card, Color("#fff2db"), false)Calls _palette with the values in its parentheses.
  74. return cardReturn the Button so the caller can store it or change its appearance.
  75. 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.
  76. var face := StyleBoxFlat.new()Build a configuration object for a rounded card face. It describes how Godot should draw the control.
  77. face.bg_color = tintMatch the card background to the miniature's packaging or the neutral empty shade.
  78. 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.
  79. face.set_border_width_all(3 if highlight else 1)Make the active outline three pixels thick. Other cards get a one-pixel line.
  80. face.set_corner_radius_all(11)Round every corner with the same radius.
  81. for key in ["normal", "hover", "pressed"]:Repeats the indented instructions for each value in ["normal", "hover", "pressed"].
  82. card.add_theme_stylebox_override(key, face)Calls card.add_theme_stylebox_override with the values in its parentheses.
  83. 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.
  84. 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.
  85. 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.
  86. selected = cellMove the shelf selector to the supplied coordinate. The same event leaves inventory and placements alone.
  87. _refresh()Calls _refresh with the values in its parentheses.
  88. 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.
  89. 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.
  90. 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.
  91. if _count_in_stock(item) <= 0:Refuse to select a stock card with no copies. The currently selected design remains available to inspect.
  92. _say("No copies in stock. Return a shelf item or use a different product.")Calls _say with the values in its parentheses.
  93. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  94. held_id = itemRemember just the stock design ID. The Place button will use it later with the active shelf coordinate.
  95. _say("Selected " + str(CATALOGUE[item]["name"]) + ".")Calls _say with the values in its parentheses.
  96. 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.
  97. var slot := cell_to_index(selected)Convert the active two-coordinate selection into a dictionary key before reading or editing the shelf.
  98. if held_id.is_empty():Stop if the player pressed Place before choosing a designed package from storage.
  99. _say("Select an item in the stock room first.")Calls _say with the values in its parentheses.
  100. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  101. if display.has(slot):Check whether the key exists. The practice Place action only fills a gap and refuses to overwrite occupied slots.
  102. _say("This slot already has a mini. Choose an empty slot.")Calls _say with the values in its parentheses.
  103. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  104. display[slot] = held_idNow that the checks passed, add the product key to the selected shelf slot.
  105. stock[held_id] = _count_in_stock(held_id) - 1Reduce storage by exactly one to match the copy just placed on the shelf.
  106. var name_before_clear: String = held_idKeep the used product's ID locally while clearing the active stock selection.
  107. held_id = ""Stores the new value in held_id. The expression uses the text inside the quotes.
  108. _say("Placed " + str(CATALOGUE[name_before_clear]["name"]) + ".")Calls _say with the values in its parentheses.
  109. 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.
  110. var slot := cell_to_index(selected)Convert the active two-coordinate selection into a dictionary key before reading or editing the shelf.
  111. var item: String = display.get(slot, "")Read the current shelf item before erasing it. An absent slot returns an empty ID.
  112. if item.is_empty():An empty slot has no item to refund. Leave both collections as they are.
  113. _say("This slot is already empty.")Calls _say with the values in its parentheses.
  114. returnLeave this action after explaining the refusal. State edits that come later in the function won't run.
  115. display.erase(slot)Remove the key entirely. A subsequent has test will now see a genuine gap.
  116. stock[item] = _count_in_stock(item) + 1Return one copy to the stock bin that matches the removed ID.
  117. _say("Returned one " + str(CATALOGUE[item]["name"]) + " to stock.")Calls _say with the values in its parentheses.
  118. 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.
  119. message = wordsStores the new value in message. The expression reads words.
  120. _refresh()Calls _refresh with the values in its parentheses.
  121. 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.
  122. for slot in range(shelf_buttons.size()):Repeats the indented instructions for each value in range(shelf_buttons.size()).
  123. 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.
  124. var item: String = display.get(slot, "")Read the current shelf item before erasing it. An absent slot returns an empty ID.
  125. 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.
  126. 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.
  127. _palette(card, tint, slot == cell_to_index(selected))Calls _palette with the values in its parentheses.
  128. for index in range(stock_buttons.size()):Repeats the indented instructions for each value in range(stock_buttons.size()).
  129. var item: String = CATALOGUE.keys()[index]Read the product ID for this index. Its record holds the friendly name and colour.
  130. 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.
  131. 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.
  132. _palette(card, CATALOGUE[item]["ink"], item == held_id)Calls _palette with the values in its parentheses.
  133. 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.
  134. 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.
  135. 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.
  136. status.text = messageShow the latest result or refusal. The visible explanation makes a guard understandable to the player.
  137. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  138. 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.
  139. 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.
  140. 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.
  141. for row in range(ROWS):Run the inner loop for the shelves at rows zero, one and two.
  142. 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.
  143. 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.
  144. 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 Place still refuses an emptied spot, check that Return calls erase(slot). The occupancy guard tests for the presence of a key.

Try a change

Return slot 00, choose Lemon Fizz from stock, and put it back in slot 04. Explain why the starting Lemon Fizz quantity in stock is the same afterwards.