Cabin Crew 27 · Give each cabin state a key

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

Ari is preparing a route finder. Two different histories can end at the same useful point, so the computer needs a way to recognise the state it has already seen.

A level view along the aisle of a regional aircraft, with two navy seats on each side.
What you’ll make Build a stable text key for the row, the cart, deliveries, turns and the obstruction.

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.

Read state. Collect the fields used by the game. → Copy and sort. Give matching bags the same order. → Join fields. Make one readable string. → Compare. Decide whether these states match.
Read state → Copy and sort → Join fields → Compare
Godot checkpoint window for Give each cabin state a key
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson state key, sort, duplicate, format string, join, equal state.

  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/27, 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. Decide what the route planner needs

    Open cabin_rules.gd and list the fields from initial_state. Circle the fields that control an action, including turns because the budget checks it.

    return {"row": 0, "cart": [], "served": [], "turns": 0, "clear": mission["blocked_row"] < 0}

    Why it works If the key leaves out a relevant field, the search could confuse a useful state with an exhausted or blocked one.

  3. Make cart order unimportant

    Find state_key. Follow the first three lines in your editor and compare the lists Water, Meal and Meal, Water. Use Compare keys to see the result in the game.

    var items: Array = state["cart"].duplicate()

    Why it works Sorting a copied array gives each collection the same order. It prevents the key calculation from rearranging anything that the player sees.

  4. Keep duplicate items visible

    Read the comma join in the format expression. On paper compare one Water with Water, Water and explain why those keys must differ.

    state["row"], ",".join(items), ",".join(seats), state["turns"], str(state["clear"])]

    Why it works join uses one part for each stored entry. Two copies of the same drink use two cart slots.

  5. Change only the row

    Find compare_keys. Observe what it changes on second after comparing the two carts. Click Compare keys and read both results.

    second["row"] = 1

    Why it works Position matters even when the same supplies are carried. The new row number changes the first part of the key.

  6. Try another one-field change

    In your copy of compare_keys change that assignment to second["turns"] = 1. Run the checkpoint and compare your prediction with the comparison result.

    Why it works The turn limit makes late and early states different. A state reached with one extra turn uses more of the same budget.

Watch the values change

  1. Create a state with Water, Meal Two packed items
    What you see. The key sorts the item names.
  2. Create a state with Meal, Water Same row, stock, turns and orders
    What you see. The keys match.
  3. Move only the second state to row 1 Rows 0 and 1
    What you see. The keys differ.

Predict before you run Do a clear aisle at row 1 and a blocked aisle at row 1 produce the same key?

Reveal the answer

No. The last field records clear, so the route planner can tell whether the next step is possible.

Complete checkpoint

The experiment proves that two differently ordered carts can have one search key while different rows change the key.

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 27", 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")
	make_button("Clear aisle", Rect2(585, 256, 100, 40), "clear")
	make_button("Compare keys", Rect2(693, 256, 100, 40), "keys")

	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
	if action == "keys":
		refresh(Rules.compare_keys(mission))
		return
	var result := Rules.apply_action(mission, state, action)
	if result["accepted"]:
		state = result["state"]
	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)
	if mission["priority"] != "":
		manifest.text += "\nFirst service: " + mission["priority"]
	if not state["clear"]:
		manifest.text += "\nRow %d blocked" % mission["blocked_row"]
	summary.text = "%s   •   Cart: %s   •   %d/%d served   •   Turns: %d / %d" % [
		row_name, carry, state["served"].size(), mission["requests"].size(), state["turns"], int(mission["budget"])]
	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, original: Dictionary, action: String) -> Dictionary:
	var state := original.duplicate(true)
	if is_finished(mission, state):
		return {"accepted": false, "message": "Service is already complete."}
	if state["turns"] >= int(mission["budget"]):
		return {"accepted": false, "message": "Turn budget used. Restart and plan a shorter route."}
	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."}
		if destination == mission["blocked_row"] and not state["clear"]:
			return {"accepted": false, "message": "The aisle is blocked. Clear it from an adjacent row."}
		state["row"] = destination
		message = "At the galley." if destination == 0 else "Ari reached row %d." % destination
	elif action == "clear":
		if state["clear"] or abs(int(state["row"]) - int(mission["blocked_row"])) != 1:
			return {"accepted": false, "message": "Stand one row from the obstruction to clear it."}
		state["clear"] = true
		message = "Aisle cleared. The cart can move through."
	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 priority: String = mission["priority"]
		if priority != "" and seat_id != priority and not state["served"].has(priority):
			return {"accepted": false, "message": "Serve priority seat %s before the other requests." % priority}
		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}

static func state_key(state: Dictionary) -> String:
	var items: Array = state["cart"].duplicate()
	items.sort()
	var seats: Array = state["served"].duplicate()
	seats.sort()
	return "%d|%s|%s|%d|%s" % [
		state["row"], ",".join(items), ",".join(seats), state["turns"], str(state["clear"])]


static func compare_keys(mission: Dictionary) -> String:
	var first := initial_state(mission)
	first["cart"] = ["Water", "Meal"]
	var second := initial_state(mission)
	second["cart"] = ["Meal", "Water"]
	var same_cart := state_key(first) == state_key(second)
	second["row"] = 1
	var moved := state_key(first) != state_key(second)
	return "Same items, same key: %s. New row, new key: %s.
%s" % [
		str(same_cart), str(moved), state_key(first)]

mission.json

{
  "rows": 3,
  "budget": 13,
  "blocked_row": 2,
  "requests": {
    "1A": "Water",
    "3D": "Meal"
  },
  "priority": "3D"
}

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 27", 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. make_button("Clear aisle", Rect2(585, 256, 100, 40), "clear")Calls make_button with the values in its parentheses.
  43. make_button("Compare keys", Rect2(693, 256, 100, 40), "keys")Calls make_button with the values in its parentheses.
  44. 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.
  45. 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.
  46. 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.
  47. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow a long message to wrap without hiding the end of it.
  48. up.grab_focus()Make the first navigation button ready for keyboard input.
  49. refresh("Train as Ari. Load items at the galley, then choose seats from the aisle.")Calls refresh with the values in its parentheses.
  50. 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.
  51. var card := ColorRect.new()Creates a variable named card. The expression creates a new ColorRect object. Godot infers the type from the first value.
  52. card.color = shadeStores the new value in card.color. The expression reads shade.
  53. card.position = box.positionUpdates card.position, which controls the node's local x and y location. The expression reads box.position.
  54. card.size = box.sizeUpdates card.size, which controls the control's width and height. The expression reads box.size.
  55. add_child(card)Adds the new node to the scene tree so that Godot can run and draw it.
  56. return cardFinishes the function and hands its result back to the caller. The expression reads card.
  57. 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.
  58. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  59. label.text = copyUpdates label.text, which controls the words a player sees. The expression reads copy.
  60. label.position = box.positionUpdates label.position, which controls the node's local x and y location. The expression reads box.position.
  61. label.size = box.sizeUpdates label.size, which controls the control's width and height. The expression reads box.size.
  62. label.add_theme_font_size_override("font_size", font_size)Calls label.add_theme_font_size_override with the values in its parentheses.
  63. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  64. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  65. 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.
  66. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  67. button.text = copyUpdates button.text, which controls the words a player sees. The expression reads copy.
  68. button.position = box.positionUpdates button.position, which controls the node's local x and y location. The expression reads box.position.
  69. button.size = box.sizeUpdates button.size, which controls the control's width and height. The expression reads box.size.
  70. button.add_theme_font_size_override("font_size", 14)Calls button.add_theme_font_size_override with the values in its parentheses.
  71. button.pressed.connect(command.bind(action))Send the right command string into command when a passenger or galley button is pressed.
  72. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  73. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  74. func _input(event: InputEvent) -> void:Godot calls this when input arrives. The event tells the game which key, pointer or touch action happened.
  75. 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.
  76. returnFinishes the function right here. Any later instructions in this function are skipped.
  77. 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.
  78. command("up" if event.keycode == KEY_UP else "down")Calls command with the values in its parentheses.
  79. get_viewport().set_input_as_handled()Stop the same key from going to the keyboard focus system after the game has processed it.
  80. 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.
  81. if action == "reset":Treat restarting as a special command rather than spending a regular service turn.
  82. state = Rules.initial_state(mission)Give this play session a fresh copy of the starting state.
  83. refresh("Cabin restarted. Check the manifest before your first move.")Calls refresh with the values in its parentheses.
  84. returnFinishes the function right here. Any later instructions in this function are skipped.
  85. if action == "keys":Checks action == "keys". The indented instructions below run only if this test passes.
  86. refresh(Rules.compare_keys(mission))Calls refresh with the values in its parentheses.
  87. returnFinishes the function right here. Any later instructions in this function are skipped.
  88. var result := Rules.apply_action(mission, state, action)Send a real command to the rules and wait for its result.
  89. if result["accepted"]:Change local state only when the service rule accepts the move.
  90. state = result["state"]Commit the returned state so the board and manifest can both reflect it.
  91. refresh(result["message"])Calls refresh with the values in its parentheses.
  92. 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.
  93. stripe.position.y = 129 + int(state["row"]) * 65Move the visible gold aisle marker to the active row, starting at the galley.
  94. if state["row"] > 0:Checks state["row"] > 0. The indented instructions below run only if this test passes.
  95. stripe.position.y += 34Reads stripe.position.y, adds to its old value, then stores the result back in the same place.
  96. for seat_id in seats:Repeats the indented instructions for each value in seats.
  97. 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.
  98. var requested: String = mission["requests"].get(seat_id, "")Read the label for an open order. Seats with no order can use an empty description.
  99. 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.
  100. if state["served"].has(seat_id):Checks state["served"].has(seat_id). The indented instructions below run only if this test passes.
  101. button.text = "%s done" % seat_idKeep the passenger’s seat ID visible while marking the delivered order in words.
  102. 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.
  103. var carry := ", ".join(state["cart"])Make the cart summary readable by adding a comma between every packed item.
  104. if carry == "":Checks carry == "". The indented instructions below run only if this test passes.
  105. carry = "empty"Stores the new value in carry. The expression uses the text inside the quotes.
  106. 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.
  107. for seat_id in mission["requests"]:Repeats the indented instructions for each value in mission["requests"].
  108. rows.append("%s asks for %s" % [seat_id, mission["requests"][seat_id]])Adds an item to the end of a list.
  109. manifest.text = "Updates manifest.text, which controls the words a player sees. The expression uses the text inside the quotes.
  110. ".join(rows)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  111. if mission["priority"] != "":Checks mission["priority"] != "". The indented instructions below run only if this test passes.
  112. manifest.text += "\nFirst service: " + mission["priority"]Reads manifest.text, adds to its old value, then stores the result back in the same place.
  113. if not state["clear"]:Checks not state["clear"]. The indented instructions below run only if this test passes.
  114. manifest.text += "\nRow %d blocked" % mission["blocked_row"]Reads manifest.text, adds to its old value, then stores the result back in the same place.
  115. summary.text = "%s • Cart: %s • %d/%d served • Turns: %d / %d" % [Updates summary.text, which controls the words a player sees. The expression uses the text inside the quotes.
  116. row_name, carry, state["served"].size(), mission["requests"].size(), state["turns"], int(mission["budget"])]Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  117. 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, original: 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. var state := original.duplicate(true)Make a new dictionary with independent nested arrays. This protects the live cart while the planner tries an imagined delivery.
  23. if is_finished(mission, state):Checks is_finished(mission, state). The indented instructions below run only if this test passes.
  24. 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.
  25. if state["turns"] >= int(mission["budget"]):Check the cutoff before movement, loading or handoff. At the limit no more successful turns are available.
  26. return {"accepted": false, "message": "Turn budget used. Restart and plan a shorter route."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  27. var message := ""Creates a variable named message. The expression uses the text inside the quotes. Godot infers the type from the first value.
  28. if action == "up" or action == "down":Checks action == "up" or action == "down". The indented instructions below run only if this test passes.
  29. 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.
  30. var destination: int = state["row"] + stepCompute the proposed row without changing Ari’s current row.
  31. if destination < 0 or destination > int(mission["rows"]):Reject a move before the galley or beyond the last passenger row.
  32. 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.
  33. if destination == mission["blocked_row"] and not state["clear"]:Prevent entry into the blocked row until Ari has cleared it.
  34. return {"accepted": false, "message": "The aisle is blocked. Clear it from an adjacent row."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  35. state["row"] = destinationCommit this row in the working state after the aisle checks accept it.
  36. 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.
  37. elif action == "clear":If the earlier branches did not run, checks action == "clear" next.
  38. if state["clear"] or abs(int(state["row"]) - int(mission["blocked_row"])) != 1:Reject a clearance that is already complete or being attempted from more than one row away. abs makes both approaches count the same.
  39. return {"accepted": false, "message": "Stand one row from the obstruction to clear it."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  40. state["clear"] = trueRemember that future legal moves can enter the previously blocked row.
  41. message = "Aisle cleared. The cart can move through."Stores the new value in message. The expression uses the text inside the quotes.
  42. elif action.begins_with("load:"):If the earlier branches did not run, checks action.begins_with("load:") next.
  43. if state["row"] != 0:The crew can load supplies only at the galley.
  44. 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.
  45. if state["cart"].size() >= CAPACITY:Count both item slots. A repeated supply still occupies an additional slot.
  46. 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.
  47. var item := action.get_slice(":", 1)Read the part after load: as the requested item name. load:Water uses Water.
  48. if not SUPPLIES.has(item):Checks not SUPPLIES.has(item). The indented instructions below run only if this test passes.
  49. 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.
  50. state["cart"].append(item)Put the newly loaded item into one cart slot.
  51. message = "Loaded %s." % itemStores the new value in message. The expression uses the text inside the quotes.
  52. elif action.begins_with("serve:"):If the earlier branches did not run, checks action.begins_with("serve:") next.
  53. var seat_id := action.get_slice(":", 1)Extract the full passenger ID. serve:2D uses 2D, not just the row or letter.
  54. 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.
  55. 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.
  56. 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.
  57. if seat_row(seat_id) != state["row"]:Require Ari to stand in the matching aisle row before handing anything over.
  58. 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.
  59. var priority: String = mission["priority"]Creates a variable named priority. 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.
  60. if priority != "" and seat_id != priority and not state["served"].has(priority):Hold a standard order back while a named priority passenger is still waiting.
  61. return {"accepted": false, "message": "Serve priority seat %s before the other requests." % priority}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  62. var item: String = requests[seat_id]Read the correct item using the full seat ID.
  63. if not state["cart"].has(item):Only a cart with the matching item can serve the passenger.
  64. 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.
  65. 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.
  66. state["served"].append(seat_id)Record exactly which passenger has been served. This can also release a priority gate.
  67. message = "Delivered %s to %s." % [item, seat_id]Stores the new value in message. The expression uses the text inside the quotes.
  68. else:Runs the indented fallback instructions if none of the earlier tests passed.
  69. 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.
  70. state["turns"] += 1Spend one turn at the shared successful exit. Paths that returned earlier leave this count alone.
  71. if is_finished(mission, state):Checks is_finished(mission, state). The indented instructions below run only if this test passes.
  72. message += " Cabin ready!"Reads message, adds to its old value, then stores the result back in the same place.
  73. return {"accepted": true, "message": message, "state": state}Send back the outcome, the message for the player and the working state the caller can keep.
  74. 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.
  75. var items: Array = state["cart"].duplicate()Copy the list before sorting, so computing a key cannot reorder the live cart.
  76. items.sort()Make Meal, Water and Water, Meal canonical. Sorting preserves duplicates.
  77. var seats: Array = state["served"].duplicate()Copy the delivered seats before arranging them for the key.
  78. seats.sort()Treat equally served cabins as alike regardless of which seat was served first.
  79. return "%d|%s|%s|%d|%s" % [Use a separator that the short item names and seat IDs cannot contain. It keeps the five fields distinguishable.
  80. state["row"], ",".join(items), ",".join(seats), state["turns"], str(state["clear"])]Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  81. static func compare_keys(mission: Dictionary) -> 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.
  82. var first := initial_state(mission)Creates a variable named first. The expression calls initial_state with the values in its parentheses. Godot infers the type from the first value.
  83. first["cart"] = ["Water", "Meal"]Stores the new value in first["cart"]. The expression makes a list whose items keep their order.
  84. var second := initial_state(mission)Creates a variable named second. The expression calls initial_state with the values in its parentheses. Godot infers the type from the first value.
  85. second["cart"] = ["Meal", "Water"]Stores the new value in second["cart"]. The expression makes a list whose items keep their order.
  86. var same_cart := state_key(first) == state_key(second)Ask whether the same supplies loaded in a different order still describe the same useful state.
  87. second["row"] = 1Change the position while leaving the cart alone. A different row needs a different key.
  88. var moved := state_key(first) != state_key(second)Creates a variable named moved. The expression calls state_key with the values in its parentheses. Godot infers the type from the first value.
  89. return "Same items, same key: %s. New row, new key: %s.Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  90. %s" % [Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  91. str(same_cart), str(moved), state_key(first)]Turns a value into text for a player message.

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 computing a key changes the HUD item order, check whether you sorted the original cart without duplicating the array first.

Try a change

Print the key after a valid delivery and highlight the fields that changed. Compare with a rejected delivery.