Tiny Shelf Studio · Lesson 22 of 50 · Intermediate · About 29 min
The studio keeps a stack of client cards. This lesson moves the first card into an editable data file so another maker can adjust a display without editing a button script.

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/21 when the lesson builds on prior work, or copy the checkpoints/22 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 JSON, FileAccess, Variant, res://, validation, integer conversion.
-
Compare the two views
Import this checkpoint. Open morning_window.json with a text editor and open shelf_rules.gd in Godot. Run and press Read the brief. Match its title, six active slots and six stock labels to the values in the file.
Why it works Keeping the same sample in the new format helps you spot mistakes when you separate the rules and data.
-
Open project data for reading
Read the first two lines of load_brief in shelf_rules.gd. Find the named resource path at the top of the file. Explain what will happen if you change it to an incorrect filename.
var file := FileAccess.open(path, FileAccess.READ)Why it works FileAccess asks for a reader. If the file cannot be opened, null lets the rule leave safely with an empty dictionary.
-
Turn text into typed game data
Find JSON.parse_string. Read what get_as_text supplies and why parsed uses the flexible Variant type. Check a real title or active value against the expected shape.
var parsed: Variant = JSON.parse_string(file.get_as_text())Why it works A parser can produce different kinds of values. Testing Dictionary, Array and String prevents accidental reads of the wrong kind.
-
Protect the grid indices
Walk the loop that checks each active index. A whole number between 0 and 11 is accepted once. Explain why 12 or a second copy of 6 causes an empty result.
active.append(int(value))Why it works The grid cannot address slot 12. A duplicate would create two rules for one button and make progress counts misleading.
-
Edit a safe field
Change the title string in morning_window.json to Morning Demo. Keep the quotes, save and rerun. Press Read the brief again.
Why it works The title and layout source can change while the drawn controls keep the same instructions.
-
Break and repair your copy
Remove the last closing brace, save and run. Read the status message. Put the brace back, save and rerun to check the board returns.
if brief.is_empty():Why it works The loader checks the parse result before reading the active array. The screen can explain the missing brief instead of attempting to build broken controls.
Watch the values change
-
Run the original file The JSON produces a dictionary with an active array and stock dictionary.
What you see. Morning Window displays six active positions. -
Change the title field One string becomes Morning Demo.
What you see. The layout stays the same and the display title changes. -
Remove the final brace The JSON text no longer describes a valid dictionary.
What you see. The studio shows its invalid-brief message.
Predict before you run Can JSON be valid text and still be wrong for this display?
Reveal the answer
Yes. For example, an active array containing 12 can be valid JSON syntax, but the validator rejects it because the last slot is 11.
Complete checkpoint
Morning Window loads from morning_window.json. A malformed file produces a clear error screen.
main.gd
extends Control
const Shelf = preload("res://shelf_rules.gd")
const UNIT_TITLE := "Load a display brief from JSON"
const INTRO := "Load a design brief from an editable data file."
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 22", 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("Read the brief", 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:
output_label.text = "%s / %d open slots / %d stock labels" % [brief["title"], brief["active"].size(), brief["stock"].size()]
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
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 := "Load a display brief from JSON"Creates a constant named UNIT_TITLE. The expression uses the text inside the quotes. Godot infers the type from the first value. -
const INTRO := "Load a design brief from an editable data file."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 22", 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("Read the brief", 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. -
output_label.text = "%s / %d open slots / %d stock labels" % [brief["title"], brief["active"].size(), brief["stock"].size()]Updates output_label.text, which controls the words a player sees. The expression uses the text inside the quotes. -
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.
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 screen says the brief is missing or invalid, first check the recent filename or punctuation edit. Then look for repeated slot numbers and catalogue IDs with a spelling mismatch.
Try a change
Change the single active value 6 to 11. Predict how the board changes. Keep the original brief on a spare copy for later quota experiments.