London Market 22 · Load a shift from a JSON file

Market Day London · Lesson 22 of 50 · Intermediate · About 30 min

A second shift should not mean a second copy of the movement code. Put the card into its own file so you can make a new request while keeping the same buttons.

Watercolour of a London street market after rain, with wet paving reflecting the stall lights.
What you’ll make Load text into a dictionary, check its shape and draw the shift from the result.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/21 when the lesson builds on prior work, or copy the checkpoints/22 folder to try this lesson on its own. Read the file names in the steps before editing.

Open file. Read from res://. → Parse text. Make project values. → Check contents. Draw a valid shift.
Open file → Parse text → Check contents
Godot checkpoint window for Load a shift from a JSON file
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson JSON, FileAccess, res://, protected access, validation, fallback.

  1. Open the files together

    Import the Lesson 22 folder and open shift.json beside shift_rules.gd in the FileSystem panel. Check that both are under res://. Run once and compare the map and order with Lesson 21.

    Why it works Separating data and rules is safest when the first file describes the same shift.

  2. Open the card for reading

    In shift_rules.gd find load_shift. Follow the first two lines. They open the file from the project folder and return an empty dictionary if it cannot be opened.

    var file := FileAccess.open("res://shift.json", FileAccess.READ)

    Why it works A file location can be wrong. The empty dictionary lets the screen give a clear error without reading a missing file.

  3. Turn text into data

    Read the JSON.parse_string call. Follow get_as_text through its brackets. The card is first read as text, then interpreted for lists, keys and numbers.

    var loaded: Variant = JSON.parse_string(file.get_as_text())

    Why it works Parse turns the contents into values that the move and order code can read.

  4. Check the type and map

    Read the guards before return loaded. List an example of three failures that would produce an empty result. Use a missing orders key, a row list with three entries or any row with four characters.

    if not loaded.get("rows") is Array or loaded["rows"].size() != 4:

    Why it works The rest of the training board expects four rows and five columns. Reject a card that cannot fit that shape.

  5. Change one request

    Open shift.json in a text editor if your Godot setup does not edit JSON in the Script panel. Replace bread with flower inside the first order. Keep the quotation marks. Save, switch to Godot and press F5.

    Why it works The same GDScript now expects a new bundle. The card controls the contents of the order line.

  6. Deliberately break and repair

    On a copy, remove the final closing curly brace. Save and run from Godot. Read the status message, add the brace back and rerun.

    if shift.is_empty():

    Why it works Testing a failure shows the reason for checking parsed content before drawing or acting on it.

Watch the values change

  1. Read matching card shift.json contains four text rows and an orders array.
    What you see. The old market appears through the file reader.
  2. Replace bread with flower The saved order array is now apple and flower.
    What you see. The HUD shows the new request without an edit to GDScript.
  3. Leave out the final brace The JSON text cannot form a dictionary.
    What you see. The screen says the shift file could not be opened.

Predict before you run What happens to Nia’s movement code when you edit one item in shift.json?

Reveal the answer

The movement code is unchanged. After a fresh run, it uses the same map but the new order.

Complete checkpoint

The market launches from shift.json and the HUD shows the file’s apple-and-bread request.

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 22  /  READ A FILE", 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)
	
	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
	
	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}

shift.json

{
  "name": "Morning order",
  "group": "Training",
  "par": 17,
  "rows": [
    "A...F",
    ".....",
    ".....",
    "B...C"
  ],
  "orders": [
    [
      "apple",
      "bread"
    ]
  ]
}

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 22 / READ A FILE", 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. 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.
  28. 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.
  29. shift = Rules.load_shift()Load the challenge card. A failed file read can show a message before the board tries to draw its data.
  30. if shift.is_empty():Checks shift.is_empty(). The indented instructions below run only if this test passes.
  31. 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.
  32. returnFinishes the function right here. Any later instructions in this function are skipped.
  33. restart()Calls restart with the values in its parentheses.
  34. 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.
  35. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  36. label.text = valueUpdates label.text, which controls the words a player sees. The expression reads value.
  37. label.position = originUpdates label.position, which controls the node's local x and y location. The expression reads origin.
  38. label.size = extentUpdates label.size, which controls the control's width and height. The expression reads extent.
  39. label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow feedback to wrap cleanly inside the width provided, improving readability on a compact canvas.
  40. label.add_theme_font_size_override("font_size", size_px)Calls label.add_theme_font_size_override with the values in its parentheses.
  41. label.add_theme_color_override("font_color", ink)Calls label.add_theme_color_override with the values in its parentheses.
  42. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  43. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  44. 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.
  45. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  46. button.text = titleUpdates button.text, which controls the words a player sees. The expression reads title.
  47. button.position = originUpdates button.position, which controls the node's local x and y location. The expression reads origin.
  48. 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.
  49. button.add_theme_font_size_override("font_size", 16)Calls button.add_theme_font_size_override with the values in its parentheses.
  50. button.pressed.connect(press_action.bind(action))Connect a press to the shared dispatcher and bind the action that this exact button should request.
  51. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  52. buttons[action] = buttonStores the new value in buttons[action]. The expression reads button.
  53. func restart() -> void:Restore the market to the initial player state without rebuilding the level or its controls.
  54. state = Rules.start()Throw away progress from the current attempt and start back at the collection counter.
  55. 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.
  56. info_update("Start at the counter. Pick an item when Nia reaches its tile.")Calls info_update with the values in its parentheses.
  57. 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.
  58. for action in ["north", "east", "south", "west"]:Repeats the indented instructions for each value in ["north", "east", "south", "west"].
  59. 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.
  60. 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.
  61. press_action(action)Calls press_action with the values in its parentheses.
  62. get_viewport().set_input_as_handled()Make this recognised direction event belong to this market action and prevent another handler spending it again.
  63. returnFinishes the function right here. Any later instructions in this function are skipped.
  64. 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.
  65. if action == "restart":Reset is a scene command rather than a counted turn, and it starts only when a valid card has been loaded.
  66. if not shift.is_empty():Checks not shift.is_empty(). The indented instructions below run only if this test passes.
  67. restart()Calls restart with the values in its parentheses.
  68. returnFinishes the function right here. Any later instructions in this function are skipped.
  69. if shift.is_empty():Checks shift.is_empty(). The indented instructions below run only if this test passes.
  70. returnFinishes the function right here. Any later instructions in this function are skipped.
  71. var result := Rules.apply_action(shift, state, action)Use the pure market rule for an actual player request.
  72. if result["ok"]:The accepted branch is the only place a move, pickup or delivery replaces the browser-visible market state.
  73. state = result["state"]Commit the proposed result after the rule accepts it. That makes this different from a preview or replay.
  74. info_update(result["message"])Update the screen even after a refusal so the player sees a clear reason without losing progress.
  75. func info_update(message: String) -> void:Read the current state and put useful values into the display before requesting a redraw.
  76. 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.
  77. var count: int = state["order"]Use the zero-based order index to find the next bundle. The displayed order number will start at one.
  78. 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.
  79. if not Rules.finished(shift, state):A completed shift has no further order index. Check before reading the array.
  80. 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.
  81. 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.
  82. info.text = "ORDER %d / %d · %sUpdates info.text, which controls the words a player sees. The expression uses the text inside the quotes.
  83. BASKET %d / 3 · %sContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  84. 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.
  85. mini(count + 1, shift["orders"].size()), shift["orders"].size(), order_text,Calls mini with the values in its parentheses.
  86. basket.size(), contents, state["turns"], shift["par"]]Counts the items in this collection.
  87. status.text = messageUpdates status.text, which controls the words a player sees. The expression reads message.
  88. queue_redraw()Tell Godot the panel needs repainting after a move or status update.
  89. func _draw() -> void:Paint the board from the current shift and state. This visual step never spends a turn.
  90. draw_rect(Rect2(0, 0, 960, 540), INK)Paints a rectangle at the given position and size.
  91. draw_rect(Rect2(482, 93, 2, 420), Color("#4f7776"))Paints a rectangle at the given position and size.
  92. 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.
  93. returnFinishes the function right here. Any later instructions in this function are skipped.
  94. var font := ThemeDB.fallback_fontCreates a variable named font. The expression reads ThemeDB.fallback_font. Godot infers the type from the first value.
  95. for y in range(4):Visit each horizontal row. The inner loop handles every column.
  96. for x in range(5):Make one tile for every x position across the current row.
  97. 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.
  98. var corner := ORIGIN + Vector2(cell) * CELLTranslate the grid coordinates into pixels using the origin and spacing.
  99. 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.
  100. 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.
  101. if Rules.blocked(shift, cell):Use the same closure check as movement, so wet squares look as impassable as they behave.
  102. fill = Color("#6b8390")Stores the new value in fill. The expression builds a colour from these values.
  103. tile = "Closed"Stores the new value in tile. The expression uses the text inside the quotes.
  104. elif Rules.ITEMS.has(Rules.marker(shift, cell)):Use the stall marker to choose a label and a distinct tile style.
  105. fill = Color("#d9a77a")Stores the new value in fill. The expression builds a colour from these values.
  106. 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.
  107. elif cell == Rules.COUNTER:Draw the finish location with its collection counter label and green fill.
  108. fill = Color("#8bc5ac")Stores the new value in fill. The expression builds a colour from these values.
  109. tile = "Counter"Stores the new value in tile. The expression uses the text inside the quotes.
  110. draw_rect(Rect2(corner, CELL - Vector2(4, 4)), fill)Paints a rectangle at the given position and size.
  111. 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.
  112. if state["cell"] == cell:Draw Nia’s marker only on the tile that matches her current coordinates.
  113. draw_circle(corner + Vector2(42, 45), 14, Color("#39416b"))Paints a filled circle or outline in this node's local coordinates.
  114. 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.

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

An empty screen with the shift warning often means a missing quote, comma or closing bracket. First undo the last edit and run again.

Try a change

Rename a copy of shift.json, run once, and then restore its name. Explain how the file-open guard differs from the parse guard.