Tiny Shelf Studio · Lesson 24 of 50 · Intermediate · About 29 min
The window has a snacks shelf. The client asks for exactly two snacks in the first row, leaving one place available for the fixed Lemon Fizz mini.

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/23 when the lesson builds on prior work, or copy the checkpoints/24 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 exact quota, counter, for loop, continue, Vector2i, upper bound.
-
Read the row brief
Find the first rows entry in morning_window.json. Read row 0, snacks and count 2. On the screen this is the top row, printed R1.
Why it works The array starts rows at zero. The displayed label is written for people who normally start counting at one.
-
Skip other rows
Find row_totals in shelf_rules.gd. Trace coordinates and continue. Put Jam Toast in R2 C1, then press Check row totals.
if coordinates(int(slot)).y != row:Why it works continue skips this loop pass when the active slot belongs to another row. A valid snack in row two cannot fill the top row quota.
-
Keep two separate totals
Find the two branches after reading item. Press Reset board, place Jam Toast into R1 C2 and press Check row totals. Compare matching snacks with the number of empty spaces in row one.
return Vector2i(matching, empty)Why it works The exact quota needs both the snacks already placed and the possible places left to put another one.
-
Spot an impossible shortage
Reset. Place Lemon Fizz at R1 C1 and Moon Milk at R1 C2. Check the row before choosing the final product.
if totals.x > target or totals.x + totals.y < target:Why it works With zero snacks and one space left, even filling every empty space with a snack can only reach one.
-
Repair the shortage
Replace Moon Milk at R1 C2 with Jam Toast and put Comet Crisps at R1 C3. Read the count again.
var target := int(quota["count"])Why it works Matching two and with zero spaces left meets the exact quota. Other parts of the brief may still need work.
-
Test the other direction
In a copy of the data change the first target from two snacks to one. Run with Jam Toast and Comet Crisps both in the first row. Check which side of the or expression becomes true.
Why it works Both above target and impossible-to-reach target are warnings. Equal matching can still be acceptable before the board is full.
Watch the values change
-
Put Jam Toast in row two Row one has zero snacks and three empty positions.
What you see. The row-one count stays at zero. -
Put Lemon Fizz and Moon Milk on row one The row has zero snacks and only one place left.
What you see. The exact two-snack quota is already impossible. -
Put Jam Toast and Comet Crisps beside Lemon Fizz There are two snacks and zero empties in row one.
What you see. The target is met exactly.
Predict before you run If the top row has one snack and two empty spaces, must it already show a warning?
Reveal the answer
No. Place one more snack and one product from another category to make a valid row of three.
Complete checkpoint
Check row totals reports an impossible shortage when two non-snacks fill the three active top-row positions.
main.gd
extends Control
const Shelf = preload("res://shelf_rules.gd")
const UNIT_TITLE := "Count a category across one row"
const INTRO := "Count how many products of a category a row contains."
const BOARD_BG := Color("#1b3142")
const PAPER := Color("#f6ecdb")
const TINT := Color("#71bdd0")
const TOP := Vector2(45, 207)
const STEP := Vector2(122, 59)
var brief: Dictionary
var board: Array
var chosen := "lemon_fizz"
var last_slot := -1
var tile_buttons: Array[Button] = []
var stock_buttons := {}
var detail_label: Label
var output_label: Label
var count_label: Label
var left_caption: Label
func _ready() -> void:
brief = Shelf.load_brief()
board = Shelf.blank_board()
make_label("TINY SHELF STUDIO / LESSON 24", Rect2(45, 24, 590, 23), 14, TINT)
make_label(UNIT_TITLE, Rect2(45, 55, 855, 45), 32)
make_label(INTRO, Rect2(45, 107, 870, 47), 16, Color("#bbcdd2"), true)
left_caption = make_label("01 • DISPLAY GRID", Rect2(45, 163, 480, 29), 16)
make_label("02 • MINI PRODUCT STOCK", Rect2(578, 163, 336, 29), 16)
detail_label = make_label("", Rect2(580, 369, 335, 47), 15, TINT, true)
output_label = make_label("", Rect2(65, 480, 824, 43), 17, PAPER, true)
count_label = make_label("", Rect2(45, 388, 495, 30), 16, TINT)
if brief.is_empty():
output_label.text = "The brief file is missing or invalid. Repair the JSON and run again."
return
build_display()
refresh()
output_label.text = "%s | Choose a product and click an open shelf space." % brief["title"]
func build_display() -> void:
for slot in range(Shelf.CAPACITY):
var cell := Shelf.coordinates(slot)
var box := Rect2(TOP + Vector2(cell) * STEP, Vector2(111, 48))
var button := make_button("", box, choose_slot.bind(slot))
button.disabled = not brief["active"].has(slot)
tile_buttons.append(button)
var index := 0
for item in brief["stock"]:
@warning_ignore("integer_division")
var position := Vector2(578 + (index % 2) * 177, 207 + (index / 2) * 51)
var button := make_button("", Rect2(position, Vector2(165, 43)), choose_product.bind(item))
stock_buttons[item] = button
index += 1
make_button("Empty hand", Rect2(578, 432, 165, 35), choose_product.bind(""))
make_button("Reset board", Rect2(755, 432, 165, 35), reset_board)
make_button("Check row totals", Rect2(45, 432, 245, 35), run_task)
func describe_slot(slot: int) -> String:
var cell := Shelf.coordinates(slot)
return "R%d C%d" % [cell.y + 1, cell.x + 1]
func choose_slot(slot: int) -> void:
var trial := Shelf.copy_for_placement(brief, board, slot, chosen)
if trial.is_empty():
output_label.text = "That shelf space or stock is unavailable. The display stayed the same."
return
board = trial
last_slot = slot
refresh()
output_label.text = "%s / %s" % [describe_slot(slot), Shelf.display_name(chosen)]
func choose_product(item: String) -> void:
chosen = item
refresh()
output_label.text = "Held product / %s" % Shelf.display_name(chosen)
func reset_board() -> void:
board = Shelf.blank_board()
last_slot = -1
refresh()
output_label.text = "Fresh display. Stock returned."
func refresh() -> void:
left_caption.text = "01 • DISPLAY GRID / %s" % brief["title"]
var placed := 0
for slot in range(tile_buttons.size()):
var button: Button = tile_buttons[slot]
var product: String = board[slot]
if button.disabled:
button.text = "—"
elif product.is_empty():
button.text = describe_slot(slot)
button.add_theme_color_override("font_color", Color("#a9c7d3"))
else:
var data: Array = Shelf.PRODUCTS[product]
button.text = "%s • %s" % [data[3], describe_slot(slot)]
button.add_theme_color_override("font_color", Color(data[2]))
placed += 1
if slot == last_slot and not button.disabled:
button.add_theme_color_override("font_hover_color", Color("#fae8a4"))
for item in stock_buttons:
var button: Button = stock_buttons[item]
var data: Array = Shelf.PRODUCTS[item]
var left := int(brief["stock"][item]) - board.count(item)
button.text = "%s%s ×%d" % ["› " if item == chosen else "", data[0], left]
button.add_theme_color_override("font_color", Color(data[2]))
detail_label.text = "In hand / %s" % Shelf.display_name(chosen)
count_label.text = "%d of %d display slots filled" % [placed, brief["active"].size()]
func run_task() -> void:
var totals := Shelf.row_totals(brief, board, 0, "snacks")
var issue := Shelf.quota_issue(brief, board)
output_label.text = "Row 1 / %d snacks / %d open." % [totals.x, totals.y] if issue.is_empty() else issue
func make_label(value: String, box: Rect2, points: int, ink: Color = PAPER, wraps: bool = false) -> Label:
var label := Label.new()
label.text = value
label.position = box.position
label.size = box.size
label.add_theme_font_size_override("font_size", points)
label.add_theme_color_override("font_color", ink)
if wraps:
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
add_child(label)
return label
func make_button(value: String, box: Rect2, action: Callable) -> Button:
var button := Button.new()
button.text = value
button.position = box.position
button.size = box.size
button.add_theme_font_size_override("font_size", 14)
button.add_theme_color_override("font_color", PAPER)
button.add_theme_color_override("font_disabled_color", Color("#6f8a9b"))
for mode in ["normal", "hover", "pressed", "disabled", "focus"]:
var panel := StyleBoxFlat.new()
panel.bg_color = Color("#233e52") if mode == "normal" else Color("#30526a")
if mode == "disabled":
panel.bg_color = Color("#1e3549")
panel.border_color = Color("#72b2c5") if mode == "focus" else Color("#42677e")
panel.set_border_width_all(1)
panel.set_corner_radius_all(7)
button.add_theme_stylebox_override(mode, panel)
button.pressed.connect(action)
add_child(button)
return button
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color("#132735"))
draw_rect(Rect2(30, 150, 517, 323), BOARD_BG)
draw_rect(Rect2(562, 150, 370, 323), BOARD_BG)
draw_rect(Rect2(45, 480, 870, 43), Color("#204452"))
draw_rect(Rect2(45, 480, 4, 43), TINT)
draw_line(Vector2(45, 144), Vector2(915, 144), Color("#436173"), 1.0)
shelf_rules.gd
extends RefCounted
const WIDTH := 4
const HEIGHT := 3
const CAPACITY := WIDTH * HEIGHT
const STOCK_PATH := "res://morning_window.json"
const PRODUCTS := {
"lemon_fizz": ["Lemon Fizz", "drinks", "#f4be5b", "FIZZ"],
"moon_milk": ["Moon Milk", "drinks", "#7993f0", "MOON"],
"jam_toast": ["Jam Toast", "snacks", "#e5829b", "JAM"],
"comet_crisps": ["Comet Crisps", "snacks", "#ec985e", "COMET"],
"rainbow_soap": ["Rainbow Soap", "care", "#72c3be", "SOAP"],
"mint_paste": ["Mint Paste", "care", "#a7d8a4", "MINT"],
}
static func coordinates(slot: int) -> Vector2i:
@warning_ignore("integer_division")
return Vector2i(slot % WIDTH, slot / WIDTH)
static func slot_index(cell: Vector2i) -> int:
return cell.y * WIDTH + cell.x
static func blank_board() -> Array:
var board: Array = []
board.resize(CAPACITY)
board.fill("")
return board
static func copy_for_placement(brief: Dictionary, board: Array, slot: int, item: String) -> Array:
if slot < 0 or slot >= CAPACITY or not brief["active"].has(slot):
return []
if not item.is_empty():
var total := int(brief["stock"].get(item, 0))
var used := board.count(item)
if board[slot] == item:
used -= 1
if used >= total:
return []
var next := board.duplicate()
next[slot] = item
return next
static func display_name(item: String) -> String:
return "Empty" if item.is_empty() else PRODUCTS[item][0]
static func is_integer(value: Variant) -> bool:
return (value is int or value is float) and int(value) == value
static func load_brief(path: String = STOCK_PATH) -> Dictionary:
var file := FileAccess.open(path, FileAccess.READ)
if file == null:
return {}
var parsed: Variant = JSON.parse_string(file.get_as_text())
if not parsed is Dictionary or not parsed.get("title") is String:
return {}
if not parsed.get("active") is Array or not parsed.get("stock") is Dictionary:
return {}
for key in ["fixed", "rows", "pairs"]:
if not parsed.get(key) is Array:
return {}
var active: Array[int] = []
for value in parsed["active"]:
if not is_integer(value) or value < 0 or value >= CAPACITY or active.has(int(value)):
return {}
active.append(int(value))
if active.is_empty():
return {}
parsed["active"] = active
var inventory := 0
for item in parsed["stock"]:
var count: Variant = parsed["stock"][item]
if not PRODUCTS.has(item) or not is_integer(count) or count < 1:
return {}
inventory += int(count)
if inventory < active.size():
return {}
for rule in parsed["fixed"]:
if not rule is Dictionary or not is_integer(rule.get("slot")):
return {}
if not active.has(int(rule["slot"])) or not parsed["stock"].has(rule.get("product")):
return {}
for rule in parsed["rows"]:
if not rule is Dictionary or not is_integer(rule.get("row")) or not is_integer(rule.get("count")):
return {}
if rule["row"] < 0 or rule["row"] >= HEIGHT or rule["count"] < 0 or rule["count"] > WIDTH:
return {}
if not ["drinks", "snacks", "care"].has(rule.get("category")):
return {}
for rule in parsed["pairs"]:
if not rule is Dictionary or not parsed["stock"].has(rule.get("left")) or not parsed["stock"].has(rule.get("right")):
return {}
if rule["left"] == rule["right"]:
return {}
return parsed
static func empty_count(brief: Dictionary, board: Array) -> int:
var empty := 0
for slot in brief["active"]:
if board[int(slot)] == "":
empty += 1
return empty
static func fixed_issue(brief: Dictionary, board: Array) -> String:
for lock in brief["fixed"]:
var slot := int(lock["slot"])
var item: String = board[slot]
if not item.is_empty() and item != lock["product"]:
return "%s needs %s." % [slot_name(slot), display_name(lock["product"])]
return ""
static func slot_name(slot: int) -> String:
var cell := coordinates(slot)
return "R%d C%d" % [cell.y + 1, cell.x + 1]
static func row_totals(brief: Dictionary, board: Array, row: int, category: String) -> Vector2i:
var matching := 0
var empty := 0
for slot in brief["active"]:
if coordinates(int(slot)).y != row:
continue
var item: String = board[int(slot)]
if item.is_empty():
empty += 1
elif PRODUCTS[item][1] == category:
matching += 1
return Vector2i(matching, empty)
static func quota_issue(brief: Dictionary, board: Array) -> String:
for quota in brief["rows"]:
var row := int(quota["row"])
var target := int(quota["count"])
var totals := row_totals(brief, board, row, quota["category"])
if totals.x > target or totals.x + totals.y < target:
return "Row %d needs exactly %d %s." % [row + 1, target, quota["category"]]
return ""
morning_window.json
{
"id": "morning_window",
"title": "Morning Window",
"chapter": "The Miniature Display",
"active": [
0,
1,
2,
4,
5,
6
],
"stock": {
"lemon_fizz": 1,
"moon_milk": 1,
"jam_toast": 1,
"comet_crisps": 1,
"rainbow_soap": 1,
"mint_paste": 1
},
"fixed": [
{
"slot": 0,
"product": "lemon_fizz"
}
],
"rows": [
{
"row": 0,
"category": "snacks",
"count": 2
},
{
"row": 1,
"category": "care",
"count": 2
}
],
"pairs": [
{
"left": "moon_milk",
"right": "rainbow_soap"
}
]
}
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 that can hold the labels, stock controls and clickable board. -
const Shelf = preload("res://shelf_rules.gd")Load the shelf-rule script to make its static functions available without placing a second screen in the scene. -
const UNIT_TITLE := "Count a category across one row"Creates a constant named UNIT_TITLE. The expression uses the text inside the quotes. Godot infers the type from the first value. -
const INTRO := "Count how many products of a category a row contains."Creates a constant named INTRO. The expression uses the text inside the quotes. Godot infers the type from the first value. -
const BOARD_BG := Color("#1b3142")Creates a constant named BOARD_BG. The expression builds a colour from these values. Godot infers the type from the first value. -
const PAPER := Color("#f6ecdb")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value. -
const TINT := Color("#71bdd0")Creates a constant named TINT. The expression builds a colour from these values. Godot infers the type from the first value. -
const TOP := Vector2(45, 207)Creates a constant named TOP. The expression packs x and y into one value. Godot infers the type from the first value. -
const STEP := Vector2(122, 59)Creates a constant named STEP. The expression packs x and y into one value. Godot infers the type from the first value. -
var brief: DictionaryKeep the design rules and stock for this attempt. The board can change while this dictionary stays the same. -
var board: ArrayStore exactly one product ID or empty string for each shelf position. -
var chosen := "lemon_fizz"Hold the selected stock ID. The player chooses a position separately. -
var last_slot := -1Remember the last position visited so the view can give local feedback. -
var tile_buttons: Array[Button] = []Hold references to the twelve visible slots in array order. -
var stock_buttons := {}Match each available product ID to its button. -
var detail_label: LabelDeclares detail_label for later use. A colon followed by a type says which kind of value belongs here. -
var output_label: LabelDeclares output_label for later use. A colon followed by a type says which kind of value belongs here. -
var count_label: LabelDeclares count_label for later use. A colon followed by a type says which kind of value belongs here. -
var left_caption: LabelDeclares left_caption for later use. A colon followed by a type says which kind of value belongs here. -
func _ready() -> void:Build the user interface when Godot has added this Control node to its scene tree. -
brief = Shelf.load_brief()Get a validated client card before using any of its stored fields. -
board = Shelf.blank_board()Make a clean array of twelve shelf positions before drawing the display. -
make_label("TINY SHELF STUDIO / LESSON 24", Rect2(45, 24, 590, 23), 14, TINT)Calls make_label with the values in its parentheses. -
make_label(UNIT_TITLE, Rect2(45, 55, 855, 45), 32)Calls make_label with the values in its parentheses. -
make_label(INTRO, Rect2(45, 107, 870, 47), 16, Color("#bbcdd2"), true)Calls make_label with the values in its parentheses. -
left_caption = make_label("01 • DISPLAY GRID", Rect2(45, 163, 480, 29), 16)Stores the new value in left_caption. The expression calls make_label with the values in its parentheses. -
make_label("02 • MINI PRODUCT STOCK", Rect2(578, 163, 336, 29), 16)Calls make_label with the values in its parentheses. -
detail_label = make_label("", Rect2(580, 369, 335, 47), 15, TINT, true)Stores the new value in detail_label. The expression calls make_label with the values in its parentheses. -
output_label = make_label("", Rect2(65, 480, 824, 43), 17, PAPER, true)Stores the new value in output_label. The expression calls make_label with the values in its parentheses. -
count_label = make_label("", Rect2(45, 388, 495, 30), 16, TINT)Stores the new value in count_label. The expression calls make_label with the values in its parentheses. -
if brief.is_empty():Explain the data problem and return before trying to act on an invalid shelf plan. -
output_label.text = "The brief file is missing or invalid. Repair the JSON and run again."Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
build_display()Calls build_display with the values in its parentheses. -
refresh()Calls refresh with the values in its parentheses. -
output_label.text = "%s | Choose a product and click an open shelf space." % brief["title"]Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
func build_display() -> void:Create all twelve tiles, then attach stock and teaching controls. -
for slot in range(Shelf.CAPACITY):Make one button per position. range stops before capacity, so the final index is 11. -
var cell := Shelf.coordinates(slot)Convert the flat slot number into grid coordinates for the screen layout. -
var box := Rect2(TOP + Vector2(cell) * STEP, Vector2(111, 48))Multiply the cell by the display spacing to give the button a visible rectangle. -
var button := make_button("", box, choose_slot.bind(slot))Make a clickable shelf or stock control and give it the bound argument it will use on a later press. -
button.disabled = not brief["active"].has(slot)Show inactive shelf spaces while preventing them from receiving a player placement. -
tile_buttons.append(button)Adds an item to the end of a list. -
var index := 0Creates a variable named index. The expression uses the whole number 0. Godot infers the type from the first value. -
for item in brief["stock"]:Add a button for each product the current card supplies. -
@warning_ignore("integer_division")This annotation gives Godot extra information about the declaration that follows. -
var position := Vector2(578 + (index % 2) * 177, 207 + (index / 2) * 51)Creates a variable named position. The expression packs x and y into one value. Godot infers the type from the first value. -
var button := make_button("", Rect2(position, Vector2(165, 43)), choose_product.bind(item))Make a clickable shelf or stock control and give it the bound argument it will use on a later press. -
stock_buttons[item] = buttonStores the new value in stock_buttons[item]. The expression reads button. -
index += 1Reads index, adds to its old value, then stores the result back in the same place. -
make_button("Empty hand", Rect2(578, 432, 165, 35), choose_product.bind(""))Calls make_button with the values in its parentheses. -
make_button("Reset board", Rect2(755, 432, 165, 35), reset_board)Calls make_button with the values in its parentheses. -
make_button("Check row totals", Rect2(45, 432, 245, 35), run_task)Calls make_button with the values in its parentheses. -
func describe_slot(slot: int) -> String:Defines describe slot, 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 cell := Shelf.coordinates(slot)Convert the flat slot number into grid coordinates for the screen layout. -
return "R%d C%d" % [cell.y + 1, cell.x + 1]Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes. -
func choose_slot(slot: int) -> void:Send a player placement through the same stock and slot guards every time. -
var trial := Shelf.copy_for_placement(brief, board, slot, chosen)Request a candidate board without mutating the currently displayed array. -
if trial.is_empty():The action was refused. Show the reason and leave the actual grid alone. -
output_label.text = "That shelf space or stock is unavailable. The display stayed the same."Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
board = trialReplace the live array only after the new placement passed its guards. -
last_slot = slotStores the new value in last_slot. The expression reads slot. -
refresh()Calls refresh with the values in its parentheses. -
output_label.text = "%s / %s" % [describe_slot(slot), Shelf.display_name(chosen)]Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
func choose_product(item: String) -> void:Change what the player is holding. The selection does not fill a shelf position. -
chosen = itemStores the new value in chosen. The expression reads item. -
refresh()Calls refresh with the values in its parentheses. -
output_label.text = "Held product / %s" % Shelf.display_name(chosen)Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
func reset_board() -> void:Clear the arrangement and reread available stock from the same brief. -
board = Shelf.blank_board()Make a clean array of twelve shelf positions before drawing the display. -
last_slot = -1Stores the new value in last_slot. The expression reads -1. -
refresh()Calls refresh with the values in its parentheses. -
output_label.text = "Fresh display. Stock returned."Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
func refresh() -> void:Read the current game values and update the text and styling. -
left_caption.text = "01 • DISPLAY GRID / %s" % brief["title"]Updates left_caption.text, which controls the words a player sees. The expression uses the text inside the quotes. -
var placed := 0Creates a variable named placed. The expression uses the whole number 0. Godot infers the type from the first value. -
for slot in range(tile_buttons.size()):Visit every visible slot to redraw its label from the current array value. -
var button: Button = tile_buttons[slot]Creates a variable named button. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold. -
var product: String = board[slot]Creates a variable named product. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold. -
if button.disabled:Checks button.disabled. The indented instructions below run only if this test passes. -
button.text = "—"Updates button.text, which controls the words a player sees. The expression uses the text inside the quotes. -
elif product.is_empty():If the earlier branches did not run, checks product.is_empty() next. -
button.text = describe_slot(slot)Updates button.text, which controls the words a player sees. The expression calls describe_slot with the values in its parentheses. -
button.add_theme_color_override("font_color", Color("#a9c7d3"))Calls button.add_theme_color_override with the values in its parentheses. -
else:Runs the indented fallback instructions if none of the earlier tests passed. -
var data: Array = Shelf.PRODUCTS[product]Read the original packet's short label and colour from the catalogue. -
button.text = "%s • %s" % [data[3], describe_slot(slot)]Updates button.text, which controls the words a player sees. The expression uses the text inside the quotes. -
button.add_theme_color_override("font_color", Color(data[2]))Calls button.add_theme_color_override with the values in its parentheses. -
placed += 1Reads placed, adds to its old value, then stores the result back in the same place. -
if slot == last_slot and not button.disabled:Checks slot == last_slot and not button.disabled. The indented instructions below run only if this test passes. -
button.add_theme_color_override("font_hover_color", Color("#fae8a4"))Calls button.add_theme_color_override with the values in its parentheses. -
for item in stock_buttons:Repeats the indented instructions for each value in stock_buttons. -
var button: Button = stock_buttons[item]Creates a variable named button. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold. -
var data: Array = Shelf.PRODUCTS[item]Creates a variable named data. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold. -
var left := int(brief["stock"][item]) - board.count(item)Subtract displayed copies from the brief allowance to show how many remain. -
button.text = "%s%s ×%d" % ["› " if item == chosen else "", data[0], left]Updates button.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle. -
button.add_theme_color_override("font_color", Color(data[2]))Calls button.add_theme_color_override with the values in its parentheses. -
detail_label.text = "In hand / %s" % Shelf.display_name(chosen)Updates detail_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
count_label.text = "%d of %d display slots filled" % [placed, brief["active"].size()]Updates count_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
func run_task() -> void:Run this lesson’s checking action and show the result before editing the layout again. -
var totals := Shelf.row_totals(brief, board, 0, "snacks")Creates a variable named totals. The expression calls Shelf.row_totals with the values in its parentheses. Godot infers the type from the first value. -
var issue := Shelf.quota_issue(brief, board)Creates a variable named issue. The expression calls Shelf.quota_issue with the values in its parentheses. Godot infers the type from the first value. -
output_label.text = "Row 1 / %d snacks / %d open." % [totals.x, totals.y] if issue.is_empty() else issueUpdates output_label.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle. -
func make_label(value: String, box: Rect2, points: int, ink: Color = PAPER, wraps: bool = false) -> Label:Build consistent headings, caption text and feedback from one helper. -
var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value. -
label.text = valueUpdates label.text, which controls the words a player sees. The expression reads value. -
label.position = box.positionUpdates label.position, which controls the node's local x and y location. The expression reads box.position. -
label.size = box.sizeUpdates label.size, which controls the control's width and height. The expression reads box.size. -
label.add_theme_font_size_override("font_size", points)Calls label.add_theme_font_size_override with the values in its parentheses. -
label.add_theme_color_override("font_color", ink)Calls label.add_theme_color_override with the values in its parentheses. -
if wraps:Checks wraps. The indented instructions below run only if this test passes. -
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow the sentence to wrap within the area reserved for it. -
add_child(label)Adds the new node to the scene tree so that Godot can run and draw it. -
return labelFinishes the function and hands its result back to the caller. The expression reads label. -
func make_button(value: String, box: Rect2, action: Callable) -> Button:Make controls with consistent style and room to select them. -
var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value. -
button.text = valueUpdates button.text, which controls the words a player sees. The expression reads value. -
button.position = box.positionUpdates button.position, which controls the node's local x and y location. The expression reads box.position. -
button.size = box.sizeUpdates button.size, which controls the control's width and height. The expression reads box.size. -
button.add_theme_font_size_override("font_size", 14)Calls button.add_theme_font_size_override with the values in its parentheses. -
button.add_theme_color_override("font_color", PAPER)Calls button.add_theme_color_override with the values in its parentheses. -
button.add_theme_color_override("font_disabled_color", Color("#6f8a9b"))Calls button.add_theme_color_override with the values in its parentheses. -
for mode in ["normal", "hover", "pressed", "disabled", "focus"]:Repeats the indented instructions for each value in ["normal", "hover", "pressed", "disabled", "focus"]. -
var panel := StyleBoxFlat.new()Creates a variable named panel. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value. -
panel.bg_color = Color("#233e52") if mode == "normal" else Color("#30526a")Stores the new value in panel.bg_color. The expression builds a colour from these values. -
if mode == "disabled":Checks mode == "disabled". The indented instructions below run only if this test passes. -
panel.bg_color = Color("#1e3549")Stores the new value in panel.bg_color. The expression builds a colour from these values. -
panel.border_color = Color("#72b2c5") if mode == "focus" else Color("#42677e")Stores the new value in panel.border_color. The expression builds a colour from these values. -
panel.set_border_width_all(1)Calls panel.set_border_width_all with the values in its parentheses. -
panel.set_corner_radius_all(7)Calls panel.set_corner_radius_all with the values in its parentheses. -
button.add_theme_stylebox_override(mode, panel)Calls button.add_theme_stylebox_override with the values in its parentheses. -
button.pressed.connect(action)Route the button's signal to the action supplied when it was created. -
add_child(button)Adds the new node to the scene tree so that Godot can run and draw it. -
return buttonFinishes the function and hands its result back to the caller. The expression reads button. -
func _draw() -> void:Paint the lesson background and display panels without changing the game. -
draw_rect(Rect2(Vector2.ZERO, size), Color("#132735"))Paints a rectangle at the given position and size. -
draw_rect(Rect2(30, 150, 517, 323), BOARD_BG)Paints a rectangle at the given position and size. -
draw_rect(Rect2(562, 150, 370, 323), BOARD_BG)Paints a rectangle at the given position and size. -
draw_rect(Rect2(45, 480, 870, 43), Color("#204452"))Paints a rectangle at the given position and size. -
draw_rect(Rect2(45, 480, 4, 43), TINT)Paints a rectangle at the given position and size. -
draw_line(Vector2(45, 144), Vector2(915, 144), Color("#436173"), 1.0)Paints a line between two points with the chosen colour and width.
Read shelf_rules.gd line by line
-
extends RefCountedKeep the shelf rules independent from Godot buttons. The live scene, hint and test tray can all call this script. -
const WIDTH := 4Define four columns in each practice shelf row. -
const HEIGHT := 3Define three rows of practice shelf space. -
const CAPACITY := WIDTH * HEIGHTMultiply the dimensions to reserve all twelve array entries, including slots closed by a brief. -
const STOCK_PATH := "res://morning_window.json"This res:// path points to the default client card inside the extracted Godot checkpoint. -
const PRODUCTS := {Use original miniature IDs as keys. Each product holds a label, category, drawing colour and short tag. -
"lemon_fizz": ["Lemon Fizz", "drinks", "#f4be5b", "FIZZ"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"moon_milk": ["Moon Milk", "drinks", "#7993f0", "MOON"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"jam_toast": ["Jam Toast", "snacks", "#e5829b", "JAM"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"comet_crisps": ["Comet Crisps", "snacks", "#ec985e", "COMET"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"rainbow_soap": ["Rainbow Soap", "care", "#72c3be", "SOAP"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"mint_paste": ["Mint Paste", "care", "#a7d8a4", "MINT"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
}Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
static func coordinates(slot: int) -> Vector2i:Convert the index in the board array into its across-and-down position. -
@warning_ignore("integer_division")The division warning acknowledges that whole-number division is intentional. Here the fraction is discarded because the result is a row index. -
return Vector2i(slot % WIDTH, slot / WIDTH)The remainder gives the column. Whole-number division by four counts the complete rows that come before the slot. -
static func slot_index(cell: Vector2i) -> int:Turn the two coordinates back into the flat index used by the board array. -
return cell.y * WIDTH + cell.xCount every space in full rows above the cell, then add the number of spaces before it in its own row. -
static func blank_board() -> Array:Return a fresh board on start, restart or a brief audit. It begins without products. -
var board: Array = []Start with an empty dynamic collection for the game state. -
board.resize(CAPACITY)Reserve a value for every possible shelf slot before the drawing code indexes it. -
board.fill("")Replace each default null value with the empty string that illustrates an unfilled shelf space. -
return boardFinishes the function and hands its result back to the caller. The expression reads board. -
static func copy_for_placement(brief: Dictionary, board: Array, slot: int, item: String) -> Array:Calculate an independent result for the attempted click. A rejected action returns an empty array. -
if slot < 0 or slot >= CAPACITY or not brief["active"].has(slot):Reject positions outside the 4 × 3 board or marked unavailable by this brief before looking at their contents. -
return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order. -
if not item.is_empty():An empty hand clears a slot without asking for stock. A held product must pass the count guard. -
var total := int(brief["stock"].get(item, 0))Read the total stock for this miniature. The default zero rejects an ID that this brief cannot supply. -
var used := board.count(item)Count the number of that miniature already on display, including repeated products when the card supplies copies. -
if board[slot] == item:Putting the same miniature in its own square reuses the one already there instead of spending another. -
used -= 1Reads used, subtracts from its old value, then stores the result back in the same place. -
if used >= total:Only accept an addition when at least one copy remains available after the same-position adjustment. -
return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order. -
var next := board.duplicate()Copy the flat array. A player click may update the new board after the guard finishes. -
next[slot] = itemSet just one position of the copy to the currently selected product ID or the empty string. -
return nextFinishes the function and hands its result back to the caller. The expression reads next. -
static func display_name(item: String) -> String:Give the UI the longer label for an ID and the friendly name Empty for the empty hand. -
return "Empty" if item.is_empty() else PRODUCTS[item][0]Finishes the function and hands its result back to the caller. The expression chooses one of two values by checking the condition in the middle. -
static func is_integer(value: Variant) -> bool:Test whole-number shape for JSON numbers. A position such as 4.5 cannot index the shelf. -
return (value is int or value is float) and int(value) == valueTest the type before converting to int. This accepts exact values such as 4 or 4.0 while rejecting text and fractions. -
static func load_brief(path: String = STOCK_PATH) -> Dictionary:Read a client brief from the supplied path or use the default Morning Window file. -
var file := FileAccess.open(path, FileAccess.READ)Ask Godot to read project text. The controller does not write to this client brief. -
if file == null:Handle a missing or unreadable file before asking it for text. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
var parsed: Variant = JSON.parse_string(file.get_as_text())Let the parser return any JSON shape. Only use it as a brief after checking the expected structure. -
if not parsed is Dictionary or not parsed.get("title") is String:A top-level array or a dictionary with no text title cannot describe this display. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
if not parsed.get("active") is Array or not parsed.get("stock") is Dictionary:Check the collection types before walking active positions or counting stock. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
for key in ["fixed", "rows", "pairs"]:Each set of rules must have an array, even on a brief with no rules of that type. -
if not parsed.get(key) is Array:Checks not parsed.get(key) is Array. The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
var active: Array[int] = []Build a new typed list of validated shelf indices. -
for value in parsed["active"]:Review every active position supplied with the client card. -
if not is_integer(value) or value < 0 or value >= CAPACITY or active.has(int(value)):Reject fractions, repeated positions and positions outside the display. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
active.append(int(value))Keep the proven value as an int so later board lookups use the expected index type. -
if active.is_empty():Checks active.is_empty(). The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
parsed["active"] = activeReplace the raw JSON array with the clean array of indices. -
var inventory := 0Start a stock total for a simple early check of whether all active spaces could be filled. -
for item in parsed["stock"]:Read each key in the stock dictionary. The keys are product IDs. -
var count: Variant = parsed["stock"][item]Creates a variable named count. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold. -
if not PRODUCTS.has(item) or not is_integer(count) or count < 1:Require a known mini and a positive whole-number stock quantity. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
inventory += int(count)Add all copies of the current miniature to the count. -
if inventory < active.size():There must be enough stock to fill every open display space. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
for rule in parsed["fixed"]:Check that every fixed rule uses an open slot and a stocked product. -
if not rule is Dictionary or not is_integer(rule.get("slot")):Checks not rule is Dictionary or not is_integer(rule.get("slot")). The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
if not active.has(int(rule["slot"])) or not parsed["stock"].has(rule.get("product")):Checks not active.has(int(rule["slot"])) or not parsed["stock"].has(rule.get("product")). The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
for rule in parsed["rows"]:Check the row number, row target and known category before trying a constraint. -
if not rule is Dictionary or not is_integer(rule.get("row")) or not is_integer(rule.get("count")):Checks not rule is Dictionary or not is_integer(rule.get("row")) or not is_integer(rule.get("count")). The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
if rule["row"] < 0 or rule["row"] >= HEIGHT or rule["count"] < 0 or rule["count"] > WIDTH:Checks rule["row"] < 0 or rule["row"] >= HEIGHT or rule["count"] < 0 or rule["count"] > WIDTH. The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
if not ["drinks", "snacks", "care"].has(rule.get("category")):Checks not ["drinks", "snacks", "care"].has(rule.get("category")). The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
for rule in parsed["pairs"]:Both members of a pair must be stocked and refer to distinct product IDs. -
if not rule is Dictionary or not parsed["stock"].has(rule.get("left")) or not parsed["stock"].has(rule.get("right")):Checks not rule is Dictionary or not parsed["stock"].has(rule.get("left")) or not parsed["stock"].has(rule.get("right")). The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
if rule["left"] == rule["right"]:Checks rule["left"] == rule["right"]. The indented instructions below run only if this test passes. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
return parsedSupply a validated dictionary to the controller, checker or test audit. -
static func empty_count(brief: Dictionary, board: Array) -> int:Count gaps in the current attempt, using only the positions this brief opens. -
var empty := 0Track unused positions separately so a partial board can still meet a target. -
for slot in brief["active"]:Repeats the indented instructions for each value in brief["active"]. -
if board[int(slot)] == "":The empty string represents an open position into which a player has placed nothing. -
empty += 1Reads empty, adds to its old value, then stores the result back in the same place. -
return emptyFinishes the function and hands its result back to the caller. The expression reads empty. -
static func fixed_issue(brief: Dictionary, board: Array) -> String:Check anchored miniatures. An empty anchor can still be filled correctly. -
for lock in brief["fixed"]:Read each required slot and product using the same kind of rule. -
var slot := int(lock["slot"])Creates a variable named slot. The expression converts a suitable value to a whole number. Godot infers the type from the first value. -
var item: String = board[slot]Read the miniature ID from the live or simulated slot. -
if not item.is_empty() and item != lock["product"]:Flag an occupied anchor with a mismatched mini. Leave the decision open while the slot is empty. -
return "%s needs %s." % [slot_name(slot), display_name(lock["product"])]Give the player a location and the correct miniature when a fixed requirement has been missed. -
return ""Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes. -
static func slot_name(slot: int) -> String:Convert zero-based coordinates into the readable names R1 C1 and R2 C3. -
var cell := coordinates(slot)Creates a variable named cell. The expression calls coordinates with the values in its parentheses. Godot infers the type from the first value. -
return "R%d C%d" % [cell.y + 1, cell.x + 1]Add one to human-facing row and column values. Keep the original indices for code. -
static func row_totals(brief: Dictionary, board: Array, row: int, category: String) -> Vector2i:Count matching products and empty positions for a single row and category. -
var matching := 0Begin the category count at zero each time this function receives a board. -
var empty := 0Track unused positions separately so a partial board can still meet a target. -
for slot in brief["active"]:Repeats the indented instructions for each value in brief["active"]. -
if coordinates(int(slot)).y != row:Ignore positions whose coordinate y places them in another row. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
var item: String = board[int(slot)]Creates a variable named item. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold. -
if item.is_empty():Checks item.is_empty(). The indented instructions below run only if this test passes. -
empty += 1Reads empty, adds to its old value, then stores the result back in the same place. -
elif PRODUCTS[item][1] == category:Look up the catalogue category before counting an occupied position as a snack, drink or care item. -
matching += 1Reads matching, adds to its old value, then stores the result back in the same place. -
return Vector2i(matching, empty)Return the matching total and the empty total together so the next check can read both. -
static func quota_issue(brief: Dictionary, board: Array) -> String:Look for a row target that has been exceeded or cannot be reached with the positions left. -
for quota in brief["rows"]:Apply the same exact-count rule to every named category quota. -
var row := int(quota["row"])Creates a variable named row. The expression converts a suitable value to a whole number. Godot infers the type from the first value. -
var target := int(quota["count"])Creates a variable named target. The expression converts a suitable value to a whole number. Godot infers the type from the first value. -
var totals := row_totals(brief, board, row, quota["category"])Creates a variable named totals. The expression calls row_totals with the values in its parentheses. Godot infers the type from the first value. -
if totals.x > target or totals.x + totals.y < target:Reject too many matches, or a shortage too large for the empty slots to fix. -
return "Row %d needs exactly %d %s." % [row + 1, target, quota["category"]]Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes. -
return ""Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
morning_window.json holds data for the game. Curly braces group named values, square brackets make ordered lists and each colon connects a key to its value.
Find and fix a bug
If the number of snacks seems doubled, make sure matching starts at zero inside row_totals and increases once per matching slot.
Try a change
On paper design a new exact quota for a fully open third row. List one arrangement that passes and one that misses by one.