Cabin Crew 29 · Replay a proposed route

Cabin Crew Express · Lesson 29 of 50 · Intermediate · About 30 min

Ari sees the route finder’s suggestion. A replay lets the team double-check that it clears the right aisle and delivers every request.

A level view along the aisle of a regional aircraft, with two navy seats on each side.
What you’ll make Run a short plan on a copied cabin state and inspect its outcome before playing it.

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/28 when the lesson builds on prior work, or copy the checkpoints/29 folder to try this lesson on its own. Read the file names in the steps before editing.

Copy start. Use a fresh copy of live values. → Read first action. Ask the rules to apply it. → Continue or stop. Keep valid results and stop on failure. → Report outcome. Show the result without committing it.
Copy start → Read first action → Continue or stop → Report outcome
Godot checkpoint window for Replay a proposed route
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson replay, Array[String], copy, iteration, deterministic rules, inspect result.

  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/29, 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. Distinguish a hint from a replay

    Open the game and press Route hint. Then press Replay plan. Write down which action the hint gives and what the replay reports.

    Why it works The hint names the next move. The replay checks the whole plan while preserving the cabin you are playing.

  3. Start from an untouched copy

    In cabin_rules.gd find replay. Underline the variable that receives a copy before the loop begins.

    var current := start.duplicate(true)

    Why it works A copied state is a safe starting point for running every suggested move. The UI keeps its own original state.

  4. Apply one action at a time

    Trace two loop iterations from apply_action through to the assignment of current. Check which state the second iteration reads.

    current = result["state"]

    Why it works Each move depends on the outcome of the last one. Reusing the starting state would forget all the previous changes.

  5. Stop on the first rejected move

    In your copy, temporarily replace the generated plan in main.gd with a one-step list containing serve:3D, keeping the list typed as Array[String]. Run Replay plan at the galley and observe a failed result. Restore the real plan afterwards.

    return {"finished": false, "state": current, "message": result["message"]}

    Why it works Early return preserves the state at the moment a route cannot continue. That helps a tester identify which step to check first.

  6. Replay twice with the same inputs

    With the original plan restored, press Replay plan twice at the same starting position. Then actually play some moves and run it again.

    Why it works Replay uses the same rule functions. Repeating identical inputs gives the same outcome, and a different live state can give a shorter remaining route.

Watch the values change

  1. Replay from the galley Live turn 0
    What you see. The planned result finishes at turn 10.
  2. Replay again at the same position Live turn 0
    What you see. The result finishes at the same turn.
  3. Try an invalid serve as the first command Live row 0
    What you see. The temporary replay stops before changing the cabin.

Predict before you run Does seeing a successful replay serve the passengers in the live cabin?

Reveal the answer

No. The replay reaches a possible ending in a copy. Ari has to take the actual turns to finish the live game.

Complete checkpoint

The standard plan replays to a successful finish without advancing the live turn counter.

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 29", 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("Route hint", Rect2(693, 256, 100, 40), "hint")
	make_button("Replay plan", Rect2(801, 256, 100, 40), "replay")

	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 == "hint":
		var route := Rules.find_route(mission, state)
		var hint := "No remaining route found. Try Restart." if route.is_empty() else "Next action: %s · %d more turns" % [route[0], route.size()]
		if Rules.is_finished(mission, state):
			hint = "All requests are complete."
		refresh(hint)
		return
	if action == "replay":
		var plan := Rules.find_route(mission, state)
		var outcome := Rules.replay(mission, state, plan)
		var finish := "finished" if outcome["finished"] else "did not finish"
		refresh("Replay %s at turn %d. The live cabin stays here." % [finish, outcome["state"]["turns"]])
		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)]

static func choices(mission: Dictionary, state: Dictionary) -> Array[String]:
	var options: Array[String] = ["up", "down", "clear"]
	if state["row"] == 0:
		for item in SUPPLIES:
			options.append("load:" + item)
	for seat_id in mission["requests"]:
		options.append("serve:" + seat_id)
	return options


static func find_route(mission: Dictionary, state: Dictionary) -> Array[String]:
	var empty: Array[String] = []
	var frontier: Array[Dictionary] = [{"state": state, "path": empty}]
	var seen := {state_key(state): true}
	var index := 0
	while index < frontier.size():
		var entry := frontier[index]
		index += 1
		if is_finished(mission, entry["state"]):
			return entry["path"]
		for action in choices(mission, entry["state"]):
			var result := apply_action(mission, entry["state"], action)
			if not result["accepted"]:
				continue
			var key := state_key(result["state"])
			if seen.has(key):
				continue
			seen[key] = true
			var path: Array[String] = entry["path"].duplicate()
			path.append(action)
			frontier.append({"state": result["state"], "path": path})
	return empty

static func replay(mission: Dictionary, start: Dictionary, actions: Array[String]) -> Dictionary:
	var current := start.duplicate(true)
	for action in actions:
		var result := apply_action(mission, current, action)
		if not result["accepted"]:
			return {"finished": false, "state": current, "message": result["message"]}
		current = result["state"]
	return {"finished": is_finished(mission, current), "state": current, "message": "Replay ended."}

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 29", 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("Route hint", Rect2(693, 256, 100, 40), "hint")Calls make_button with the values in its parentheses.
  44. make_button("Replay plan", Rect2(801, 256, 100, 40), "replay")Calls make_button with the values in its parentheses.
  45. 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.
  46. 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.
  47. 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.
  48. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow a long message to wrap without hiding the end of it.
  49. up.grab_focus()Make the first navigation button ready for keyboard input.
  50. refresh("Train as Ari. Load items at the galley, then choose seats from the aisle.")Calls refresh with the values in its parentheses.
  51. 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.
  52. var card := ColorRect.new()Creates a variable named card. The expression creates a new ColorRect object. Godot infers the type from the first value.
  53. card.color = shadeStores the new value in card.color. The expression reads shade.
  54. card.position = box.positionUpdates card.position, which controls the node's local x and y location. The expression reads box.position.
  55. card.size = box.sizeUpdates card.size, which controls the control's width and height. The expression reads box.size.
  56. add_child(card)Adds the new node to the scene tree so that Godot can run and draw it.
  57. return cardFinishes the function and hands its result back to the caller. The expression reads card.
  58. 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.
  59. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  60. label.text = copyUpdates label.text, which controls the words a player sees. The expression reads copy.
  61. label.position = box.positionUpdates label.position, which controls the node's local x and y location. The expression reads box.position.
  62. label.size = box.sizeUpdates label.size, which controls the control's width and height. The expression reads box.size.
  63. label.add_theme_font_size_override("font_size", font_size)Calls label.add_theme_font_size_override with the values in its parentheses.
  64. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  65. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  66. 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.
  67. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  68. button.text = copyUpdates button.text, which controls the words a player sees. The expression reads copy.
  69. button.position = box.positionUpdates button.position, which controls the node's local x and y location. The expression reads box.position.
  70. button.size = box.sizeUpdates button.size, which controls the control's width and height. The expression reads box.size.
  71. button.add_theme_font_size_override("font_size", 14)Calls button.add_theme_font_size_override with the values in its parentheses.
  72. button.pressed.connect(command.bind(action))Send the right command string into command when a passenger or galley button is pressed.
  73. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  74. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  75. func _input(event: InputEvent) -> void:Godot calls this when input arrives. The event tells the game which key, pointer or touch action happened.
  76. 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.
  77. returnFinishes the function right here. Any later instructions in this function are skipped.
  78. 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.
  79. command("up" if event.keycode == KEY_UP else "down")Calls command with the values in its parentheses.
  80. get_viewport().set_input_as_handled()Stop the same key from going to the keyboard focus system after the game has processed it.
  81. 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.
  82. if action == "reset":Treat restarting as a special command rather than spending a regular service turn.
  83. state = Rules.initial_state(mission)Give this play session a fresh copy of the starting state.
  84. refresh("Cabin restarted. Check the manifest before your first move.")Calls refresh with the values in its parentheses.
  85. returnFinishes the function right here. Any later instructions in this function are skipped.
  86. if action == "hint":Checks action == "hint". The indented instructions below run only if this test passes.
  87. var route := Rules.find_route(mission, state)Search from Ari’s current position and supplies.
  88. var hint := "No remaining route found. Try Restart." if route.is_empty() else "Next action: %s · %d more turns" % [route[0], route.size()]Creates a variable named hint. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  89. if Rules.is_finished(mission, state):Checks Rules.is_finished(mission, state). The indented instructions below run only if this test passes.
  90. hint = "All requests are complete."Stores the new value in hint. The expression uses the text inside the quotes.
  91. refresh(hint)Calls refresh with the values in its parentheses.
  92. returnFinishes the function right here. Any later instructions in this function are skipped.
  93. if action == "replay":Checks action == "replay". The indented instructions below run only if this test passes.
  94. var plan := Rules.find_route(mission, state)Creates a variable named plan. The expression calls Rules.find_route with the values in its parentheses. Godot infers the type from the first value.
  95. var outcome := Rules.replay(mission, state, plan)Run the whole planned route on a copy and inspect the end result.
  96. var finish := "finished" if outcome["finished"] else "did not finish"Creates a variable named finish. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  97. refresh("Replay %s at turn %d. The live cabin stays here." % [finish, outcome["state"]["turns"]])Calls refresh with the values in its parentheses.
  98. returnFinishes the function right here. Any later instructions in this function are skipped.
  99. var result := Rules.apply_action(mission, state, action)Send a real command to the rules and wait for its result.
  100. if result["accepted"]:Change local state only when the service rule accepts the move.
  101. state = result["state"]Commit the returned state so the board and manifest can both reflect it.
  102. refresh(result["message"])Calls refresh with the values in its parentheses.
  103. 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.
  104. stripe.position.y = 129 + int(state["row"]) * 65Move the visible gold aisle marker to the active row, starting at the galley.
  105. if state["row"] > 0:Checks state["row"] > 0. The indented instructions below run only if this test passes.
  106. stripe.position.y += 34Reads stripe.position.y, adds to its old value, then stores the result back in the same place.
  107. for seat_id in seats:Repeats the indented instructions for each value in seats.
  108. 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.
  109. var requested: String = mission["requests"].get(seat_id, "")Read the label for an open order. Seats with no order can use an empty description.
  110. 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.
  111. if state["served"].has(seat_id):Checks state["served"].has(seat_id). The indented instructions below run only if this test passes.
  112. button.text = "%s done" % seat_idKeep the passenger’s seat ID visible while marking the delivered order in words.
  113. 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.
  114. var carry := ", ".join(state["cart"])Make the cart summary readable by adding a comma between every packed item.
  115. if carry == "":Checks carry == "". The indented instructions below run only if this test passes.
  116. carry = "empty"Stores the new value in carry. The expression uses the text inside the quotes.
  117. 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.
  118. for seat_id in mission["requests"]:Repeats the indented instructions for each value in mission["requests"].
  119. rows.append("%s asks for %s" % [seat_id, mission["requests"][seat_id]])Adds an item to the end of a list.
  120. manifest.text = "Updates manifest.text, which controls the words a player sees. The expression uses the text inside the quotes.
  121. ".join(rows)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  122. if mission["priority"] != "":Checks mission["priority"] != "". The indented instructions below run only if this test passes.
  123. manifest.text += "\nFirst service: " + mission["priority"]Reads manifest.text, adds to its old value, then stores the result back in the same place.
  124. if not state["clear"]:Checks not state["clear"]. The indented instructions below run only if this test passes.
  125. 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.
  126. 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.
  127. 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.
  128. 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.
  92. static func choices(mission: Dictionary, state: Dictionary) -> Array[String]:Defines choices, 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. var options: Array[String] = ["up", "down", "clear"]List a few possible commands. The transition rule will remove impossible choices later.
  94. if state["row"] == 0:Checks state["row"] == 0. The indented instructions below run only if this test passes.
  95. for item in SUPPLIES:Repeats the indented instructions for each value in SUPPLIES.
  96. options.append("load:" + item)Add a distinct action for each available item at the galley.
  97. for seat_id in mission["requests"]:Repeats the indented instructions for each value in mission["requests"].
  98. options.append("serve:" + seat_id)Build an explicit command for each known passenger. A command at the wrong row will be rejected.
  99. return optionsFinishes the function and hands its result back to the caller. The expression reads options.
  100. static func find_route(mission: Dictionary, state: Dictionary) -> Array[String]:Defines find route, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  101. var empty: Array[String] = []Creates a variable named empty. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  102. var frontier: Array[Dictionary] = [{"state": state, "path": empty}]Begin the search with one waiting entry, Ari’s actual cabin and an empty list of moves.
  103. var seen := {state_key(state): true}Remember the starting position as already discovered to avoid queuing the same state again.
  104. var index := 0Creates a variable named index. The expression uses the whole number 0. Godot infers the type from the first value.
  105. while index < frontier.size():Continue as long as the queue contains an entry at the reading position. Adding to the end keeps each depth in order.
  106. var entry := frontier[index]Read the oldest unprocessed route candidate without deleting anything from the front of the array.
  107. index += 1Move the reading position forward so this entry will not be examined again.
  108. if is_finished(mission, entry["state"]):Check whether this entry serves every passenger. In this search the earliest solution removed from the queue uses the fewest moves.
  109. return entry["path"]Finishes the function and hands its result back to the caller. The expression looks up the item or key written between the square brackets.
  110. for action in choices(mission, entry["state"]):Repeats the indented instructions for each value in choices(mission, entry["state"]).
  111. var result := apply_action(mission, entry["state"], action)Simulate one possible step through the same rule used for the real cabin.
  112. if not result["accepted"]:Ignore a rejected move because it contributes no viable new cabin.
  113. continueSkips the rest of this turn through the loop and moves on to the next item.
  114. var key := state_key(result["state"])Creates a variable named key. The expression calls state_key with the values in its parentheses. Godot infers the type from the first value.
  115. if seen.has(key):Skip a state that is already waiting or has already been examined.
  116. continueSkips the rest of this turn through the loop and moves on to the next item.
  117. seen[key] = trueMark the state as discovered when it joins the queue. This also stops two different parents from adding it.
  118. var path: Array[String] = entry["path"].duplicate()Copy the path so adding an action to this branch does not alter its siblings.
  119. path.append(action)Remember the action that reached this new state.
  120. frontier.append({"state": result["state"], "path": path})Put the new candidate at the back of the queue, behind any candidates with shorter paths.
  121. return emptyReport that no route could be found from this state inside the allowed turns.
  122. static func replay(mission: Dictionary, start: Dictionary, actions: Array[String]) -> Dictionary:Defines replay, 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.
  123. var current := start.duplicate(true)Create a private copy for replay. Keep the original state available for the player.
  124. for action in actions:Repeats the indented instructions for each value in actions.
  125. var result := apply_action(mission, current, action)Creates a variable named result. The expression calls apply_action with the values in its parentheses. Godot infers the type from the first value.
  126. if not result["accepted"]:Ignore a rejected move because it contributes no viable new cabin.
  127. return {"finished": false, "state": current, "message": result["message"]}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  128. current = result["state"]Carry forward everything the last simulated turn changed.
  129. return {"finished": is_finished(mission, current), "state": current, "message": "Replay ended."}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.

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 replay forgets a loaded item when it reaches the next step, make sure the loop passes current to apply_action and updates current after each accepted action.

Try a change

Create a typed route with the first correct load followed by an intentionally wrong move. Record the first rejected step and suggest how to replace it.