Tiny Shelf Studio · Lesson 20 of 50 · Beginner to intermediate · About 29 min
The cabinet is ready for displays, but the studio needs a way to catch missing or duplicated pieces when a programmer changes the rules.

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


Build it step by step
Language and tools in this lesson Invariants, Array.count(), Expected vs actual, Boolean checks, Regression paths.
-
Open a practice copy
Extract the course. In the Godot Project Manager, import checkpoints/20/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.
-
Count a specific design in two places
Find _total. Add the quantity in stock to the number of matching IDs in display.values(). Work out the starting Lemon Fizz total.
return _count_in_stock(item) + display.values().count(item)Why it works An invariant is a fact that should stay true. Placement and Return move a mini between locations, so the total should stay the same.
-
Compute an expected opening total
In _passes_audit, loop over CATALOGUE. Read the negative-stock guard and find the expected amount from START_STOCK and PREVIEW.
var expected := int(START_STOCK[item]) + PREVIEW.values().count(item)Why it works Each design gets its own comparison. This catches a case where one wrong item could be exchanged for another without changing the whole cabinet's total.
-
Include the single legitimate trade
Read the two checks on exchanged. Predict how the Lemon Fizz and Jam Toast totals change after Swap 2 Fizz.
if exchanged and item == "lemon_fizz": expected -= 2Why it works A swap is the one legitimate change to the number of copies. The audit can calculate its effect from the stored Boolean.
-
Run Audit after several actions
Audit the starter shelf. Trade, place Jam Toast, undo once and audit again. In a separate copy, temporarily remove the stock subtraction in _place, then place a mini and run Audit.
if _total(item) != expected:Why it works Running the same check after different paths catches regressions. Intentionally breaking a working rule proves the test can detect the problem.
-
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
-
Audit the starter cabinet Lemon Fizz total is 2 in stock plus 1 on display.
What you see. All stock tallies reconcile. -
Swap, place Jam Toast and Audit The swap lowers Fizz by 2 and creates 1 Jam Toast. Place only moves that Jam Toast.
What you see. The audit passes. -
Try a Place with the stock subtraction temporarily removed A new mini appears without spending its copy.
What you see. The audit reports that a tally is wrong.
Predict before you run Can an audit of the total detect an item in the wrong display position?
Reveal the answer
No. The quantity can still be right. Test layout with the exact row clue and copies with the stock audit.
Complete checkpoint
The intact checkpoint passes its tally test after places, returns, swaps, undo and reset. The deliberately broken placement is detected.
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)
_button("Reset lab", Vector2(699, 403), Vector2(100, 38), _reset)
_button("Audit", Vector2(811, 403), Vector2(100, 38), _check)
_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 _reset() -> void:
display = PREVIEW.duplicate()
stock = START_STOCK.duplicate()
held_id = ""
selected = Vector2i.ZERO
exchanged = false
history.clear()
_say("Restored the starter shelf. You can run the puzzle again.")
func _total(item: String) -> int:
return _count_in_stock(item) + display.values().count(item)
func _passes_audit() -> bool:
for item: String in CATALOGUE:
if _count_in_stock(item) < 0:
return false
var expected := int(START_STOCK[item]) + PREVIEW.values().count(item)
if exchanged and item == "lemon_fizz":
expected -= 2
if exchanged and item == "jam_toast":
expected += 1
if _total(item) != expected:
return false
return true
func _check() -> void:
_say("All stock tallies reconcile." if _passes_audit() else "A stock tally is wrong. Trace a recent move.")
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
-
extends ControlUse a screen node as the scene root. It owns the cabinet background and all its labels and buttons. -
const COLUMNS := 4Keep the horizontal shelf limit in one name. Column values run from zero through three. -
const ROWS := 3The practice cabinet has three shelf levels. Row numbers run from zero through two. -
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. -
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. -
const CATALOGUE := {Collect fictional miniature records by ID. Button labels can change without changing the key that a puzzle recognises. -
"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. -
"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. -
"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. -
"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. -
}Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
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. -
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. -
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. -
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. -
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. -
var selected := Vector2i.ZEROStart the cursor at column zero, row zero. It selects a position even before a stock design is chosen. -
var display := PREVIEW.duplicate()Working display holds integer slot keys and product IDs. duplicate gives each attempt its own mutable copy. -
var stock := START_STOCK.duplicate()Working stock keeps product IDs and counts in a separate dictionary. Changes here leave the named starting counts intact. -
var held_id := ""The empty string represents no product selected. Choosing a product stores its ID without spending a copy. -
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. -
var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here. -
var detail: LabelDeclares detail for later use. A colon followed by a type says which kind of value belongs here. -
var held_label: LabelDeclares held_label for later use. A colon followed by a type says which kind of value belongs here. -
var set_label: LabelDeclares set_label for later use. A colon followed by a type says which kind of value belongs here. -
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. -
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. -
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. -
var exchanged := falseThe practice exchange has not been claimed. There are only two flag states. -
var history: Array[Dictionary] = []Keep earlier accepted edits as dictionaries, newest last. The type brackets require every member to be a dictionary. -
func _ready() -> void:Godot calls this scene method when the scene is ready. It creates one practice room and paints the current state. -
_label("TINY SHELF STUDIO", Vector2(31, 21), Vector2(575, 47), 34)Calls _label with the values in its parentheses. -
_label("MINIATURES LAB / STOCK & DISPLAY", Vector2(34, 72), Vector2(510, 25), 15, MUTED)Calls _label with the values in its parentheses. -
_label("THE PICNIC CABINET", Vector2(54, 123), Vector2(485, 31), 20)Calls _label with the values in its parentheses. -
_label("STOCK ROOM", Vector2(588, 123), Vector2(308, 31), 20)Calls _label with the values in its parentheses. -
for row in range(ROWS):Run the inner loop for the shelves at rows zero, one and two. -
for column in range(COLUMNS):Within one row, create buttons for columns zero through three, just as the displayed flat index is calculated. -
var cell := Vector2i(column, row)Package the two grid coordinates together. These are positions on the shelf grid rather than positions in pixels. -
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. -
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. -
shelf_buttons.append(slot)Save this Button reference at the next available flat index. -
for index in range(CATALOGUE.size()):Use one pass per product record so a catalogue change also changes how many stock controls are created. -
var item: String = CATALOGUE.keys()[index]Read the product ID for this index. Its record holds the friendly name and colour. -
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. -
var card := _button("", point, Vector2(154, 55), _choose_stock.bind(item))This card sends its product code to the chooser when pressed. -
card.add_theme_font_size_override("font_size", 13)Calls card.add_theme_font_size_override with the values in its parentheses. -
stock_buttons.append(card)Keep each card for later quantity updates. -
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. -
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. -
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. -
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. -
status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTWrap long explanatory messages within the stock panel at word boundaries when possible. -
_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. -
_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. -
_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. -
_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. -
_button("Reset lab", Vector2(699, 403), Vector2(100, 38), _reset)Place a reusable control and give it the named function to call on a click or tap. -
_button("Audit", Vector2(811, 403), Vector2(100, 38), _check)Place a reusable control and give it the named function to call on a click or tap. -
_refresh()Calls _refresh with the values in its parentheses. -
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. -
var label := Label.new()Create a Godot text node that can be added to the visible scene. -
label.text = wordsGive the label its starting content. Some labels begin blank and receive current values in refresh. -
label.position = pointPlace the label in pixel coordinates inside the parent Control. -
label.size = extentSet the label's intended width and height. The width is used when wrapping the report. -
label.add_theme_font_size_override("font_size", font_size)Calls label.add_theme_font_size_override with the values in its parentheses. -
label.add_theme_color_override("font_color", colour)Calls label.add_theme_color_override with the values in its parentheses. -
add_child(label)Attach the newly created label to this Control so Godot can draw it. -
return labelHand the actual node back to the caller so it can change the text later. -
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. -
var card := Button.new()Create a reusable pressable control. -
card.text = wordsUpdates card.text, which controls the words a player sees. The expression reads words. -
card.position = pointUpdates card.position, which controls the node's local x and y location. The expression reads point. -
card.size = extentUpdates card.size, which controls the control's width and height. The expression reads extent. -
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. -
card.pressed.connect(action)When this button emits its pressed signal, call the function passed to the helper. -
card.add_theme_font_size_override("font_size", 15)Calls card.add_theme_font_size_override with the values in its parentheses. -
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"]. -
card.add_theme_color_override(key, NAVY)Calls card.add_theme_color_override with the values in its parentheses. -
add_child(card)Attach the control to the cabinet interface so it can receive input. -
_palette(card, Color("#fff2db"), false)Calls _palette with the values in its parentheses. -
return cardReturn the Button so the caller can store it or change its appearance. -
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. -
var face := StyleBoxFlat.new()Build a configuration object for a rounded card face. It describes how Godot should draw the control. -
face.bg_color = tintMatch the card background to the miniature's packaging or the neutral empty shade. -
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. -
face.set_border_width_all(3 if highlight else 1)Make the active outline three pixels thick. Other cards get a one-pixel line. -
face.set_corner_radius_all(11)Round every corner with the same radius. -
for key in ["normal", "hover", "pressed"]:Repeats the indented instructions for each value in ["normal", "hover", "pressed"]. -
card.add_theme_stylebox_override(key, face)Calls card.add_theme_stylebox_override with the values in its parentheses. -
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. -
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. -
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. -
selected = cellMove the shelf selector to the supplied coordinate. The same event leaves inventory and placements alone. -
_refresh()Calls _refresh with the values in its parentheses. -
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. -
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. -
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. -
if _count_in_stock(item) <= 0:Refuse to select a stock card with no copies. The currently selected design remains available to inspect. -
_say("No copies in stock. Return a shelf item or use a different product.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
held_id = itemRemember just the stock design ID. The Place button will use it later with the active shelf coordinate. -
_say("Selected " + str(CATALOGUE[item]["name"]) + ".")Calls _say with the values in its parentheses. -
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. -
var slot := cell_to_index(selected)Convert the active two-coordinate selection into a dictionary key before reading or editing the shelf. -
if held_id.is_empty():Stop if the player pressed Place before choosing a designed package from storage. -
_say("Select an item in the stock room first.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
if display.has(slot):Check whether the key exists. The practice Place action only fills a gap and refuses to overwrite occupied slots. -
_say("This slot already has a mini. Choose an empty slot.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
if _count_in_stock(held_id) <= 0:Even an already selected design can run out. Check the quantity again at the moment of placement. -
_say("That mini is out of stock.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
_remember()Save the current state before applying this accepted edit. The earlier guards have already returned for invalid actions. -
display[slot] = held_idNow that the checks passed, add the product key to the selected shelf slot. -
stock[held_id] = _count_in_stock(held_id) - 1Reduce storage by exactly one to match the copy just placed on the shelf. -
_say("Placed " + str(CATALOGUE[held_id]["name"]) + ".")Calls _say with the values in its parentheses. -
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. -
var slot := cell_to_index(selected)Convert the active two-coordinate selection into a dictionary key before reading or editing the shelf. -
var item: String = display.get(slot, "")Read the current shelf item before erasing it. An absent slot returns an empty ID. -
if item.is_empty():An empty slot has no item to refund. Leave both collections as they are. -
_say("This slot is already empty.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
_remember()Save the current state before applying this accepted edit. The earlier guards have already returned for invalid actions. -
display.erase(slot)Remove the key entirely. A subsequent has test will now see a genuine gap. -
stock[item] = _count_in_stock(item) + 1Return one copy to the stock bin that matches the removed ID. -
_say("Returned one " + str(CATALOGUE[item]["name"]) + " to stock.")Calls _say with the values in its parentheses. -
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. -
var seen := {}Start a fresh dictionary so each audit of distinct designs uses only the currently visible minis. -
for item: String in display.values():Read product IDs because position does not matter for the unique-design count. -
if item in PICNIC:Count only IDs that appear on the practice set's list. -
seen[item] = trueA repeat writes to the same key. The dictionary records knowledge of a design rather than the number of copies. -
return seen.size()Return the number of unique matching designs. -
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. -
if exchanged:Stop a second use of this exchange, even after more copies have been returned to stock. -
_say("The studio special has already been claimed.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
if _count_in_stock("lemon_fizz") < 2:Confirm two spare copies are currently available. Displayed copies are in another dictionary. -
_say("You need two spare Lemon Fizz minis in stock.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
_remember()Save the current state before applying this accepted edit. The earlier guards have already returned for invalid actions. -
stock["lemon_fizz"] = _count_in_stock("lemon_fizz") - 2Spend the two exact spare minis named by the deal. -
stock["jam_toast"] = _count_in_stock("jam_toast") + 1Give the announced item, Jam Toast, with no random roll. -
exchanged = trueRecord that the one-time deal has been applied. -
_say("Two Lemon Fizz minis traded for one Jam Toast.")Calls _say with the values in its parentheses. -
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. -
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. -
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. -
return falseStop as soon as one required slot has the wrong ID. -
return trueReturn success only after checking every requested slot. -
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. -
history.append({Add a snapshot just before a legal edit changes the working state. -
"display": display.duplicate(),Save a separate copy of the slot-to-product mapping. Later shelf edits leave this record undisturbed. -
"stock": stock.duplicate(),Copy counts too. A reference to the same dictionary would follow later edits. -
"held_id": held_id,Remember the selected design. It may explain which piece was placed or swapped. -
"exchanged": exchanged,Remember the used-deal flag so undo can reverse an exchange completely. -
})Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
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. -
if history.is_empty():If there are no accepted edits to reverse, leave the shelf alone and explain why. -
_say("There is no display change to undo.")Calls _say with the values in its parentheses. -
returnLeave this action after explaining the refusal. State edits that come later in the function won't run. -
var last: Dictionary = history.pop_back()Remove and retrieve the latest snapshot. Earlier snapshots wait for a later Undo. -
display = last["display"]Make the snapshot's saved cabinet your live one again. -
stock = last["stock"]Restore storage at the same time as the cabinet to avoid losing or duplicating a copy. -
held_id = last["held_id"]Restore the selected stock design from the moment before the edited action. -
exchanged = last["exchanged"]Restore the trade flag so reversing the deal restores its availability as well. -
_say("Restored the previous shelf and stock room.")Calls _say with the values in its parentheses. -
func _reset() -> void:Defines reset, 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. -
display = PREVIEW.duplicate()Reset to a fresh copy of the three starting shelf placements. -
stock = START_STOCK.duplicate()Reset to a fresh copy of the four opening stock counts. -
held_id = ""Stores the new value in held_id. The expression uses the text inside the quotes. -
selected = Vector2i.ZEROMove the selection back to the top-left square. -
exchanged = falseMake the printed trade available again for the next playtest. -
history.clear()Drop old snapshots. Reset cannot be undone into an earlier practice run. -
_say("Restored the starter shelf. You can run the puzzle again.")Calls _say with the values in its parentheses. -
func _total(item: String) -> int:Defines total, 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. -
return _count_in_stock(item) + display.values().count(item)Count the design across both places. Array.count includes every physical copy, while _picnic_unique counted designs only once. -
func _passes_audit() -> bool:Defines passes audit, 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. -
for item: String in CATALOGUE:Audit each catalogue ID separately to find an incorrect change even if the overall number of minis stayed the same. -
if _count_in_stock(item) < 0:Reject a negative count before comparing totals. The cabinet cannot borrow minis it does not have. -
return falseThe extra indent keeps this failure result inside the failed comparison. -
var expected := int(START_STOCK[item]) + PREVIEW.values().count(item)Calculate what this design would total before any exchange, using the unmodified opening data. -
if exchanged and item == "lemon_fizz":Apply the documented cost only for Lemon Fizz and only after the exchange. -
expected -= 2Allow two fewer Fizz minis than the starting total. -
if exchanged and item == "jam_toast":Apply the documented reward only to Jam Toast and only after the exchange. -
expected += 1Allow one more Jam Toast than the starting total. -
if _total(item) != expected:Flag a mismatch between the quantity the rules allow and the quantity currently present. -
return falseThe extra indent keeps this failure result inside the failed comparison. -
return trueEvery item passed all checks. The cabinet totals are consistent. -
func _check() -> void:Defines check, 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. -
_say("All stock tallies reconcile." if _passes_audit() else "A stock tally is wrong. Trace a recent move.")Calls _say with the values in its parentheses. -
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. -
message = wordsStores the new value in message. The expression reads words. -
_refresh()Calls _refresh with the values in its parentheses. -
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. -
for slot in range(shelf_buttons.size()):Repeats the indented instructions for each value in range(shelf_buttons.size()). -
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. -
var item: String = display.get(slot, "")Read the current shelf item before erasing it. An absent slot returns an empty ID. -
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. -
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. -
_palette(card, tint, slot == cell_to_index(selected))Calls _palette with the values in its parentheses. -
for index in range(stock_buttons.size()):Repeats the indented instructions for each value in range(stock_buttons.size()). -
var item: String = CATALOGUE.keys()[index]Read the product ID for this index. Its record holds the friendly name and colour. -
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. -
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. -
_palette(card, CATALOGUE[item]["ink"], item == held_id)Calls _palette with the values in its parentheses. -
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. -
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. -
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. -
status.text = messageShow the latest result or refusal. The visible explanation makes a guard understandable to the player. -
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. -
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. -
func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state. -
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. -
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. -
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. -
for row in range(ROWS):Run the inner loop for the shelves at rows zero, one and two. -
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. -
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. -
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 Audit reports a break only after a legitimate trade, check both expected adjustments. Fizz falls by two and Jam Toast rises by one.
Try a change
Add a second audit for invalid shelf keys. Consider checking indexes below zero and indexes at or above COLUMNS times ROWS.