Market Day London · Lesson 28 of 50 · Intermediate · About 35 min
A dry route around the market can take patience. Instead of guessing which neighbour looks promising, Nia’s hint checks short legal plans first.

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/27 when the lesson builds on prior work, or copy the checkpoints/28 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 breadth-first search, queue, visited states, array index, continue, shortest route.
-
Open the route challenge
Import Lesson 28. Press Route hint while Nia is at C. Read the recommended first action and the number of legal turns. Write the count down before moving.
Why it works The hint plans through the whole order queue. It also includes the trips and the delivery actions.
-
Start with one entry
Open shift_rules.gd, find find_route and inspect the first queue. Notice the starting state and an empty route stored together.
var queue: Array[Dictionary] = [{"state": state, "route": empty}]Why it works The first entry represents where you are now. The empty route costs zero turns.
-
Read the oldest entry
Read the while loop with index. Follow how index increases and later entries are appended. Use cards to model checking a starting entry then two one-move entries.
var entry: Dictionary = queue[index]Why it works Increasing the index reads entries in arrival order. All one-turn routes are considered before two-turn routes.
-
Use the same legal rules
Trace the inner loop over directions, pick and deliver. Read what happens if result ok is false. Try walking into a rain tile during the game.
var result := apply_action(shift, entry["state"], action)Why it works A hint cannot suggest a move the game rejects when both share the same rule.
-
Skip seen situations
Read the key lookup before route.append. Walk out and back during play, then ask for a new hint. Compare whether the count from the current situation changes.
if visited.has(key):Why it works When location, bundle and request are identical, revisiting them cannot make a shorter plan.
-
Check the finish
Find the return when a queued state is finished. Follow the displayed actions or repeatedly use the hint until both bundles have been accepted.
return entry["route"]Why it works The first finished entry is one of the shortest. Each legal action has the same price of one turn.
Watch the values change
-
Ask for a hint at the start The empty basket and counter begin the queue.
What you see. A first action and a 40-turn plan are shown. -
Walk one suggested step The live route has spent one turn.
What you see. A new hint can finish in 39 further legal turns. -
Reach the counter twice Both bundles have been handed over.
What you see. The finished state has no more actions to suggest.
Predict before you run If a second route has the same shortest length, does the planner have to show the same first action?
Reveal the answer
A different equally short route can start differently. The order of candidate actions decides which route a fixed version shows first.
Complete checkpoint
Route hint finds a 40-turn legal plan from the starting counter and shows its first action.
main.gd
extends Control
const Rules = preload("res://shift_rules.gd")
const ORIGIN := Vector2(30, 114)
const CELL := Vector2(88, 71)
const INK := Color("#162e32")
const PAPER := Color("#f9efda")
const MINT := Color("#9cddc2")
const GOLD := Color("#f0c881")
var shift: Dictionary
var state: Dictionary
var status: Label
var info: Label
var board_title: Label
var detail: Label
var buttons: Dictionary = {}
func _ready() -> void:
board_title = make_label("MARKET DAY LONDON", Vector2(29, 20), Vector2(900, 40), 32, PAPER)
make_label("BRIAR LANE / LESSON 28 / ROUTE HINT", Vector2(32, 65), Vector2(890, 24), 16, GOLD)
info = make_label("", Vector2(507, 105), Vector2(422, 105), 19, PAPER)
make_button("north", "↑ North", Vector2(617, 221), 96)
make_button("west", "← West", Vector2(507, 266), 96)
make_button("south", "↓ South", Vector2(617, 266), 96)
make_button("east", "→ East", Vector2(727, 266), 96)
make_button("pick", "Pick item", Vector2(507, 318), 133)
make_button("deliver", "Deliver", Vector2(650, 318), 133)
make_button("restart", "Restart shift", Vector2(507, 369), 134)
make_button("hint", "Route hint", Vector2(650, 369), 133)
status = make_label("", Vector2(507, 421), Vector2(420, 87), 17, MINT)
detail = make_label("", Vector2(32, 418), Vector2(440, 105), 15, PAPER)
shift = Rules.load_shift()
if shift.is_empty():
status.text = "The shift file could not be opened."
return
restart()
func make_label(value: String, origin: Vector2, extent: Vector2, size_px: int, ink: Color) -> Label:
var label := Label.new()
label.text = value
label.position = origin
label.size = extent
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
label.add_theme_font_size_override("font_size", size_px)
label.add_theme_color_override("font_color", ink)
add_child(label)
return label
func make_button(action: String, title: String, origin: Vector2, width: float) -> void:
var button := Button.new()
button.text = title
button.position = origin
button.size = Vector2(width, 37)
button.add_theme_font_size_override("font_size", 16)
button.pressed.connect(press_action.bind(action))
add_child(button)
buttons[action] = button
func restart() -> void:
state = Rules.start()
detail.text = "Open paths are pale. Dark tiles have closed."
info_update("Start at the counter. Pick an item when Nia reaches its tile.")
func _unhandled_key_input(event: InputEvent) -> void:
for action in ["north", "east", "south", "west"]:
var key: String = {"north": "ui_up", "east": "ui_right", "south": "ui_down", "west": "ui_left"}[action]
if event.is_action_pressed(key) and not event.is_echo():
press_action(action)
get_viewport().set_input_as_handled()
return
func press_action(action: String) -> void:
if action == "restart":
if not shift.is_empty():
restart()
return
if shift.is_empty():
return
if action == "hint":
var route := Rules.find_route(shift, state)
detail.text = "No more actions to show." if route.is_empty() else "Next action: %s. Finish in %d legal turns." % [route[0], route.size()]
return
var result := Rules.apply_action(shift, state, action)
if result["ok"]:
state = result["state"]
info_update(result["message"])
func info_update(message: String) -> void:
var basket: Array = state["basket"]
var count: int = state["order"]
var order_text := "All bundles accepted"
if not Rules.finished(shift, state):
order_text = " + ".join(shift["orders"][count])
var contents := ", ".join(basket) if not basket.is_empty() else "empty"
info.text = "ORDER %d / %d · %s
BASKET %d / 3 · %s
TURN %d / GOLD TARGET %d" % [
mini(count + 1, shift["orders"].size()), shift["orders"].size(), order_text,
basket.size(), contents, state["turns"], shift["par"]]
status.text = message
queue_redraw()
func _draw() -> void:
draw_rect(Rect2(0, 0, 960, 540), INK)
draw_rect(Rect2(482, 93, 2, 420), Color("#4f7776"))
if shift.is_empty() or state.is_empty():
return
var font := ThemeDB.fallback_font
for y in range(4):
for x in range(5):
var cell := Vector2i(x, y)
var corner := ORIGIN + Vector2(cell) * CELL
var fill := Color("#ded0a9")
var tile := "%d,%d" % [x, y]
if Rules.blocked(shift, cell):
fill = Color("#6b8390")
tile = "Closed"
elif Rules.ITEMS.has(Rules.marker(shift, cell)):
fill = Color("#d9a77a")
tile = str(Rules.ITEMS[Rules.marker(shift, cell)]).capitalize()
elif cell == Rules.COUNTER:
fill = Color("#8bc5ac")
tile = "Counter"
draw_rect(Rect2(corner, CELL - Vector2(4, 4)), fill)
draw_string(font, corner + Vector2(9, 22), tile, HORIZONTAL_ALIGNMENT_LEFT, -1, 15, INK)
if state["cell"] == cell:
draw_circle(corner + Vector2(42, 45), 14, Color("#39416b"))
draw_string(font, corner + Vector2(29, 50), "Nia", HORIZONTAL_ALIGNMENT_LEFT, -1, 13, Color.WHITE)
shift_rules.gd
extends RefCounted
const CAPACITY := 3
const INCREMENT := {"west": Vector2i.LEFT, "east": Vector2i.RIGHT,
"north": Vector2i.UP, "south": Vector2i.DOWN}
const ITEMS := {"A": "apple", "F": "flower", "B": "bread"}
const COUNTER := Vector2i(4, 3)
static func load_shift() -> Dictionary:
var file := FileAccess.open("res://shift.json", FileAccess.READ)
if file == null:
return {}
var loaded: Variant = JSON.parse_string(file.get_as_text())
if not loaded is Dictionary or not loaded.get("orders") is Array:
return {}
if not loaded.get("rows") is Array or loaded["rows"].size() != 4:
return {}
for row in loaded["rows"]:
if not row is String or row.length() != 5:
return {}
if loaded["orders"].is_empty() or not loaded.has("par"):
return {}
return loaded
static func start() -> Dictionary:
return {"cell": COUNTER, "basket": [], "order": 0, "turns": 0}
static func finished(shift: Dictionary, state: Dictionary) -> bool:
return int(state["order"]) >= shift["orders"].size()
static func exact_bundle(basket: Array, order: Array) -> bool:
var remaining := basket.duplicate()
for item in order:
if not remaining.has(item):
return false
remaining.erase(item)
return remaining.is_empty()
static func marker(shift: Dictionary, cell: Vector2i) -> String:
var row: String = shift["rows"][cell.y]
return row.substr(cell.x, 1)
static func blocked(shift: Dictionary, cell: Vector2i) -> bool:
return marker(shift, cell) == "#"
static func reject(message: String) -> Dictionary:
return {"ok": false, "message": message}
static func apply_action(shift: Dictionary, state: Dictionary, action: String) -> Dictionary:
if finished(shift, state):
return reject("Shift complete. Restart to practise again.")
var next := state.duplicate(true)
var cell: Vector2i = next["cell"]
var message := ""
if INCREMENT.has(action):
var destination: Vector2i = cell + INCREMENT[action]
var area := Rect2i(0, 0, 5, 4)
if not area.has_point(destination):
return reject("Briar Lane ends there.")
if blocked(shift, destination):
return reject("Rain has closed that tile. Find a dry route.")
next["cell"] = destination
message = "Moved %s to (%d, %d)." % [action, destination.x, destination.y]
elif action == "pick":
var symbol := marker(shift, cell)
if not ITEMS.has(symbol):
return reject("Stand on a stall tile to pick up an item.")
if next["basket"].size() >= CAPACITY:
return reject("Your basket has three items already.")
var item: String = ITEMS[symbol]
var order: Array = shift["orders"][next["order"]]
if next["basket"].count(item) >= order.count(item):
return reject("This bundle does not need another %s." % item)
next["basket"].append(item)
message = "Added %s to your basket." % item
elif action == "deliver":
if cell != COUNTER:
return reject("Deliver from the collection counter.")
var order: Array = shift["orders"][next["order"]]
if not exact_bundle(next["basket"], order):
return reject("Match the whole order. The basket stays as it was.")
next["basket"].clear()
next["order"] += 1
message = "Bundle accepted."
else:
return reject("Choose a market action.")
next["turns"] += 1
if finished(shift, next):
var at_target: bool = next["turns"] <= shift["par"]
message += " Shift complete. " + ("Gold target met." if at_target else "Keep practising for gold.")
return {"ok": true, "state": next, "message": message}
static func preview(shift: Dictionary, live: Dictionary, action: String) -> String:
var result := apply_action(shift, live, action)
if not result["ok"]:
return result["message"]
return "Live cell %s stays put. %s alone would set a copy to %s." % [
str(live["cell"]), action, str(result["state"]["cell"])]
static func state_key(state: Dictionary) -> String:
var basket: Array = state["basket"].duplicate()
basket.sort()
var cell: Vector2i = state["cell"]
return "%d,%d|%s|%d" % [cell.x, cell.y, ",".join(basket), state["order"]]
static func compare_keys() -> String:
var first := start()
first["basket"] = ["apple", "bread"]
var second := start()
second["basket"] = ["bread", "apple"]
var same_items := state_key(first) == state_key(second)
second["order"] = 1
var changed_order := state_key(first) != state_key(second)
return "Same items: %s. New order changes key: %s.
%s" % [
str(same_items), str(changed_order), state_key(first)]
static func find_route(shift: Dictionary, state: Dictionary) -> Array[String]:
var empty: Array[String] = []
var queue: Array[Dictionary] = [{"state": state, "route": empty}]
var visited := {state_key(state): true}
var index := 0
while index < queue.size():
var entry: Dictionary = queue[index]
index += 1
if finished(shift, entry["state"]):
return entry["route"]
for action in ["west", "east", "north", "south", "pick", "deliver"]:
var result := apply_action(shift, entry["state"], action)
if not result["ok"]:
continue
var key := state_key(result["state"])
if visited.has(key):
continue
visited[key] = true
var route: Array[String] = entry["route"].duplicate()
route.append(action)
queue.append({"state": result["state"], "route": route})
return empty
shift.json
{
"name": "Two orders",
"group": "Training",
"par": 41,
"rows": [
"A.#.F",
"..#..",
"..#..",
"B...C"
],
"orders": [
[
"apple",
"flower"
],
[
"bread",
"flower"
]
]
}
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 ControlThe learning scene uses Godot’s Control node for drawing, labels and input. -
const Rules = preload("res://shift_rules.gd")Load the pure rule helper once so this view can read level data and send player actions to it. -
const ORIGIN := Vector2(30, 114)Set the upper-left point of the map, leaving room for the title before the first row. -
const CELL := Vector2(88, 71)Keep the tiles at predictable intervals so a coordinate can turn into a screen position. -
const INK := Color("#162e32")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value. -
const PAPER := Color("#f9efda")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value. -
const MINT := Color("#9cddc2")Creates a constant named MINT. The expression builds a colour from these values. Godot infers the type from the first value. -
const GOLD := Color("#f0c881")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value. -
var shift: DictionaryStore the fixed map and order card for this attempt. -
var state: DictionaryHold the position, basket, turn and current request that can change during the shift. -
var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here. -
var info: LabelDeclares info for later use. A colon followed by a type says which kind of value belongs here. -
var board_title: LabelDeclares board_title for later use. A colon followed by a type says which kind of value belongs here. -
var detail: LabelDeclares detail for later use. A colon followed by a type says which kind of value belongs here. -
var buttons: Dictionary = {}Creates a variable named buttons. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold. -
func _ready() -> void:Godot calls this once after the main node enters the scene. It creates the HUD and buttons before reading the data. -
board_title = make_label("MARKET DAY LONDON", Vector2(29, 20), Vector2(900, 40), 32, PAPER)Stores the new value in board_title. The expression calls make_label with the values in its parentheses. -
make_label("BRIAR LANE / LESSON 28 / ROUTE HINT", Vector2(32, 65), Vector2(890, 24), 16, GOLD)Calls make_label with the values in its parentheses. -
info = make_label("", Vector2(507, 105), Vector2(422, 105), 19, PAPER)Stores the new value in info. The expression calls make_label with the values in its parentheses. -
make_button("north", "↑ North", Vector2(617, 221), 96)Calls make_button with the values in its parentheses. -
make_button("west", "← West", Vector2(507, 266), 96)Calls make_button with the values in its parentheses. -
make_button("south", "↓ South", Vector2(617, 266), 96)Calls make_button with the values in its parentheses. -
make_button("east", "→ East", Vector2(727, 266), 96)Calls make_button with the values in its parentheses. -
make_button("pick", "Pick item", Vector2(507, 318), 133)Calls make_button with the values in its parentheses. -
make_button("deliver", "Deliver", Vector2(650, 318), 133)Calls make_button with the values in its parentheses. -
make_button("restart", "Restart shift", Vector2(507, 369), 134)Calls make_button with the values in its parentheses. -
make_button("hint", "Route hint", Vector2(650, 369), 133)Calls make_button with the values in its parentheses. -
status = make_label("", Vector2(507, 421), Vector2(420, 87), 17, MINT)Place the action feedback on the lower right, where it remains near the control buttons. -
detail = make_label("", Vector2(32, 418), Vector2(440, 105), 15, PAPER)Reserve a separate panel for exploration results such as a hint or a replay report. -
shift = Rules.load_shift()Load the challenge card. A failed file read can show a message before the board tries to draw its data. -
if shift.is_empty():Checks shift.is_empty(). The indented instructions below run only if this test passes. -
status.text = "The shift file could not be opened."Updates status.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. -
restart()Calls restart with the values in its parentheses. -
func make_label(value: String, origin: Vector2, extent: Vector2, size_px: int, ink: Color) -> Label:Create a reusable label with explicit size and colour so each part of the scene keeps a readable place. -
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 = originUpdates label.position, which controls the node's local x and y location. The expression reads origin. -
label.size = extentUpdates label.size, which controls the control's width and height. The expression reads extent. -
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow feedback to wrap cleanly inside the width provided, improving readability on a compact canvas. -
label.add_theme_font_size_override("font_size", size_px)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. -
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(action: String, title: String, origin: Vector2, width: float) -> void:Give a visible caption and a specific game action to each button. A helper keeps their hit areas consistent. -
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 = titleUpdates button.text, which controls the words a player sees. The expression reads title. -
button.position = originUpdates button.position, which controls the node's local x and y location. The expression reads origin. -
button.size = Vector2(width, 37)Updates button.size, which controls the control's width and height. The expression packs x and y into one value. -
button.add_theme_font_size_override("font_size", 16)Calls button.add_theme_font_size_override with the values in its parentheses. -
button.pressed.connect(press_action.bind(action))Connect a press to the shared dispatcher and bind the action that this exact button should request. -
add_child(button)Adds the new node to the scene tree so that Godot can run and draw it. -
buttons[action] = buttonStores the new value in buttons[action]. The expression reads button. -
func restart() -> void:Restore the market to the initial player state without rebuilding the level or its controls. -
state = Rules.start()Throw away progress from the current attempt and start back at the collection counter. -
detail.text = "Open paths are pale. Dark tiles have closed."Updates detail.text, which controls the words a player sees. The expression uses the text inside the quotes. -
info_update("Start at the counter. Pick an item when Nia reaches its tile.")Calls info_update with the values in its parentheses. -
func _unhandled_key_input(event: InputEvent) -> void:Handle arrow keys that were not consumed by another control. Touch buttons and keyboard arrows use the same actions. -
for action in ["north", "east", "south", "west"]:Repeats the indented instructions for each value in ["north", "east", "south", "west"]. -
var key: String = {"north": "ui_up", "east": "ui_right", "south": "ui_down", "west": "ui_left"}[action]Creates a variable named key. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold. -
if event.is_action_pressed(key) and not event.is_echo():Recognise the relevant direction press and ignore keyboard repeats so one press is one requested move. -
press_action(action)Calls press_action with the values in its parentheses. -
get_viewport().set_input_as_handled()Make this recognised direction event belong to this market action and prevent another handler spending it again. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
func press_action(action: String) -> void:Route commands to restart, tools or live play. Only the live accepted-action branch can adopt a new state. -
if action == "restart":Reset is a scene command rather than a counted turn, and it starts only when a valid card has been loaded. -
if not shift.is_empty():Checks not shift.is_empty(). The indented instructions below run only if this test passes. -
restart()Calls restart with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if shift.is_empty():Checks shift.is_empty(). The indented instructions below run only if this test passes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if action == "hint":Checks action == "hint". The indented instructions below run only if this test passes. -
var route := Rules.find_route(shift, state)Ask the planner for a legal sequence from the current position, basket and request. -
detail.text = "No more actions to show." if route.is_empty() else "Next action: %s. Finish in %d legal turns." % [route[0], route.size()]Updates detail.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var result := Rules.apply_action(shift, state, action)Use the pure market rule for an actual player request. -
if result["ok"]:The accepted branch is the only place a move, pickup or delivery replaces the browser-visible market state. -
state = result["state"]Commit the proposed result after the rule accepts it. That makes this different from a preview or replay. -
info_update(result["message"])Update the screen even after a refusal so the player sees a clear reason without losing progress. -
func info_update(message: String) -> void:Read the current state and put useful values into the display before requesting a redraw. -
var basket: Array = state["basket"]Creates a variable named basket. 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 count: int = state["order"]Use the zero-based order index to find the next bundle. The displayed order number will start at one. -
var order_text := "All bundles accepted"Creates a variable named order_text. The expression uses the text inside the quotes. Godot infers the type from the first value. -
if not Rules.finished(shift, state):A completed shift has no further order index. Check before reading the array. -
order_text = " + ".join(shift["orders"][count])Lay out the current bundle with a plus sign between items so the player can read the full request. -
var contents := ", ".join(basket) if not basket.is_empty() else "empty"Creates a variable named contents. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value. -
info.text = "ORDER %d / %d · %sUpdates info.text, which controls the words a player sees. The expression uses the text inside the quotes. -
BASKET %d / 3 · %sContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function. -
TURN %d / GOLD TARGET %d" % [Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function. -
mini(count + 1, shift["orders"].size()), shift["orders"].size(), order_text,Calls mini with the values in its parentheses. -
basket.size(), contents, state["turns"], shift["par"]]Counts the items in this collection. -
status.text = messageUpdates status.text, which controls the words a player sees. The expression reads message. -
queue_redraw()Tell Godot the panel needs repainting after a move or status update. -
func _draw() -> void:Paint the board from the current shift and state. This visual step never spends a turn. -
draw_rect(Rect2(0, 0, 960, 540), INK)Paints a rectangle at the given position and size. -
draw_rect(Rect2(482, 93, 2, 420), Color("#4f7776"))Paints a rectangle at the given position and size. -
if shift.is_empty() or state.is_empty():Checks shift.is_empty() or state.is_empty(). The indented instructions below run only if this test passes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var font := ThemeDB.fallback_fontCreates a variable named font. The expression reads ThemeDB.fallback_font. Godot infers the type from the first value. -
for y in range(4):Visit each horizontal row. The inner loop handles every column. -
for x in range(5):Make one tile for every x position across the current row. -
var cell := Vector2i(x, y)Creates a variable named cell. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value. -
var corner := ORIGIN + Vector2(cell) * CELLTranslate the grid coordinates into pixels using the origin and spacing. -
var fill := Color("#ded0a9")Creates a variable named fill. The expression builds a colour from these values. Godot infers the type from the first value. -
var tile := "%d,%d" % [x, y]Creates a variable named tile. The expression uses the text inside the quotes. Godot infers the type from the first value. -
if Rules.blocked(shift, cell):Use the same closure check as movement, so wet squares look as impassable as they behave. -
fill = Color("#6b8390")Stores the new value in fill. The expression builds a colour from these values. -
tile = "Closed"Stores the new value in tile. The expression uses the text inside the quotes. -
elif Rules.ITEMS.has(Rules.marker(shift, cell)):Use the stall marker to choose a label and a distinct tile style. -
fill = Color("#d9a77a")Stores the new value in fill. The expression builds a colour from these values. -
tile = str(Rules.ITEMS[Rules.marker(shift, cell)]).capitalize()Stores the new value in tile. The expression turns a value into text for a player message. -
elif cell == Rules.COUNTER:Draw the finish location with its collection counter label and green fill. -
fill = Color("#8bc5ac")Stores the new value in fill. The expression builds a colour from these values. -
tile = "Counter"Stores the new value in tile. The expression uses the text inside the quotes. -
draw_rect(Rect2(corner, CELL - Vector2(4, 4)), fill)Paints a rectangle at the given position and size. -
draw_string(font, corner + Vector2(9, 22), tile, HORIZONTAL_ALIGNMENT_LEFT, -1, 15, INK)Paints a piece of text with a font at a position measured from the node's origin. -
if state["cell"] == cell:Draw Nia’s marker only on the tile that matches her current coordinates. -
draw_circle(corner + Vector2(42, 45), 14, Color("#39416b"))Paints a filled circle or outline in this node's local coordinates. -
draw_string(font, corner + Vector2(29, 50), "Nia", HORIZONTAL_ALIGNMENT_LEFT, -1, 13, Color.WHITE)Paints a piece of text with a font at a position measured from the node's origin.
Read shift_rules.gd line by line
-
extends RefCountedThis file holds the market rules without needing a drawing node. The live controls, preview and planner can call the same class. -
const CAPACITY := 3Nia can carry at most three items. Every pickup passes through this same limit. -
const INCREMENT := {"west": Vector2i.LEFT, "east": Vector2i.RIGHT,Record the one-square change for each direction in a dictionary. The direction buttons send those same keys. -
"north": Vector2i.UP, "south": Vector2i.DOWN}Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
const ITEMS := {"A": "apple", "F": "flower", "B": "bread"}Translate A, F and B from the shift card into the exact item names that the orders use. -
const COUNTER := Vector2i(4, 3)The training map always starts at its lower right collection counter. Coordinates count from zero. -
static func load_shift() -> Dictionary:Defines load shift, 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 file := FileAccess.open("res://shift.json", FileAccess.READ)Ask Godot to read the JSON card from the project folder. This action does not write to the level. -
if file == null:Stop immediately when the file could not be opened. There is no usable text to parse. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
var loaded: Variant = JSON.parse_string(file.get_as_text())Parse text to game data. Variant allows the parser to return a dictionary or another result until the type check. -
if not loaded is Dictionary or not loaded.get("orders") is Array:Use the order list only after proving the outer value is a dictionary. A wrong shape returns an empty result. -
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 loaded.get("rows") is Array or loaded["rows"].size() != 4:The training map needs four horizontal rows. Reject a missing rows list or an unexpected row count. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
for row in loaded["rows"]:Inspect every row in the card before the screen or movement code uses a square from it. -
if not row is String or row.length() != 5:Each row must be text exactly five characters long, so the map reader can reliably find its columns. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
if loaded["orders"].is_empty() or not loaded.has("par"):An empty queue or missing target cannot start this shift. The main screen has a message for an invalid card. -
return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
return loadedHand the card back only after the validation gates. A loaded card can now be shared by drawing and rules. -
static func start() -> Dictionary:Defines start, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
return {"cell": COUNTER, "basket": [], "order": 0, "turns": 0}Begin on C with an empty basket, the first indexed order and zero turns. Nothing from a previous run is carried over. -
static func finished(shift: Dictionary, state: Dictionary) -> bool:Defines finished, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
return int(state["order"]) >= shift["orders"].size()The first order uses index zero. With two orders, the completed state reaches index two and no valid order remains. -
static func exact_bundle(basket: Array, order: Array) -> bool:Defines exact bundle, 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 remaining := basket.duplicate()Copy the basket before matching. Removing items from the temporary list must not remove them from Nia’s actual basket. -
for item in order:Match each requested copy one at a time. If an order repeats apple, this loop checks for two available copies. -
if not remaining.has(item):A missing item makes the bundle fail immediately. The original basket remains safe while this temporary list changes. -
return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false. -
remaining.erase(item)Remove the first matching copy from the temporary list. An order entry can only be satisfied once. -
return remaining.is_empty()A match also requires no surplus items. If the list contains an extra good, the order is not exact. -
static func marker(shift: Dictionary, cell: Vector2i) -> String:Defines marker, 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 row: String = shift["rows"][cell.y]Choose the text row with y before looking for a character horizontally. -
return row.substr(cell.x, 1)Use x to take exactly one marker from the chosen row. The other squares on the line stay unchanged. -
static func blocked(shift: Dictionary, cell: Vector2i) -> bool:Defines blocked, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
return marker(shift, cell) == "#"Only # is a rain closure. A plain dot and all stall or counter symbols remain walkable. -
static func reject(message: String) -> Dictionary:Defines reject, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
return {"ok": false, "message": message}False tells the screen not to replace the live state. The readable message still explains what happened. -
static func apply_action(shift: Dictionary, state: Dictionary, action: String) -> Dictionary:Defines apply action, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
if finished(shift, state):Protect the finished screen from extra moves. Restart is placed in the interface rather than treated as a market turn. -
return reject("Shift complete. Restart to practise again.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
var next := state.duplicate(true)Make an independent dictionary and basket before any changes. Preview and route search need this copy. -
var cell: Vector2i = next["cell"]Read Nia’s current grid coordinates once. Picking or delivering can now test the current square. -
var message := ""Creates a variable named message. The expression uses the text inside the quotes. Godot infers the type from the first value. -
if INCREMENT.has(action):Directions use the movement dictionary. Pickup and delivery go through separate checks further down. -
var destination: Vector2i = cell + INCREMENT[action]Add the step to the old cell to get the proposed destination. Nia’s live position has not changed. -
var area := Rect2i(0, 0, 5, 4)The teaching lane is five by four squares. A rectangle uses valid x values zero to four and y values zero to three. -
if not area.has_point(destination):Check bounds before reading a character. Passing it to marker first could request a cell that does not exist. -
return reject("Briar Lane ends there.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
if blocked(shift, destination):Look up the proposed cell on the map. Refusing the rain tile here avoids changing Nia or the turn count. -
return reject("Rain has closed that tile. Find a dry route.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
next["cell"] = destinationStore a legal move in the proposed state. The caller still decides whether to keep that result. -
message = "Moved %s to (%d, %d)." % [action, destination.x, destination.y]Stores the new value in message. The expression uses the text inside the quotes. -
elif action == "pick":The Pick item button attempts to take the good sold on Nia’s current square. -
var symbol := marker(shift, cell)Read the map symbol below Nia. A, B and F select items, while a walkable dot is empty. -
if not ITEMS.has(symbol):If Nia is away from a mapped stall, refuse the attempt with a clear prompt. -
return reject("Stand on a stall tile to pick up an item.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
if next["basket"].size() >= CAPACITY:A basket full of three items cannot accept a fourth. Refusal happens before any change. -
return reject("Your basket has three items already.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
var item: String = ITEMS[symbol]Look up the item name using the stall symbol. Its value must use the same spelling as the order array. -
var order: Array = shift["orders"][next["order"]]Choose the active bundle using the order index. Never add items for a future bundle early. -
if next["basket"].count(item) >= order.count(item):Compare how many copies are held with how many are requested. Even a genuine stall item may be unneeded. -
return reject("This bundle does not need another %s." % item)Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
next["basket"].append(item)Take the accepted item in the copy only. One bread or apple is added, never a whole order at once. -
message = "Added %s to your basket." % itemStores the new value in message. The expression uses the text inside the quotes. -
elif action == "deliver":A delivery has two gates. Nia must be standing at the counter and have the complete current bundle. -
if cell != COUNTER:A matching basket is not enough at a stall. The collection counter has the defined finish position. -
return reject("Deliver from the collection counter.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
var order: Array = shift["orders"][next["order"]]Choose the active bundle using the order index. Never add items for a future bundle early. -
if not exact_bundle(next["basket"], order):Reject a partial bundle without spending a turn or removing goods. The exact match works whichever stall the player visited first. -
return reject("Match the whole order. The basket stays as it was.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
next["basket"].clear()An accepted bundle uses all the goods that it requested. The next customer begins with an empty basket. -
next["order"] += 1Advance the active service index after one handover. The finished check can notice when there are no orders left. -
message = "Bundle accepted."Stores the new value in message. The expression uses the text inside the quotes. -
else:Runs the indented fallback instructions if none of the earlier tests passed. -
return reject("Choose a market action.")Finishes the function and hands its result back to the caller. The expression calls reject with the values in its parentheses. -
next["turns"] += 1Add exactly one turn for a legal action. All rejected actions exit earlier, so they never reach this line. -
if finished(shift, next):Ask whether the proposed state has completed the full queue. One served customer is not a finish if another remains. -
var at_target: bool = next["turns"] <= shift["par"]Compare the finished turn count with the card’s gold target. An equal count qualifies. -
message += " Shift complete. " + ("Gold target met." if at_target else "Keep practising for gold.")Show the same completed shift with the correct gold or practice message. A long route still completes the order. -
return {"ok": true, "state": next, "message": message}Give the interface or planner the exact next state and a message. Positive ok means the action was accepted. -
static func preview(shift: Dictionary, live: Dictionary, action: String) -> String:Defines preview, 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 result := apply_action(shift, live, action)Run the same legality checks as normal play so a preview cannot recommend a forbidden square. -
if not result["ok"]:Ignore failed actions, whether they hit a puddle or attempt a pickup the current order does not need. -
return result["message"]Finishes the function and hands its result back to the caller. The expression looks up the item or key written between the square brackets. -
return "Live cell %s stays put. %s alone would set a copy to %s." % [Describe both positions. Keeping the result as text makes it clear Nia has not yet moved. -
str(live["cell"]), action, str(result["state"]["cell"])]Turns a value into text for a player message. -
static func state_key(state: Dictionary) -> String:Defines state key, 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 basket: Array = state["basket"].duplicate()Make a basket copy before sorting. The interface can keep displaying the actual loading order. -
basket.sort()Sort names into a standard order. Two lists with the same goods get the same text, while an extra copy still changes the key. -
var cell: Vector2i = state["cell"]Creates a variable named cell. 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. -
return "%d,%d|%s|%d" % [cell.x, cell.y, ",".join(basket), state["order"]]Use punctuation to separate tile, basket and order fields. No turn count is needed because every action costs one and gold is only a target. -
static func compare_keys() -> String:Defines compare keys, 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 first := start()Creates a variable named first. The expression calls start with the values in its parentheses. Godot infers the type from the first value. -
first["basket"] = ["apple", "bread"]Stores the new value in first["basket"]. The expression makes a list whose items keep their order. -
var second := start()Creates a variable named second. The expression calls start with the values in its parentheses. Godot infers the type from the first value. -
second["basket"] = ["bread", "apple"]Stores the new value in second["basket"]. The expression makes a list whose items keep their order. -
var same_items := state_key(first) == state_key(second)Two equally loaded baskets on the same square and request should produce identical state keys. -
second["order"] = 1Change which request the second copy serves. The planner should now distinguish these otherwise similar situations. -
var changed_order := state_key(first) != state_key(second)Read whether the important change produced a different key. -
return "Same items: %s. New order changes key: %s.Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes. -
%s" % [Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function. -
str(same_items), str(changed_order), state_key(first)]Turns a value into text for a player message. -
static func find_route(shift: Dictionary, state: Dictionary) -> Array[String]:Defines find route, 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 empty: Array[String] = []Start with no planned actions. The same type lets the function also return an empty route when no solution exists. -
var queue: Array[Dictionary] = [{"state": state, "route": empty}]Each pending entry holds a state and the actions needed to reach it. It begins with the current state. -
var visited := {state_key(state): true}Mark the starting key as seen so a route walking away and returning will not put it back in the queue. -
var index := 0The next position to read starts at the front. It works as a queue without shifting the whole array after each visit. -
while index < queue.size():Keep reading pending entries while there is another one to inspect. New candidates can be appended during the loop. -
var entry: Dictionary = queue[index]Take the next oldest entry. Shorter routes enter the queue before longer ones. -
index += 1Advance to the next pending entry. Appending a child will not change which older entry comes next. -
if finished(shift, entry["state"]):Check whether the route for this entry completes all orders at the counter. -
return entry["route"]The earliest finished entry has a shortest turn count, so it is safe to stop searching. -
for action in ["west", "east", "north", "south", "pick", "deliver"]:Try each legal kind of input from this state, including shopping and handovers. The order of actions breaks ties between equally short routes. -
var result := apply_action(shift, entry["state"], action)Compute the outcome of this candidate action using the live rule without altering the queue item. -
if not result["ok"]:Ignore failed actions, whether they hit a puddle or attempt a pickup the current order does not need. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
var key := state_key(result["state"])Summarise the candidate situation so the planner can compare it to all earlier routes. -
if visited.has(key):The shortest route to this key is already in the queue or handled. Skip the repeated situation. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
visited[key] = trueMark the first visit before inserting a child, so another candidate with the same key cannot create duplicate work. -
var route: Array[String] = entry["route"].duplicate()Copy the old path before adding a move. Other branches keep their own lists of actions. -
route.append(action)Add one legal action to the new child path. -
queue.append({"state": result["state"], "route": route})Put the child behind earlier entries. That preserves breadth-first order. -
return emptyThere was no finished state to return. The interface reports that it has no useful further step.
shift.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 search never ends, inspect whether you mark each new key as visited before putting it in the queue.
Try a change
Change the bottom rain passage in a copy so Nia cannot cross. Ask for a hint and describe why no full plan is returned.