Cabin Crew 22 · Load a passenger manifest from JSON

Cabin Crew Express · Lesson 22 of 50 · Intermediate · About 27 min

An airline dispatcher sends Ari a manifest before take-off. The same cabin routine needs to work on a flight with a different set of orders.

A level view along the aisle of a regional aircraft, with two navy seats on each side.
What you’ll make Change passenger requests in a data file while the delivery rules stay reusable.

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. Use the project-relative path. → Read bytes. Collect the file contents as text. → Parse JSON. Return a Godot value. → Validate. Require a dictionary of requests.
Open file → Read bytes → Parse JSON → Validate
Godot checkpoint window for Load a passenger manifest from JSON
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson JSON, data file, FileAccess, parse_string, Variant, Dictionary, guard.

  1. Open the training cabin

    Unzip the course project and open Godot 4.7.2. In Project Manager choose Import, select the project.godot file inside checkpoints/22, then choose Edit. Click the Run Project triangle at the top right or press F5.

    Why it works A fresh checkpoint opens the exact version for this lesson. Make a copy before changing any code so you can compare the result.

  2. Find the manifest

    In FileSystem locate mission.json. If Godot opens it externally, open the file in a plain text editor. Identify the four braces around the full document and its requests block.

    "requests": {
        "2A": "Water",
        "2D": "Blanket"
      }

    Why it works JSON stores named information with quoted keys, quoted text values, braces and separating commas. Gameplay can read a new manifest without new delivery rules.

  3. Find the file in the project

    Back in Godot, double-click cabin_rules.gd and find load_mission. Compare its res:// path against the file name shown in FileSystem.

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

    Why it works res:// starts at the Godot project. READ opens the file so the game can inspect it without changing the original.

  4. Read text and decode it

    Read get_as_text and JSON.parse_string together. Make one annotation above each line in your own checkpoint copy so you remember which one reads the letters and which one turns them into values.

    var data: Variant = JSON.parse_string(text)

    Why it works A text file arrives as text. The parser understands the JSON punctuation and produces a Godot value. Variant can hold any type or null if decoding fails.

  5. Check that it contains requests

    Look at the two consecutive if guards. Temporarily rename requests to bookings in the JSON file. Save before running the project, observe the message, and put the name back.

    if not (data.get("requests") is Dictionary):

    Why it works The first guard catches a wrong top-level type. The second checks for a dictionary under requests, so the cabin can show a readable error instead of accessing a missing key.

  6. Dispatch a different request

    With the file repaired, change 2D's item from Blanket to Meal. Save, rerun the game and check both the manifest and the text on seat 2D. Load the meal and serve it at row 2.

    Why it works Both the labels and the delivery rule read the same manifest. When the file changes, they agree on the requested item.

Watch the values change

  1. Run with the original manifest 2D requests Blanket
    What you see. The row and side panel agree.
  2. Rename requests No enabled request dictionary
    What you see. A readable file error replaces the main game.
  3. Restore requests and edit 2D 2D requests Meal
    What you see. A meal goes to the updated seat.

Predict before you run What should happen after a missing comma separates two seat requests?

Reveal the answer

JSON parsing fails. The checkpoint shows its manifest error. Open the Godot debugger if you need the parser's own message.

Complete checkpoint

A correctly edited JSON manifest produces different passenger requests. An invalid requests field produces a readable error.

main.gd

extends Control

const Rules = preload("res://cabin_rules.gd")
const SEATS = ["A", "B", "C", "D"]

var mission: Dictionary
var state: Dictionary
var status: Label
var manifest: Label
var summary: Label
var seats: Dictionary = {}
var stripe: ColorRect


func _ready() -> void:
	make_panel(Color("#14283f"), Rect2(0, 0, 960, 540))
	make_label("CABIN CREW EXPRESS", Rect2(28, 18, 450, 36), 27)
	make_label("TRAINING FLIGHT  •  CHECKPOINT 22", Rect2(29, 57, 510, 27), 14)
	mission = Rules.load_mission()
	if mission.is_empty():
		make_label("Could not read mission.json. Check its braces and commas.", Rect2(28, 140, 880, 50), 22)
		return
	state = Rules.initial_state(mission)
	make_panel(Color("#203a53"), Rect2(28, 98, 522, 332))
	make_panel(Color("#203a53"), Rect2(568, 98, 364, 332))
	make_label("Galley", Rect2(254, 111, 90, 35), 16)

	var row_stripe := make_panel(Color("#52728a"), Rect2(256, 150, 67, 245))
	row_stripe.mouse_filter = Control.MOUSE_FILTER_IGNORE
	stripe = make_panel(Color("#ffd386"), Rect2(258, 158, 63, 18))
	stripe.mouse_filter = Control.MOUSE_FILTER_IGNORE

	var lefts := [46, 150, 335, 439]
	for row in range(1, int(mission["rows"]) + 1):
		var top := 157 + row * 65
		make_label(str(row), Rect2(276, top, 28, 42), 19)
		for col in range(SEATS.size()):
			var seat_id := str(row) + str(SEATS[col])
			var button := make_button(seat_id, Rect2(lefts[col], top, 92, 42), "serve:" + seat_id)
			seats[seat_id] = button

	make_label("Galley supplies", Rect2(585, 111, 310, 25), 19)
	for slot in range(Rules.SUPPLIES.size()):
		var item: String = Rules.SUPPLIES[slot]
		make_button(item, Rect2(585 + slot * 108, 146, 100, 39), "load:" + item)
	var up := make_button("Earlier row", Rect2(585, 201, 100, 40), "up")
	make_button("Later row", Rect2(693, 201, 100, 40), "down")
	make_button("Restart", Rect2(801, 201, 100, 40), "reset")


	manifest = make_label("", Rect2(585, 314, 305, 105), 15)
	summary = make_label("", Rect2(29, 438, 900, 30), 19)
	status = make_label("", Rect2(29, 477, 900, 56), 17)
	status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	up.grab_focus()
	refresh("Train as Ari. Load items at the galley, then choose seats from the aisle.")


func make_panel(shade: Color, box: Rect2) -> ColorRect:
	var card := ColorRect.new()
	card.color = shade
	card.position = box.position
	card.size = box.size
	add_child(card)
	return card


func make_label(copy: String, box: Rect2, font_size: int) -> Label:
	var label := Label.new()
	label.text = copy
	label.position = box.position
	label.size = box.size
	label.add_theme_font_size_override("font_size", font_size)
	add_child(label)
	return label


func make_button(copy: String, box: Rect2, action: String) -> Button:
	var button := Button.new()
	button.text = copy
	button.position = box.position
	button.size = box.size
	button.add_theme_font_size_override("font_size", 14)
	button.pressed.connect(command.bind(action))
	add_child(button)
	return button


func _input(event: InputEvent) -> void:
	if mission.is_empty() or not (event is InputEventKey) or not event.pressed or event.echo:
		return
	if event.keycode == KEY_UP or event.keycode == KEY_DOWN:
		command("up" if event.keycode == KEY_UP else "down")
		get_viewport().set_input_as_handled()


func command(action: String) -> void:
	if action == "reset":
		state = Rules.initial_state(mission)
		refresh("Cabin restarted. Check the manifest before your first move.")
		return
	var result := Rules.apply_action(mission, state, action)
	refresh(result["message"])


func refresh(message: String) -> void:
	stripe.position.y = 129 + int(state["row"]) * 65
	if state["row"] > 0:
		stripe.position.y += 34
	for seat_id in seats:
		var button: Button = seats[seat_id]
		var requested: String = mission["requests"].get(seat_id, "")
		button.text = seat_id if requested == "" else "%s %s" % [seat_id, requested]
		if state["served"].has(seat_id):
			button.text = "%s done" % seat_id
	var row_name := "Galley" if state["row"] == 0 else "Row %d" % state["row"]
	var carry := ", ".join(state["cart"])
	if carry == "":
		carry = "empty"
	var rows: Array[String] = []
	for seat_id in mission["requests"]:
		rows.append("%s asks for %s" % [seat_id, mission["requests"][seat_id]])
	manifest.text = "
".join(rows)
	summary.text = "%s   •   Cart: %s   •   %d/%d served   •   Turns: %d" % [
		row_name, carry, state["served"].size(), mission["requests"].size(), state["turns"]]
	status.text = message

cabin_rules.gd

extends RefCounted

const SUPPLIES = ["Water", "Meal", "Blanket"]
const CAPACITY = 2

static func load_mission() -> Dictionary:
	var file := FileAccess.open("res://mission.json", FileAccess.READ)
	if file == null:
		return {}
	var text := file.get_as_text()
	var data: Variant = JSON.parse_string(text)
	if not (data is Dictionary):
		return {}
	if not (data.get("requests") is Dictionary):
		return {}
	return data

static func seat_row(seat_id: String) -> int:
	return seat_id.substr(0, seat_id.length() - 1).to_int()


static func initial_state(mission: Dictionary) -> Dictionary:
	return {"row": 0, "cart": [], "served": [], "turns": 0, "clear": mission["blocked_row"] < 0}


static func is_finished(mission: Dictionary, state: Dictionary) -> bool:
	return state["served"].size() == mission["requests"].size()

static func apply_action(mission: Dictionary, state: Dictionary, action: String) -> Dictionary:
	if is_finished(mission, state):
		return {"accepted": false, "message": "Service is already complete."}
	var message := ""
	if action == "up" or action == "down":
		var step := -1 if action == "up" else 1
		var destination: int = state["row"] + step
		if destination < 0 or destination > int(mission["rows"]):
			return {"accepted": false, "message": "This is the end of the aisle."}
		state["row"] = destination
		message = "At the galley." if destination == 0 else "Ari reached row %d." % destination
	elif action.begins_with("load:"):
		if state["row"] != 0:
			return {"accepted": false, "message": "Return to the galley to load supplies."}
		if state["cart"].size() >= CAPACITY:
			return {"accepted": false, "message": "The cart already holds two items."}
		var item := action.get_slice(":", 1)
		if not SUPPLIES.has(item):
			return {"accepted": false, "message": "That item is not stocked."}
		state["cart"].append(item)
		message = "Loaded %s." % item
	elif action.begins_with("serve:"):
		var seat_id := action.get_slice(":", 1)
		var requests: Dictionary = mission["requests"]
		if not requests.has(seat_id) or state["served"].has(seat_id):
			return {"accepted": false, "message": "There is no open request at %s." % seat_id}
		if seat_row(seat_id) != state["row"]:
			return {"accepted": false, "message": "Move beside row %d first." % seat_row(seat_id)}
		var item: String = requests[seat_id]
		if not state["cart"].has(item):
			return {"accepted": false, "message": "%s needs %s. Check your cart." % [seat_id, item]}
		state["cart"].erase(item)
		state["served"].append(seat_id)
		message = "Delivered %s to %s." % [item, seat_id]
	else:
		return {"accepted": false, "message": "Choose a service action."}

	state["turns"] += 1
	if is_finished(mission, state):
		message += " Cabin ready!"
	return {"accepted": true, "message": message, "state": state}

mission.json

{
  "rows": 3,
  "budget": 16,
  "blocked_row": -1,
  "requests": {
    "2A": "Water",
    "2D": "Blanket"
  },
  "priority": ""
}

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 ControlMake the scene a Godot Control so it can hold and position interface nodes.
  2. const Rules = preload("res://cabin_rules.gd")Load the script that contains the cabin rules when this scene is parsed.
  3. const SEATS = ["A", "B", "C", "D"]Give the four seat columns letter names. A and B sit left of the aisle, while C and D sit right.
  4. var mission: DictionaryKeep the layout and request manifest separate from the state created while playing.
  5. var state: DictionaryStore changes to position, turn count, supplies, delivery flags and the obstruction.
  6. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  7. var manifest: LabelDeclares manifest for later use. A colon followed by a type says which kind of value belongs here.
  8. var summary: LabelDeclares summary for later use. A colon followed by a type says which kind of value belongs here.
  9. var seats: Dictionary = {}Creates a variable named seats. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold.
  10. var stripe: ColorRectDeclares stripe for later use. A colon followed by a type says which kind of value belongs here.
  11. func _ready() -> void:Godot calls this once after the scene and its children are ready. Use it to set up the room and connect controls.
  12. make_panel(Color("#14283f"), Rect2(0, 0, 960, 540))Calls make_panel with the values in its parentheses.
  13. make_label("CABIN CREW EXPRESS", Rect2(28, 18, 450, 36), 27)Calls make_label with the values in its parentheses.
  14. make_label("TRAINING FLIGHT • CHECKPOINT 22", Rect2(29, 57, 510, 27), 14)Calls make_label with the values in its parentheses.
  15. mission = Rules.load_mission()Read all training flight data before creating any seat buttons.
  16. if mission.is_empty():Show a tiny error screen if the manifest could not be loaded or did not pass the data guards.
  17. make_label("Could not read mission.json. Check its braces and commas.", Rect2(28, 140, 880, 50), 22)Calls make_label with the values in its parentheses.
  18. returnFinishes the function right here. Any later instructions in this function are skipped.
  19. state = Rules.initial_state(mission)Give this play session a fresh copy of the starting state.
  20. make_panel(Color("#203a53"), Rect2(28, 98, 522, 332))Calls make_panel with the values in its parentheses.
  21. make_panel(Color("#203a53"), Rect2(568, 98, 364, 332))Calls make_panel with the values in its parentheses.
  22. make_label("Galley", Rect2(254, 111, 90, 35), 16)Calls make_label with the values in its parentheses.
  23. var row_stripe := make_panel(Color("#52728a"), Rect2(256, 150, 67, 245))Creates a variable named row_stripe. The expression calls make_panel with the values in its parentheses. Godot infers the type from the first value.
  24. row_stripe.mouse_filter = Control.MOUSE_FILTER_IGNOREUpdates row_stripe.mouse_filter, which controls how this control participates in pointer and touch input. The expression reads Control.MOUSE_FILTER_IGNORE.
  25. stripe = make_panel(Color("#ffd386"), Rect2(258, 158, 63, 18))Stores the new value in stripe. The expression calls make_panel with the values in its parentheses.
  26. stripe.mouse_filter = Control.MOUSE_FILTER_IGNOREUpdates stripe.mouse_filter, which controls how this control participates in pointer and touch input. The expression reads Control.MOUSE_FILTER_IGNORE.
  27. var lefts := [46, 150, 335, 439]Leave space after the second seat for the aisle between the two sides.
  28. for row in range(1, int(mission["rows"]) + 1):Make one row per passenger row. range excludes its upper bound, so add one to include the last row.
  29. var top := 157 + row * 65Creates a variable named top. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  30. make_label(str(row), Rect2(276, top, 28, 42), 19)Calls make_label with the values in its parentheses.
  31. for col in range(SEATS.size()):Repeats the indented instructions for each value in range(SEATS.size()).
  32. var seat_id := str(row) + str(SEATS[col])Join row number and column name to form a stable passenger ID such as 2A.
  33. var button := make_button(seat_id, Rect2(lefts[col], top, 92, 42), "serve:" + seat_id)Creates a variable named button. The expression calls make_button with the values in its parentheses. Godot infers the type from the first value.
  34. seats[seat_id] = buttonIndex a button by seat name so refresh can later change its label independently.
  35. make_label("Galley supplies", Rect2(585, 111, 310, 25), 19)Calls make_label with the values in its parentheses.
  36. for slot in range(Rules.SUPPLIES.size()):Repeats the indented instructions for each value in range(Rules.SUPPLIES.size()).
  37. var item: String = Rules.SUPPLIES[slot]Read each stock label from the list used by the rules so button names and commands agree.
  38. make_button(item, Rect2(585 + slot * 108, 146, 100, 39), "load:" + item)Calls make_button with the values in its parentheses.
  39. var up := make_button("Earlier row", Rect2(585, 201, 100, 40), "up")Creates a variable named up. The expression calls make_button with the values in its parentheses. Godot infers the type from the first value.
  40. make_button("Later row", Rect2(693, 201, 100, 40), "down")Calls make_button with the values in its parentheses.
  41. make_button("Restart", Rect2(801, 201, 100, 40), "reset")Calls make_button with the values in its parentheses.
  42. manifest = make_label("", Rect2(585, 314, 305, 105), 15)Stores the new value in manifest. The expression calls make_label with the values in its parentheses.
  43. summary = make_label("", Rect2(29, 438, 900, 30), 19)Stores the new value in summary. The expression calls make_label with the values in its parentheses.
  44. status = make_label("", Rect2(29, 477, 900, 56), 17)Stores the new value in status. The expression calls make_label with the values in its parentheses.
  45. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow a long message to wrap without hiding the end of it.
  46. up.grab_focus()Make the first navigation button ready for keyboard input.
  47. refresh("Train as Ari. Load items at the galley, then choose seats from the aisle.")Calls refresh with the values in its parentheses.
  48. func make_panel(shade: Color, box: Rect2) -> ColorRect:Defines make panel, 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.
  49. var card := ColorRect.new()Creates a variable named card. The expression creates a new ColorRect object. Godot infers the type from the first value.
  50. card.color = shadeStores the new value in card.color. The expression reads shade.
  51. card.position = box.positionUpdates card.position, which controls the node's local x and y location. The expression reads box.position.
  52. card.size = box.sizeUpdates card.size, which controls the control's width and height. The expression reads box.size.
  53. add_child(card)Adds the new node to the scene tree so that Godot can run and draw it.
  54. return cardFinishes the function and hands its result back to the caller. The expression reads card.
  55. func make_label(copy: String, box: Rect2, font_size: int) -> Label:Defines make label, 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.
  56. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  57. label.text = copyUpdates label.text, which controls the words a player sees. The expression reads copy.
  58. label.position = box.positionUpdates label.position, which controls the node's local x and y location. The expression reads box.position.
  59. label.size = box.sizeUpdates label.size, which controls the control's width and height. The expression reads box.size.
  60. label.add_theme_font_size_override("font_size", font_size)Calls label.add_theme_font_size_override with the values in its parentheses.
  61. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  62. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  63. func make_button(copy: String, box: Rect2, action: String) -> Button:Defines make button, 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.
  64. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  65. button.text = copyUpdates button.text, which controls the words a player sees. The expression reads copy.
  66. button.position = box.positionUpdates button.position, which controls the node's local x and y location. The expression reads box.position.
  67. button.size = box.sizeUpdates button.size, which controls the control's width and height. The expression reads box.size.
  68. button.add_theme_font_size_override("font_size", 14)Calls button.add_theme_font_size_override with the values in its parentheses.
  69. button.pressed.connect(command.bind(action))Send the right command string into command when a passenger or galley button is pressed.
  70. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  71. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  72. func _input(event: InputEvent) -> void:Godot calls this when input arrives. The event tells the game which key, pointer or touch action happened.
  73. if mission.is_empty() or not (event is InputEventKey) or not event.pressed or event.echo:Checks mission.is_empty() or not (event is InputEventKey) or not event.pressed or event.echo. The indented instructions below run only if this test passes.
  74. returnFinishes the function right here. Any later instructions in this function are skipped.
  75. if event.keycode == KEY_UP or event.keycode == KEY_DOWN:Checks event.keycode == KEY_UP or event.keycode == KEY_DOWN. The indented instructions below run only if this test passes.
  76. command("up" if event.keycode == KEY_UP else "down")Calls command with the values in its parentheses.
  77. get_viewport().set_input_as_handled()Stop the same key from going to the keyboard focus system after the game has processed it.
  78. func command(action: String) -> void:Defines command, 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.
  79. if action == "reset":Treat restarting as a special command rather than spending a regular service turn.
  80. state = Rules.initial_state(mission)Give this play session a fresh copy of the starting state.
  81. refresh("Cabin restarted. Check the manifest before your first move.")Calls refresh with the values in its parentheses.
  82. returnFinishes the function right here. Any later instructions in this function are skipped.
  83. var result := Rules.apply_action(mission, state, action)Send a real command to the rules and wait for its result.
  84. refresh(result["message"])Calls refresh with the values in its parentheses.
  85. func refresh(message: String) -> void:Defines refresh, 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.
  86. stripe.position.y = 129 + int(state["row"]) * 65Move the visible gold aisle marker to the active row, starting at the galley.
  87. if state["row"] > 0:Checks state["row"] > 0. The indented instructions below run only if this test passes.
  88. stripe.position.y += 34Reads stripe.position.y, adds to its old value, then stores the result back in the same place.
  89. for seat_id in seats:Repeats the indented instructions for each value in seats.
  90. var button: Button = seats[seat_id]Creates a variable named button. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold.
  91. var requested: String = mission["requests"].get(seat_id, "")Read the label for an open order. Seats with no order can use an empty description.
  92. button.text = seat_id if requested == "" else "%s %s" % [seat_id, requested]Updates button.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  93. if state["served"].has(seat_id):Checks state["served"].has(seat_id). The indented instructions below run only if this test passes.
  94. button.text = "%s done" % seat_idKeep the passenger’s seat ID visible while marking the delivered order in words.
  95. var row_name := "Galley" if state["row"] == 0 else "Row %d" % state["row"]Creates a variable named row_name. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  96. var carry := ", ".join(state["cart"])Make the cart summary readable by adding a comma between every packed item.
  97. if carry == "":Checks carry == "". The indented instructions below run only if this test passes.
  98. carry = "empty"Stores the new value in carry. The expression uses the text inside the quotes.
  99. var rows: Array[String] = []Creates a variable named rows. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  100. for seat_id in mission["requests"]:Repeats the indented instructions for each value in mission["requests"].
  101. rows.append("%s asks for %s" % [seat_id, mission["requests"][seat_id]])Adds an item to the end of a list.
  102. manifest.text = "Updates manifest.text, which controls the words a player sees. The expression uses the text inside the quotes.
  103. ".join(rows)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  104. summary.text = "%s • Cart: %s • %d/%d served • Turns: %d" % [Updates summary.text, which controls the words a player sees. The expression uses the text inside the quotes.
  105. row_name, carry, state["served"].size(), mission["requests"].size(), state["turns"]]Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  106. status.text = messageReplace previous feedback with the newest result or route hint.
Read cabin_rules.gd line by line
  1. extends RefCountedCreate a script that stores rules without needing a node on the screen. RefCounted lets Godot free objects when nothing uses them.
  2. const SUPPLIES = ["Water", "Meal", "Blanket"]Keep the three stocked items together in a constant list. The galley buttons and load rule use the same names.
  3. const CAPACITY = 2Name the two-slot limit so a different part of the program does not quietly use another number.
  4. static func load_mission() -> Dictionary:Read the fixed rules for this training cabin. A static function can be called on the Rules script directly.
  5. var file := FileAccess.open("res://mission.json", FileAccess.READ)Open mission.json at the project root in reading mode. If the file is missing, file will be null.
  6. if file == null:Ask whether the manifest opened correctly before trying to read from it.
  7. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  8. var text := file.get_as_text()Read the characters from the open file. At this point the contents are still raw text.
  9. var data: Variant = JSON.parse_string(text)Turn the JSON text into a Godot value. Variant allows a valid object or the null value returned for invalid text.
  10. if not (data is Dictionary):Reject a manifest whose outer value is not an object with named keys.
  11. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  12. if not (data.get("requests") is Dictionary):Require a dictionary of requests so each whole seat ID can act as a key.
  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. return dataHand the loaded configuration back to the caller.
  15. static func seat_row(seat_id: String) -> int:Accept the whole seat name and return just its numeric row. Keep the letter for looking up the request.
  16. return seat_id.substr(0, seat_id.length() - 1).to_int()Remove the last character and convert what remains. For 2D this produces 2, and for 12A it produces 12.
  17. static func initial_state(mission: Dictionary) -> Dictionary:Create fresh values for the live cabin. The mission defines the fixed layout, not which service actions have already happened.
  18. return {"row": 0, "cart": [], "served": [], "turns": 0, "clear": mission["blocked_row"] < 0}Start at the galley with no supplies, no delivered orders and no turns. A negative blocked-row index means the aisle is already clear.
  19. static func is_finished(mission: Dictionary, state: Dictionary) -> bool:Defines is 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.
  20. return state["served"].size() == mission["requests"].size()Complete the cabin when the served count equals the manifest’s request count. The service branch prevents duplicates in served.
  21. static func apply_action(mission: 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.
  22. if is_finished(mission, state):Checks is_finished(mission, state). The indented instructions below run only if this test passes.
  23. return {"accepted": false, "message": "Service is already complete."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  24. var message := ""Creates a variable named message. The expression uses the text inside the quotes. Godot infers the type from the first value.
  25. if action == "up" or action == "down":Checks action == "up" or action == "down". The indented instructions below run only if this test passes.
  26. var step := -1 if action == "up" else 1Turn the movement command into one numerical step. Earlier rows use minus one, and later rows use plus one.
  27. var destination: int = state["row"] + stepCompute the proposed row without changing Ari’s current row.
  28. if destination < 0 or destination > int(mission["rows"]):Reject a move before the galley or beyond the last passenger row.
  29. return {"accepted": false, "message": "This is the end of the aisle."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  30. state["row"] = destinationCommit this row in the working state after the aisle checks accept it.
  31. message = "At the galley." if destination == 0 else "Ari reached row %d." % destinationStores the new value in message. The expression chooses one of two values by checking the condition in the middle.
  32. elif action.begins_with("load:"):If the earlier branches did not run, checks action.begins_with("load:") next.
  33. if state["row"] != 0:The crew can load supplies only at the galley.
  34. return {"accepted": false, "message": "Return to the galley to load supplies."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  35. if state["cart"].size() >= CAPACITY:Count both item slots. A repeated supply still occupies an additional slot.
  36. return {"accepted": false, "message": "The cart already holds two items."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  37. var item := action.get_slice(":", 1)Read the part after load: as the requested item name. load:Water uses Water.
  38. if not SUPPLIES.has(item):Checks not SUPPLIES.has(item). The indented instructions below run only if this test passes.
  39. return {"accepted": false, "message": "That item is not stocked."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  40. state["cart"].append(item)Put the newly loaded item into one cart slot.
  41. message = "Loaded %s." % itemStores the new value in message. The expression uses the text inside the quotes.
  42. elif action.begins_with("serve:"):If the earlier branches did not run, checks action.begins_with("serve:") next.
  43. var seat_id := action.get_slice(":", 1)Extract the full passenger ID. serve:2D uses 2D, not just the row or letter.
  44. var requests: Dictionary = mission["requests"]Creates a variable named requests. 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.
  45. if not requests.has(seat_id) or state["served"].has(seat_id):Reject a seat without a request or one that has already received its item.
  46. return {"accepted": false, "message": "There is no open request at %s." % seat_id}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  47. if seat_row(seat_id) != state["row"]:Require Ari to stand in the matching aisle row before handing anything over.
  48. return {"accepted": false, "message": "Move beside row %d first." % seat_row(seat_id)}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  49. var item: String = requests[seat_id]Read the correct item using the full seat ID.
  50. if not state["cart"].has(item):Only a cart with the matching item can serve the passenger.
  51. return {"accepted": false, "message": "%s needs %s. Check your cart." % [seat_id, item]}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  52. state["cart"].erase(item)Remove one matching item from the cart after a valid delivery. If a second copy exists, it stays in the cart.
  53. state["served"].append(seat_id)Record exactly which passenger has been served. This can also release a priority gate.
  54. message = "Delivered %s to %s." % [item, seat_id]Stores the new value in message. The expression uses the text inside the quotes.
  55. else:Runs the indented fallback instructions if none of the earlier tests passed.
  56. return {"accepted": false, "message": "Choose a service action."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  57. state["turns"] += 1Spend one turn at the shared successful exit. Paths that returned earlier leave this count alone.
  58. if is_finished(mission, state):Checks is_finished(mission, state). The indented instructions below run only if this test passes.
  59. message += " Cabin ready!"Reads message, adds to its old value, then stores the result back in the same place.
  60. return {"accepted": true, "message": message, "state": state}Send back the outcome, the message for the player and the working state the caller can keep.

mission.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 your edit seems to do nothing, save mission.json before restarting the project. Check that its file name and folder match the res:// path.

Try a change

Move the two requests onto different rows and prove both are deliverable. Keep the keys distinct and use only Water, Meal or Blanket.