London Market 27 · Make a key for the market state

Market Day London · Lesson 27 of 50 · Intermediate · About 35 min

Nia can load an apple and bread in either order. If she stands on the same square and the same request is active, a planner can treat the two baskets as the same situation.

Watercolour of a London street market after rain, with wet paving reflecting the stall lights.
What you’ll make Compare two routes by their current tile, basket and active order.

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 basket. Keep the live order intact. → Sort and join. Preserve item quantities. → Join the key. Add tile and order.
Copy basket → Sort and join → Join the key
Godot checkpoint window for Make a key for the market state
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson state key, sort, join, copy, dictionary key, duplicate item.

  1. Run the comparison

    Import Lesson 27 and press Compare keys. Find the yes after Same items. Read the key printed underneath and split it after every vertical bar.

    Why it works The result is a short record of where Nia is, what she carries and which order is active.

  2. Capture the position

    Open shift_rules.gd and read state_key. Explain what changes when Nia moves one square west while keeping all the items.

    var cell: Vector2i = state["cell"]

    Why it works Coordinates affect the next legal choices. A planner must remember the position.

  3. Sort a copy of the basket

    Follow duplicate and sort. Try sorting apple and bread in two starting orders on paper. Compare identical results with a basket that contains two apples.

    basket.sort()

    Why it works Sorting gives one order for an equivalent list and keeps duplicates. Copying keeps the real display order intact.

  4. Include the active order

    Find the formatted string. Predict which part changes when the order number increases. Check the New order changes key message.

    return "%d,%d|%s|%d" % [cell.x, cell.y, ",".join(basket), state["order"]]

    Why it works A different order can ask for different items even with the same tile and empty basket.

  5. Leave the gold total outside

    Compare the situation after two harmless steps out and back with the same basket and order. Explain why the second visit would never improve a shortest route.

    Why it works The legal moves from the situation are the same. A search finds the earlier situation first and can keep that shorter route.

  6. Make a key with repeated goods

    Change the comparison helper to use apple, apple and bread in different starting orders. Run, then remove an apple from just one copy and run again.

    Why it works Item quantities matter. A key should stay equal only while the actual basket contents match.

Watch the values change

  1. Compare apple then bread The same items were loaded in another order.
    What you see. Sorting produces identical keys.
  2. Advance the second copy’s order Position and basket are unchanged, but order is now 1.
    What you see. The last part changes, so the keys differ.
  3. Walk back to the same tile No purchase or delivery changed the basket or order.
    What you see. The key returns to the same value despite additional turns.

Predict before you run Should a basket with apple and bread have the same key as a basket with apple, apple and bread?

Reveal the answer

No. The second contains an extra apple. Sorting keeps duplicates, so the strings differ.

Complete checkpoint

Compare keys confirms a matching basket and a different key after the request number changes.

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 27  /  STATE KEYS", 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("keys", "Compare keys", 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 == "keys":
			detail.text = Rules.compare_keys()
			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)]

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
  1. extends ControlThe learning scene uses Godot’s Control node for drawing, labels and input.
  2. 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.
  3. const ORIGIN := Vector2(30, 114)Set the upper-left point of the map, leaving room for the title before the first row.
  4. const CELL := Vector2(88, 71)Keep the tiles at predictable intervals so a coordinate can turn into a screen position.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. var shift: DictionaryStore the fixed map and order card for this attempt.
  10. var state: DictionaryHold the position, basket, turn and current request that can change during the shift.
  11. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  12. var info: LabelDeclares info for later use. A colon followed by a type says which kind of value belongs here.
  13. var board_title: LabelDeclares board_title for later use. A colon followed by a type says which kind of value belongs here.
  14. var detail: LabelDeclares detail for later use. A colon followed by a type says which kind of value belongs here.
  15. 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.
  16. func _ready() -> void:Godot calls this once after the main node enters the scene. It creates the HUD and buttons before reading the data.
  17. 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.
  18. make_label("BRIAR LANE / LESSON 27 / STATE KEYS", Vector2(32, 65), Vector2(890, 24), 16, GOLD)Calls make_label with the values in its parentheses.
  19. 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.
  20. make_button("north", "↑ North", Vector2(617, 221), 96)Calls make_button with the values in its parentheses.
  21. make_button("west", "← West", Vector2(507, 266), 96)Calls make_button with the values in its parentheses.
  22. make_button("south", "↓ South", Vector2(617, 266), 96)Calls make_button with the values in its parentheses.
  23. make_button("east", "→ East", Vector2(727, 266), 96)Calls make_button with the values in its parentheses.
  24. make_button("pick", "Pick item", Vector2(507, 318), 133)Calls make_button with the values in its parentheses.
  25. make_button("deliver", "Deliver", Vector2(650, 318), 133)Calls make_button with the values in its parentheses.
  26. make_button("restart", "Restart shift", Vector2(507, 369), 134)Calls make_button with the values in its parentheses.
  27. make_button("keys", "Compare keys", Vector2(650, 369), 133)Calls make_button with the values in its parentheses.
  28. 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.
  29. 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.
  30. shift = Rules.load_shift()Load the challenge card. A failed file read can show a message before the board tries to draw its data.
  31. if shift.is_empty():Checks shift.is_empty(). The indented instructions below run only if this test passes.
  32. 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.
  33. returnFinishes the function right here. Any later instructions in this function are skipped.
  34. restart()Calls restart with the values in its parentheses.
  35. 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.
  36. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  37. label.text = valueUpdates label.text, which controls the words a player sees. The expression reads value.
  38. label.position = originUpdates label.position, which controls the node's local x and y location. The expression reads origin.
  39. label.size = extentUpdates label.size, which controls the control's width and height. The expression reads extent.
  40. label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow feedback to wrap cleanly inside the width provided, improving readability on a compact canvas.
  41. label.add_theme_font_size_override("font_size", size_px)Calls label.add_theme_font_size_override with the values in its parentheses.
  42. label.add_theme_color_override("font_color", ink)Calls label.add_theme_color_override with the values in its parentheses.
  43. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  44. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  45. 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.
  46. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  47. button.text = titleUpdates button.text, which controls the words a player sees. The expression reads title.
  48. button.position = originUpdates button.position, which controls the node's local x and y location. The expression reads origin.
  49. 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.
  50. button.add_theme_font_size_override("font_size", 16)Calls button.add_theme_font_size_override with the values in its parentheses.
  51. button.pressed.connect(press_action.bind(action))Connect a press to the shared dispatcher and bind the action that this exact button should request.
  52. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  53. buttons[action] = buttonStores the new value in buttons[action]. The expression reads button.
  54. func restart() -> void:Restore the market to the initial player state without rebuilding the level or its controls.
  55. state = Rules.start()Throw away progress from the current attempt and start back at the collection counter.
  56. 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.
  57. info_update("Start at the counter. Pick an item when Nia reaches its tile.")Calls info_update with the values in its parentheses.
  58. 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.
  59. for action in ["north", "east", "south", "west"]:Repeats the indented instructions for each value in ["north", "east", "south", "west"].
  60. 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.
  61. 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.
  62. press_action(action)Calls press_action with the values in its parentheses.
  63. get_viewport().set_input_as_handled()Make this recognised direction event belong to this market action and prevent another handler spending it again.
  64. returnFinishes the function right here. Any later instructions in this function are skipped.
  65. 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.
  66. if action == "restart":Reset is a scene command rather than a counted turn, and it starts only when a valid card has been loaded.
  67. if not shift.is_empty():Checks not shift.is_empty(). The indented instructions below run only if this test passes.
  68. restart()Calls restart with the values in its parentheses.
  69. returnFinishes the function right here. Any later instructions in this function are skipped.
  70. if shift.is_empty():Checks shift.is_empty(). The indented instructions below run only if this test passes.
  71. returnFinishes the function right here. Any later instructions in this function are skipped.
  72. if action == "keys":Checks action == "keys". The indented instructions below run only if this test passes.
  73. detail.text = Rules.compare_keys()Print the key test separately from live play so comparison cannot affect Nia’s order.
  74. returnFinishes the function right here. Any later instructions in this function are skipped.
  75. var result := Rules.apply_action(shift, state, action)Use the pure market rule for an actual player request.
  76. if result["ok"]:The accepted branch is the only place a move, pickup or delivery replaces the browser-visible market state.
  77. state = result["state"]Commit the proposed result after the rule accepts it. That makes this different from a preview or replay.
  78. info_update(result["message"])Update the screen even after a refusal so the player sees a clear reason without losing progress.
  79. func info_update(message: String) -> void:Read the current state and put useful values into the display before requesting a redraw.
  80. 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.
  81. var count: int = state["order"]Use the zero-based order index to find the next bundle. The displayed order number will start at one.
  82. 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.
  83. if not Rules.finished(shift, state):A completed shift has no further order index. Check before reading the array.
  84. 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.
  85. 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.
  86. info.text = "ORDER %d / %d · %sUpdates info.text, which controls the words a player sees. The expression uses the text inside the quotes.
  87. BASKET %d / 3 · %sContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  88. 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.
  89. mini(count + 1, shift["orders"].size()), shift["orders"].size(), order_text,Calls mini with the values in its parentheses.
  90. basket.size(), contents, state["turns"], shift["par"]]Counts the items in this collection.
  91. status.text = messageUpdates status.text, which controls the words a player sees. The expression reads message.
  92. queue_redraw()Tell Godot the panel needs repainting after a move or status update.
  93. func _draw() -> void:Paint the board from the current shift and state. This visual step never spends a turn.
  94. draw_rect(Rect2(0, 0, 960, 540), INK)Paints a rectangle at the given position and size.
  95. draw_rect(Rect2(482, 93, 2, 420), Color("#4f7776"))Paints a rectangle at the given position and size.
  96. 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.
  97. returnFinishes the function right here. Any later instructions in this function are skipped.
  98. var font := ThemeDB.fallback_fontCreates a variable named font. The expression reads ThemeDB.fallback_font. Godot infers the type from the first value.
  99. for y in range(4):Visit each horizontal row. The inner loop handles every column.
  100. for x in range(5):Make one tile for every x position across the current row.
  101. 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.
  102. var corner := ORIGIN + Vector2(cell) * CELLTranslate the grid coordinates into pixels using the origin and spacing.
  103. 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.
  104. 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.
  105. if Rules.blocked(shift, cell):Use the same closure check as movement, so wet squares look as impassable as they behave.
  106. fill = Color("#6b8390")Stores the new value in fill. The expression builds a colour from these values.
  107. tile = "Closed"Stores the new value in tile. The expression uses the text inside the quotes.
  108. elif Rules.ITEMS.has(Rules.marker(shift, cell)):Use the stall marker to choose a label and a distinct tile style.
  109. fill = Color("#d9a77a")Stores the new value in fill. The expression builds a colour from these values.
  110. 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.
  111. elif cell == Rules.COUNTER:Draw the finish location with its collection counter label and green fill.
  112. fill = Color("#8bc5ac")Stores the new value in fill. The expression builds a colour from these values.
  113. tile = "Counter"Stores the new value in tile. The expression uses the text inside the quotes.
  114. draw_rect(Rect2(corner, CELL - Vector2(4, 4)), fill)Paints a rectangle at the given position and size.
  115. 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.
  116. if state["cell"] == cell:Draw Nia’s marker only on the tile that matches her current coordinates.
  117. draw_circle(corner + Vector2(42, 45), 14, Color("#39416b"))Paints a filled circle or outline in this node's local coordinates.
  118. 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
  1. extends RefCountedThis file holds the market rules without needing a drawing node. The live controls, preview and planner can call the same class.
  2. const CAPACITY := 3Nia can carry at most three items. Every pickup passes through this same limit.
  3. 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.
  4. "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.
  5. 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.
  6. const COUNTER := Vector2i(4, 3)The training map always starts at its lower right collection counter. Coordinates count from zero.
  7. 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.
  8. 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.
  9. if file == null:Stop immediately when the file could not be opened. There is no usable text to parse.
  10. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  11. 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.
  12. 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.
  13. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  14. 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.
  15. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  16. for row in loaded["rows"]:Inspect every row in the card before the screen or movement code uses a square from it.
  17. 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.
  18. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  19. 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.
  20. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  21. return loadedHand the card back only after the validation gates. A loaded card can now be shared by drawing and rules.
  22. 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.
  23. 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.
  24. 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.
  25. 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.
  26. 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.
  27. var remaining := basket.duplicate()Copy the basket before matching. Removing items from the temporary list must not remove them from Nia’s actual basket.
  28. for item in order:Match each requested copy one at a time. If an order repeats apple, this loop checks for two available copies.
  29. if not remaining.has(item):A missing item makes the bundle fail immediately. The original basket remains safe while this temporary list changes.
  30. return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false.
  31. remaining.erase(item)Remove the first matching copy from the temporary list. An order entry can only be satisfied once.
  32. return remaining.is_empty()A match also requires no surplus items. If the list contains an extra good, the order is not exact.
  33. 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.
  34. var row: String = shift["rows"][cell.y]Choose the text row with y before looking for a character horizontally.
  35. 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.
  36. 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.
  37. return marker(shift, cell) == "#"Only # is a rain closure. A plain dot and all stall or counter symbols remain walkable.
  38. 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.
  39. return {"ok": false, "message": message}False tells the screen not to replace the live state. The readable message still explains what happened.
  40. 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.
  41. if finished(shift, state):Protect the finished screen from extra moves. Restart is placed in the interface rather than treated as a market turn.
  42. 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.
  43. var next := state.duplicate(true)Make an independent dictionary and basket before any changes. Preview and route search need this copy.
  44. var cell: Vector2i = next["cell"]Read Nia’s current grid coordinates once. Picking or delivering can now test the current square.
  45. var message := ""Creates a variable named message. The expression uses the text inside the quotes. Godot infers the type from the first value.
  46. if INCREMENT.has(action):Directions use the movement dictionary. Pickup and delivery go through separate checks further down.
  47. 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.
  48. 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.
  49. 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.
  50. 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.
  51. if blocked(shift, destination):Look up the proposed cell on the map. Refusing the rain tile here avoids changing Nia or the turn count.
  52. 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.
  53. next["cell"] = destinationStore a legal move in the proposed state. The caller still decides whether to keep that result.
  54. 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.
  55. elif action == "pick":The Pick item button attempts to take the good sold on Nia’s current square.
  56. var symbol := marker(shift, cell)Read the map symbol below Nia. A, B and F select items, while a walkable dot is empty.
  57. if not ITEMS.has(symbol):If Nia is away from a mapped stall, refuse the attempt with a clear prompt.
  58. 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.
  59. if next["basket"].size() >= CAPACITY:A basket full of three items cannot accept a fourth. Refusal happens before any change.
  60. 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.
  61. 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.
  62. var order: Array = shift["orders"][next["order"]]Choose the active bundle using the order index. Never add items for a future bundle early.
  63. 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.
  64. 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.
  65. next["basket"].append(item)Take the accepted item in the copy only. One bread or apple is added, never a whole order at once.
  66. message = "Added %s to your basket." % itemStores the new value in message. The expression uses the text inside the quotes.
  67. elif action == "deliver":A delivery has two gates. Nia must be standing at the counter and have the complete current bundle.
  68. if cell != COUNTER:A matching basket is not enough at a stall. The collection counter has the defined finish position.
  69. 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.
  70. var order: Array = shift["orders"][next["order"]]Choose the active bundle using the order index. Never add items for a future bundle early.
  71. 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.
  72. 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.
  73. next["basket"].clear()An accepted bundle uses all the goods that it requested. The next customer begins with an empty basket.
  74. next["order"] += 1Advance the active service index after one handover. The finished check can notice when there are no orders left.
  75. message = "Bundle accepted."Stores the new value in message. The expression uses the text inside the quotes.
  76. else:Runs the indented fallback instructions if none of the earlier tests passed.
  77. 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.
  78. next["turns"] += 1Add exactly one turn for a legal action. All rejected actions exit earlier, so they never reach this line.
  79. if finished(shift, next):Ask whether the proposed state has completed the full queue. One served customer is not a finish if another remains.
  80. var at_target: bool = next["turns"] <= shift["par"]Compare the finished turn count with the card’s gold target. An equal count qualifies.
  81. 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.
  82. 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.
  83. 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.
  84. var result := apply_action(shift, live, action)Run the same legality checks as normal play so a preview cannot recommend a forbidden square.
  85. if not result["ok"]:Ignore failed actions, whether they hit a puddle or attempt a pickup the current order does not need.
  86. 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.
  87. 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.
  88. str(live["cell"]), action, str(result["state"]["cell"])]Turns a value into text for a player message.
  89. 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.
  90. var basket: Array = state["basket"].duplicate()Make a basket copy before sorting. The interface can keep displaying the actual loading order.
  91. 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.
  92. 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.
  93. 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.
  94. 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.
  95. 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.
  96. first["basket"] = ["apple", "bread"]Stores the new value in first["basket"]. The expression makes a list whose items keep their order.
  97. 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.
  98. second["basket"] = ["bread", "apple"]Stores the new value in second["basket"]. The expression makes a list whose items keep their order.
  99. var same_items := state_key(first) == state_key(second)Two equally loaded baskets on the same square and request should produce identical state keys.
  100. second["order"] = 1Change which request the second copy serves. The planner should now distinguish these otherwise similar situations.
  101. var changed_order := state_key(first) != state_key(second)Read whether the important change produced a different key.
  102. 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.
  103. %s" % [Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  104. str(same_items), str(changed_order), state_key(first)]Turns a value into text for a player message.

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 two equivalent baskets get different keys, make sure you sort the copied array before joining it.

Try a change

Add a rule on paper that closes a tile for one turn each time it rains. Decide which new state detail your key needs and why.