Tiny Shelf 27 · Search for a complete arrangement

Tiny Shelf Studio · Lesson 27 of 50 · Intermediate · About 34 min

Your friend asks whether the current arrangement can still be finished. The studio needs a way to try choices without moving the actual mini boxes on screen.

Tiny patterned boxes and bottles arranged for an exhibition on a miniature display stand.
What you’ll make Use recursive backtracking to try all valid continuations of a practice board until one complete arrangement passes.

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

Copy the board. Keep live slots untouched. → Check the branch. Discard a rule violation. → Try an item. Search from the new trial. → Undo or return. Restore the cell or keep a solution.
Copy the board → Check the branch → Try an item → Undo or return
Godot checkpoint window for Search for a complete arrangement
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson backtracking, recursion, working copy, pruning, base case, stock guard.

  1. Try the starting board

    In the running scene press Try a full arrangement with every active space clear. Read the completion result, then verify that each screen space remains blank.

    Why it works The solver answers a question about the current board. Only a player's placement updates the visible scene.

  2. Give the search a copy

    Find solve. Trace board.duplicate before search begins. Explain why copying the flat array copies all the information used in this version.

    var trial := board.duplicate()

    Why it works The board stores only product strings. Those strings are values, so a flat duplicate can safely hold the trial changes.

  3. Cut a branch early

    Read the first guard in search. Imagine Moon Milk placed at the fixed Lemon Fizz slot. There is no need to complete that branch before rejecting it.

    if not rule_issue(brief, trial).is_empty():

    Why it works Placing more things cannot fix an existing wrong anchor. Returning an empty result saves deeper work.

  4. Find the next empty slot

    Trace the loop over active positions. Mark each already-filled slot that is skipped. Read the stock check before a temporary mini is put in the first open slot.

    if trial.count(item) >= int(brief["stock"][item]):

    Why it works The search preserves your placed products, and the same mini cannot be used more times than the brief supplies.

  5. Try, recurse and undo

    On paper put Lemon Fizz in slot 0 of a trial. Follow the recursive call as it considers another open slot. Read the line immediately after the call.

    trial[slot] = ""

    Why it works If the deeper choices fail, clearing the trial position lets the loop try another product. This is backtracking.

  6. Recognise two stopping cases

    Find the success return after the outer loop and the empty return after all stock choices for one slot are tried. In the live board place Moon Milk at R2 C1 and Mint Paste at R2 C2. Try a full arrangement again.

    return trial.duplicate()

    Why it works If every slot is already filled, the branch has a solution. If no candidate works for an open slot, return failure so the caller can try another branch.

Watch the values change

  1. Empty display The solver uses a copied board and six available minis.
    What you see. It finds a completion and leaves the live board blank.
  2. Wrong product in slot 0 The first rule test sees a conflicting fixed spot.
    What you see. The whole branch fails before exploring later spaces.
  3. Moon Milk in R2 C1 and Mint Paste in R2 C2 No legal placement of Rainbow Soap can share an edge with Moon Milk while keeping the anchor and exact rows.
    What you see. There is no completion from those placements.

Predict before you run Why return a duplicate on success instead of returning the trial array itself?

Reveal the answer

Earlier recursive calls still unwind and clear temporary choices. The returned duplicate keeps the successful arrangement while the working array is cleaned up.

Complete checkpoint

Try a full arrangement finds a valid completion for a blank shelf and an impossible continuation for the trapped pair.

main.gd

extends Control

const Shelf = preload("res://shelf_rules.gd")
const UNIT_TITLE := "Search for a complete arrangement"
const INTRO := "Try arrangements on a working copy of the board."
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 27", 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("Try a full arrangement", 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 result := Shelf.solve(brief, board)
	output_label.text = "A completion exists. Your live display stayed the same." if not result.is_empty() else "No solution for this arrangement."


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 ""

static func neighbours(first: int, second: int) -> bool:
	var gap := coordinates(first) - coordinates(second)
	return absi(gap.x) + absi(gap.y) == 1


static func has_pair(brief: Dictionary, board: Array, first: String, second: String) -> bool:
	for left in brief["active"]:
		if board[int(left)] != first:
			continue
		for right in brief["active"]:
			if board[int(right)] == second and neighbours(int(left), int(right)):
				return true
	return false


static func pair_issue(brief: Dictionary, board: Array) -> String:
	for pair in brief["pairs"]:
		var first: String = pair["left"]
		var second: String = pair["right"]
		if has_pair(brief, board, first, second):
			continue
		var full := empty_count(brief, board) == 0
		var used_all := board.count(first) == int(brief["stock"][first]) and board.count(second) == int(brief["stock"][second])
		if full or used_all:
			return "%s and %s need a shared edge." % [display_name(first), display_name(second)]
	return ""

static func rule_issue(brief: Dictionary, board: Array) -> String:
	var issue := fixed_issue(brief, board)
	if issue.is_empty():
		issue = quota_issue(brief, board)
	if issue.is_empty():
		issue = pair_issue(brief, board)
	return issue


static func report(brief: Dictionary, board: Array) -> Dictionary:
	var issue := rule_issue(brief, board)
	if not issue.is_empty():
		return {"state": "revise", "message": issue}
	var remaining := empty_count(brief, board)
	if remaining > 0:
		return {"state": "open", "message": "Fits so far. Fill %d more display slots." % remaining}
	return {"state": "ready", "message": "Display ready. Every brief rule passes."}

static func solve(brief: Dictionary, board: Array) -> Array:
	var trial := board.duplicate()
	return search(brief, trial)


static func search(brief: Dictionary, trial: Array) -> Array:
	if not rule_issue(brief, trial).is_empty():
		return []
	for position in brief["active"]:
		var slot := int(position)
		if trial[slot] != "":
			continue
		for item in brief["stock"]:
			if trial.count(item) >= int(brief["stock"][item]):
				continue
			trial[slot] = item
			var result := search(brief, trial)
			trial[slot] = ""
			if not result.is_empty():
				return result
		return []
	return trial.duplicate()

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
  1. extends ControlUse a screen node that can hold the labels, stock controls and clickable board.
  2. 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.
  3. const UNIT_TITLE := "Search for a complete arrangement"Creates a constant named UNIT_TITLE. The expression uses the text inside the quotes. Godot infers the type from the first value.
  4. const INTRO := "Try arrangements on a working copy of the board."Creates a constant named INTRO. The expression uses the text inside the quotes. Godot infers the type from the first value.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. var brief: DictionaryKeep the design rules and stock for this attempt. The board can change while this dictionary stays the same.
  11. var board: ArrayStore exactly one product ID or empty string for each shelf position.
  12. var chosen := "lemon_fizz"Hold the selected stock ID. The player chooses a position separately.
  13. var last_slot := -1Remember the last position visited so the view can give local feedback.
  14. var tile_buttons: Array[Button] = []Hold references to the twelve visible slots in array order.
  15. var stock_buttons := {}Match each available product ID to its button.
  16. var detail_label: LabelDeclares detail_label for later use. A colon followed by a type says which kind of value belongs here.
  17. var output_label: LabelDeclares output_label for later use. A colon followed by a type says which kind of value belongs here.
  18. var count_label: LabelDeclares count_label for later use. A colon followed by a type says which kind of value belongs here.
  19. var left_caption: LabelDeclares left_caption for later use. A colon followed by a type says which kind of value belongs here.
  20. func _ready() -> void:Build the user interface when Godot has added this Control node to its scene tree.
  21. brief = Shelf.load_brief()Get a validated client card before using any of its stored fields.
  22. board = Shelf.blank_board()Make a clean array of twelve shelf positions before drawing the display.
  23. make_label("TINY SHELF STUDIO / LESSON 27", Rect2(45, 24, 590, 23), 14, TINT)Calls make_label with the values in its parentheses.
  24. make_label(UNIT_TITLE, Rect2(45, 55, 855, 45), 32)Calls make_label with the values in its parentheses.
  25. make_label(INTRO, Rect2(45, 107, 870, 47), 16, Color("#bbcdd2"), true)Calls make_label with the values in its parentheses.
  26. 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.
  27. make_label("02 • MINI PRODUCT STOCK", Rect2(578, 163, 336, 29), 16)Calls make_label with the values in its parentheses.
  28. 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.
  29. 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.
  30. 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.
  31. if brief.is_empty():Explain the data problem and return before trying to act on an invalid shelf plan.
  32. 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.
  33. returnFinishes the function right here. Any later instructions in this function are skipped.
  34. build_display()Calls build_display with the values in its parentheses.
  35. refresh()Calls refresh with the values in its parentheses.
  36. 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.
  37. func build_display() -> void:Create all twelve tiles, then attach stock and teaching controls.
  38. for slot in range(Shelf.CAPACITY):Make one button per position. range stops before capacity, so the final index is 11.
  39. var cell := Shelf.coordinates(slot)Convert the flat slot number into grid coordinates for the screen layout.
  40. var box := Rect2(TOP + Vector2(cell) * STEP, Vector2(111, 48))Multiply the cell by the display spacing to give the button a visible rectangle.
  41. 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.
  42. button.disabled = not brief["active"].has(slot)Show inactive shelf spaces while preventing them from receiving a player placement.
  43. tile_buttons.append(button)Adds an item to the end of a list.
  44. var index := 0Creates a variable named index. The expression uses the whole number 0. Godot infers the type from the first value.
  45. for item in brief["stock"]:Add a button for each product the current card supplies.
  46. @warning_ignore("integer_division")This annotation gives Godot extra information about the declaration that follows.
  47. 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.
  48. 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.
  49. stock_buttons[item] = buttonStores the new value in stock_buttons[item]. The expression reads button.
  50. index += 1Reads index, adds to its old value, then stores the result back in the same place.
  51. make_button("Empty hand", Rect2(578, 432, 165, 35), choose_product.bind(""))Calls make_button with the values in its parentheses.
  52. make_button("Reset board", Rect2(755, 432, 165, 35), reset_board)Calls make_button with the values in its parentheses.
  53. make_button("Try a full arrangement", Rect2(45, 432, 245, 35), run_task)Calls make_button with the values in its parentheses.
  54. 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.
  55. var cell := Shelf.coordinates(slot)Convert the flat slot number into grid coordinates for the screen layout.
  56. 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.
  57. func choose_slot(slot: int) -> void:Send a player placement through the same stock and slot guards every time.
  58. var trial := Shelf.copy_for_placement(brief, board, slot, chosen)Request a candidate board without mutating the currently displayed array.
  59. if trial.is_empty():The action was refused. Show the reason and leave the actual grid alone.
  60. 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.
  61. returnFinishes the function right here. Any later instructions in this function are skipped.
  62. board = trialReplace the live array only after the new placement passed its guards.
  63. last_slot = slotStores the new value in last_slot. The expression reads slot.
  64. refresh()Calls refresh with the values in its parentheses.
  65. 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.
  66. func choose_product(item: String) -> void:Change what the player is holding. The selection does not fill a shelf position.
  67. chosen = itemStores the new value in chosen. The expression reads item.
  68. refresh()Calls refresh with the values in its parentheses.
  69. 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.
  70. func reset_board() -> void:Clear the arrangement and reread available stock from the same brief.
  71. board = Shelf.blank_board()Make a clean array of twelve shelf positions before drawing the display.
  72. last_slot = -1Stores the new value in last_slot. The expression reads -1.
  73. refresh()Calls refresh with the values in its parentheses.
  74. 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.
  75. func refresh() -> void:Read the current game values and update the text and styling.
  76. 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.
  77. var placed := 0Creates a variable named placed. The expression uses the whole number 0. Godot infers the type from the first value.
  78. for slot in range(tile_buttons.size()):Visit every visible slot to redraw its label from the current array value.
  79. 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.
  80. 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.
  81. if button.disabled:Checks button.disabled. The indented instructions below run only if this test passes.
  82. button.text = "—"Updates button.text, which controls the words a player sees. The expression uses the text inside the quotes.
  83. elif product.is_empty():If the earlier branches did not run, checks product.is_empty() next.
  84. 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.
  85. button.add_theme_color_override("font_color", Color("#a9c7d3"))Calls button.add_theme_color_override with the values in its parentheses.
  86. else:Runs the indented fallback instructions if none of the earlier tests passed.
  87. var data: Array = Shelf.PRODUCTS[product]Read the original packet's short label and colour from the catalogue.
  88. 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.
  89. button.add_theme_color_override("font_color", Color(data[2]))Calls button.add_theme_color_override with the values in its parentheses.
  90. placed += 1Reads placed, adds to its old value, then stores the result back in the same place.
  91. 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.
  92. button.add_theme_color_override("font_hover_color", Color("#fae8a4"))Calls button.add_theme_color_override with the values in its parentheses.
  93. for item in stock_buttons:Repeats the indented instructions for each value in stock_buttons.
  94. 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.
  95. 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.
  96. var left := int(brief["stock"][item]) - board.count(item)Subtract displayed copies from the brief allowance to show how many remain.
  97. 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.
  98. button.add_theme_color_override("font_color", Color(data[2]))Calls button.add_theme_color_override with the values in its parentheses.
  99. 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.
  100. 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.
  101. func run_task() -> void:Run this lesson’s checking action and show the result before editing the layout again.
  102. var result := Shelf.solve(brief, board)Check for a possible completion from the current state and keep the returned solution off-screen.
  103. output_label.text = "A completion exists. Your live display stayed the same." if not result.is_empty() else "No solution for this arrangement."Updates output_label.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  104. 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.
  105. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  106. label.text = valueUpdates label.text, which controls the words a player sees. The expression reads value.
  107. label.position = box.positionUpdates label.position, which controls the node's local x and y location. The expression reads box.position.
  108. label.size = box.sizeUpdates label.size, which controls the control's width and height. The expression reads box.size.
  109. label.add_theme_font_size_override("font_size", points)Calls label.add_theme_font_size_override with the values in its parentheses.
  110. label.add_theme_color_override("font_color", ink)Calls label.add_theme_color_override with the values in its parentheses.
  111. if wraps:Checks wraps. The indented instructions below run only if this test passes.
  112. label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow the sentence to wrap within the area reserved for it.
  113. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  114. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  115. func make_button(value: String, box: Rect2, action: Callable) -> Button:Make controls with consistent style and room to select them.
  116. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  117. button.text = valueUpdates button.text, which controls the words a player sees. The expression reads value.
  118. button.position = box.positionUpdates button.position, which controls the node's local x and y location. The expression reads box.position.
  119. button.size = box.sizeUpdates button.size, which controls the control's width and height. The expression reads box.size.
  120. button.add_theme_font_size_override("font_size", 14)Calls button.add_theme_font_size_override with the values in its parentheses.
  121. button.add_theme_color_override("font_color", PAPER)Calls button.add_theme_color_override with the values in its parentheses.
  122. button.add_theme_color_override("font_disabled_color", Color("#6f8a9b"))Calls button.add_theme_color_override with the values in its parentheses.
  123. for mode in ["normal", "hover", "pressed", "disabled", "focus"]:Repeats the indented instructions for each value in ["normal", "hover", "pressed", "disabled", "focus"].
  124. var panel := StyleBoxFlat.new()Creates a variable named panel. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value.
  125. 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.
  126. if mode == "disabled":Checks mode == "disabled". The indented instructions below run only if this test passes.
  127. panel.bg_color = Color("#1e3549")Stores the new value in panel.bg_color. The expression builds a colour from these values.
  128. 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.
  129. panel.set_border_width_all(1)Calls panel.set_border_width_all with the values in its parentheses.
  130. panel.set_corner_radius_all(7)Calls panel.set_corner_radius_all with the values in its parentheses.
  131. button.add_theme_stylebox_override(mode, panel)Calls button.add_theme_stylebox_override with the values in its parentheses.
  132. button.pressed.connect(action)Route the button's signal to the action supplied when it was created.
  133. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  134. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  135. func _draw() -> void:Paint the lesson background and display panels without changing the game.
  136. draw_rect(Rect2(Vector2.ZERO, size), Color("#132735"))Paints a rectangle at the given position and size.
  137. draw_rect(Rect2(30, 150, 517, 323), BOARD_BG)Paints a rectangle at the given position and size.
  138. draw_rect(Rect2(562, 150, 370, 323), BOARD_BG)Paints a rectangle at the given position and size.
  139. draw_rect(Rect2(45, 480, 870, 43), Color("#204452"))Paints a rectangle at the given position and size.
  140. draw_rect(Rect2(45, 480, 4, 43), TINT)Paints a rectangle at the given position and size.
  141. 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
  1. extends RefCountedKeep the shelf rules independent from Godot buttons. The live scene, hint and test tray can all call this script.
  2. const WIDTH := 4Define four columns in each practice shelf row.
  3. const HEIGHT := 3Define three rows of practice shelf space.
  4. const CAPACITY := WIDTH * HEIGHTMultiply the dimensions to reserve all twelve array entries, including slots closed by a brief.
  5. const STOCK_PATH := "res://morning_window.json"This res:// path points to the default client card inside the extracted Godot checkpoint.
  6. const PRODUCTS := {Use original miniature IDs as keys. Each product holds a label, category, drawing colour and short tag.
  7. "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.
  8. "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.
  9. "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.
  10. "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.
  11. "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.
  12. "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.
  13. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  14. static func coordinates(slot: int) -> Vector2i:Convert the index in the board array into its across-and-down position.
  15. @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.
  16. 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.
  17. static func slot_index(cell: Vector2i) -> int:Turn the two coordinates back into the flat index used by the board array.
  18. 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.
  19. static func blank_board() -> Array:Return a fresh board on start, restart or a brief audit. It begins without products.
  20. var board: Array = []Start with an empty dynamic collection for the game state.
  21. board.resize(CAPACITY)Reserve a value for every possible shelf slot before the drawing code indexes it.
  22. board.fill("")Replace each default null value with the empty string that illustrates an unfilled shelf space.
  23. return boardFinishes the function and hands its result back to the caller. The expression reads board.
  24. 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.
  25. 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.
  26. return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order.
  27. if not item.is_empty():An empty hand clears a slot without asking for stock. A held product must pass the count guard.
  28. 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.
  29. var used := board.count(item)Count the number of that miniature already on display, including repeated products when the card supplies copies.
  30. if board[slot] == item:Putting the same miniature in its own square reuses the one already there instead of spending another.
  31. used -= 1Reads used, subtracts from its old value, then stores the result back in the same place.
  32. if used >= total:Only accept an addition when at least one copy remains available after the same-position adjustment.
  33. return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order.
  34. var next := board.duplicate()Copy the flat array. A player click may update the new board after the guard finishes.
  35. next[slot] = itemSet just one position of the copy to the currently selected product ID or the empty string.
  36. return nextFinishes the function and hands its result back to the caller. The expression reads next.
  37. 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.
  38. 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.
  39. static func is_integer(value: Variant) -> bool:Test whole-number shape for JSON numbers. A position such as 4.5 cannot index the shelf.
  40. 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.
  41. static func load_brief(path: String = STOCK_PATH) -> Dictionary:Read a client brief from the supplied path or use the default Morning Window file.
  42. var file := FileAccess.open(path, FileAccess.READ)Ask Godot to read project text. The controller does not write to this client brief.
  43. if file == null:Handle a missing or unreadable file before asking it for text.
  44. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  45. 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.
  46. 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.
  47. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  48. 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.
  49. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  50. for key in ["fixed", "rows", "pairs"]:Each set of rules must have an array, even on a brief with no rules of that type.
  51. if not parsed.get(key) is Array:Checks not parsed.get(key) is Array. The indented instructions below run only if this test passes.
  52. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  53. var active: Array[int] = []Build a new typed list of validated shelf indices.
  54. for value in parsed["active"]:Review every active position supplied with the client card.
  55. 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.
  56. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  57. active.append(int(value))Keep the proven value as an int so later board lookups use the expected index type.
  58. if active.is_empty():Checks active.is_empty(). The indented instructions below run only if this test passes.
  59. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  60. parsed["active"] = activeReplace the raw JSON array with the clean array of indices.
  61. var inventory := 0Start a stock total for a simple early check of whether all active spaces could be filled.
  62. for item in parsed["stock"]:Read each key in the stock dictionary. The keys are product IDs.
  63. 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.
  64. if not PRODUCTS.has(item) or not is_integer(count) or count < 1:Require a known mini and a positive whole-number stock quantity.
  65. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  66. inventory += int(count)Add all copies of the current miniature to the count.
  67. if inventory < active.size():There must be enough stock to fill every open display space.
  68. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  69. for rule in parsed["fixed"]:Check that every fixed rule uses an open slot and a stocked product.
  70. 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.
  71. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  72. 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.
  73. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  74. for rule in parsed["rows"]:Check the row number, row target and known category before trying a constraint.
  75. 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.
  76. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  77. 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.
  78. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  79. 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.
  80. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  81. for rule in parsed["pairs"]:Both members of a pair must be stocked and refer to distinct product IDs.
  82. 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.
  83. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  84. if rule["left"] == rule["right"]:Checks rule["left"] == rule["right"]. The indented instructions below run only if this test passes.
  85. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  86. return parsedSupply a validated dictionary to the controller, checker or test audit.
  87. static func empty_count(brief: Dictionary, board: Array) -> int:Count gaps in the current attempt, using only the positions this brief opens.
  88. var empty := 0Track unused positions separately so a partial board can still meet a target.
  89. for slot in brief["active"]:Repeats the indented instructions for each value in brief["active"].
  90. if board[int(slot)] == "":The empty string represents an open position into which a player has placed nothing.
  91. empty += 1Reads empty, adds to its old value, then stores the result back in the same place.
  92. return emptyFinishes the function and hands its result back to the caller. The expression reads empty.
  93. static func fixed_issue(brief: Dictionary, board: Array) -> String:Check anchored miniatures. An empty anchor can still be filled correctly.
  94. for lock in brief["fixed"]:Read each required slot and product using the same kind of rule.
  95. 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.
  96. var item: String = board[slot]Read the miniature ID from the live or simulated slot.
  97. 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.
  98. 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.
  99. return ""Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  100. static func slot_name(slot: int) -> String:Convert zero-based coordinates into the readable names R1 C1 and R2 C3.
  101. 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.
  102. 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.
  103. 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.
  104. var matching := 0Begin the category count at zero each time this function receives a board.
  105. var empty := 0Track unused positions separately so a partial board can still meet a target.
  106. for slot in brief["active"]:Repeats the indented instructions for each value in brief["active"].
  107. if coordinates(int(slot)).y != row:Ignore positions whose coordinate y places them in another row.
  108. continueSkips the rest of this turn through the loop and moves on to the next item.
  109. 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.
  110. if item.is_empty():Checks item.is_empty(). The indented instructions below run only if this test passes.
  111. empty += 1Reads empty, adds to its old value, then stores the result back in the same place.
  112. elif PRODUCTS[item][1] == category:Look up the catalogue category before counting an occupied position as a snack, drink or care item.
  113. matching += 1Reads matching, adds to its old value, then stores the result back in the same place.
  114. return Vector2i(matching, empty)Return the matching total and the empty total together so the next check can read both.
  115. 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.
  116. for quota in brief["rows"]:Apply the same exact-count rule to every named category quota.
  117. 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.
  118. 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.
  119. 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.
  120. 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.
  121. 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.
  122. return ""Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  123. static func neighbours(first: int, second: int) -> bool:Decide whether two slots share a horizontal or vertical edge.
  124. var gap := coordinates(first) - coordinates(second)Subtract column and row separately so one row cannot wrap into the next.
  125. return absi(gap.x) + absi(gap.y) == 1Use the sum of absolute distances. Exactly one step reaches an orthogonal neighbour.
  126. static func has_pair(brief: Dictionary, board: Array, first: String, second: String) -> bool:Search the active product pairs for at least one with the desired identifiers beside one another.
  127. for left in brief["active"]:Try every active slot as the first product location.
  128. if board[int(left)] != first:Skip all candidate positions that do not contain the first required mini.
  129. continueSkips the rest of this turn through the loop and moves on to the next item.
  130. for right in brief["active"]:Compare the first product with every active position in which the second product could sit.
  131. if board[int(right)] == second and neighbours(int(left), int(right)):Both matching product IDs and a shared edge are necessary for success.
  132. return trueFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value true.
  133. return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false.
  134. static func pair_issue(brief: Dictionary, board: Array) -> String:Find any required pair with no shared edge that the current placement can no longer repair by adding stock.
  135. for pair in brief["pairs"]:Repeats the indented instructions for each value in brief["pairs"].
  136. var first: String = pair["left"]Creates a variable named first. 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.
  137. var second: String = pair["right"]Creates a variable named second. 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.
  138. if has_pair(brief, board, first, second):The early continue moves on when this pair already meets the brief.
  139. continueSkips the rest of this turn through the loop and moves on to the next item.
  140. var full := empty_count(brief, board) == 0A full board has no room for additions. A missing pair then needs the player to move or remove a box.
  141. var used_all := board.count(first) == int(brief["stock"][first]) and board.count(second) == int(brief["stock"][second])If both products have no stock left, more placements elsewhere cannot become the required pair.
  142. if full or used_all:Report the pair when filling the current layout cannot supply a missing neighbour.
  143. return "%s and %s need a shared edge." % [display_name(first), display_name(second)]Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  144. return ""Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  145. static func rule_issue(brief: Dictionary, board: Array) -> String:Run all the constraints in a predictable order and keep the first useful issue.
  146. var issue := fixed_issue(brief, board)Consider fixed spots first so the user can correct the layout's anchors before other geometry.
  147. if issue.is_empty():Checks issue.is_empty(). The indented instructions below run only if this test passes.
  148. issue = quota_issue(brief, board)Only check the row target while there is no earlier issue.
  149. if issue.is_empty():Checks issue.is_empty(). The indented instructions below run only if this test passes.
  150. issue = pair_issue(brief, board)Only check product neighbours while the anchors and row limits allow the attempt.
  151. return issueFinishes the function and hands its result back to the caller. The expression reads issue.
  152. static func report(brief: Dictionary, board: Array) -> Dictionary:Translate the current situation into a named state and clear guidance.
  153. var issue := rule_issue(brief, board)Creates a variable named issue. The expression calls rule_issue with the values in its parentheses. Godot infers the type from the first value.
  154. if not issue.is_empty():Checks not issue.is_empty(). The indented instructions below run only if this test passes.
  155. return {"state": "revise", "message": issue}Tell the player what needs changing before this branch can become a solution.
  156. var remaining := empty_count(brief, board)Creates a variable named remaining. The expression calls empty_count with the values in its parentheses. Godot infers the type from the first value.
  157. if remaining > 0:Checks remaining > 0. The indented instructions below run only if this test passes.
  158. return {"state": "open", "message": "Fits so far. Fill %d more display slots." % remaining}Count the remaining gaps. This partial display has not triggered any local checks.
  159. return {"state": "ready", "message": "Display ready. Every brief rule passes."}Report success when no local rule failed and all open shelf spaces have a product.
  160. static func solve(brief: Dictionary, board: Array) -> Array:Start the placement search on a copy of the current board.
  161. var trial := board.duplicate()Protect the player's display as the solver tests product choices.
  162. return search(brief, trial)Let the recursive function search from the supplied display rather than resetting existing player choices.
  163. static func search(brief: Dictionary, trial: Array) -> Array:Explore choices for the first still-empty slot. Continue until a branch passes or all choices run out.
  164. if not rule_issue(brief, trial).is_empty():Cut a trial branch that cannot be fixed by adding more products.
  165. return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order.
  166. for position in brief["active"]:Read the list of positions this brief lets the player fill.
  167. var slot := int(position)Creates a variable named slot. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  168. if trial[slot] != "":Leave players' fixed placements and earlier branch choices in place.
  169. continueSkips the rest of this turn through the loop and moves on to the next item.
  170. for item in brief["stock"]:Consider each available mini ID in a fixed order.
  171. if trial.count(item) >= int(brief["stock"][item]):Skip a product after this branch has placed every copy supplied by the brief.
  172. continueSkips the rest of this turn through the loop and moves on to the next item.
  173. trial[slot] = itemMake a temporary placement in the current empty slot.
  174. var result := search(brief, trial)Try to fill the rest of the display from this choice.
  175. trial[slot] = ""Remove the temporary product before considering the next choice or returning to a caller.
  176. if not result.is_empty():The nonempty result is a complete arrangement from some successful branch.
  177. return resultFinishes the function and hands its result back to the caller. The expression reads result.
  178. return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order.
  179. return trial.duplicate()All active slots have been checked. Copy the answer so the backtracking clean-up leaves it intact.

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 repeated runs appear to place invisible minis, check that you clear the trial position after a recursive call and always make the first board copy.

Try a change

Reverse the order of the stock choices in your copy. Compare the first arrangement returned on an empty shelf. Both solutions should still pass the same checks.