Cruise Game 30 · Replay a route and test the rules

Midnight Deck Dash · Lesson 30 of 50 · Intermediate · About 30 min

Before the next guests board, the crew rehearses tonight's delivery routes. Write the same kind of check for your game so changes cannot quietly break a deck.

The ship’s Art Deco Grand Atrium, with carved rails, teal upholstery and warm gold lights.
What you’ll make Run repeatable checks for blocked moves, wait actions, successful deliveries and deterministic replay.

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

Prepare a deck. Start with a known layout and fresh state. → Try fixed actions. Check bulkhead, Wait and the found route. → Compare results. Verify the expected values and both replay outputs. → Report what failed. Readable messages tell you which rule to inspect.
Prepare a deck → Try fixed actions → Compare results → Report what failed
Godot checkpoint window for Replay a route and test the rules
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson test fixture, expected versus actual, replay, determinism, test failure message, regression.

  1. Open this checkpoint in Godot

    Unzip checkpoint 30. Open Godot Project Manager, choose Import and select its project.godot. Double-click main.gd in FileSystem, then find the Test button. Press F6 if the main scene is open, or F5 to run the project.

    Why it works Each checkpoint is a complete playable exercise. Saving an extra copy before editing gives you a quick way back when an experiment goes wrong.

  2. Start every rehearsal from the same state

    Open route_rules.gd, find replay, and trace the state created at its start. Follow how it feeds the result of one action into the next.

    state = next_state(deck, state, action)

    Why it works Replay uses an ordered action list. It gives every action the complete state returned by the previous one, so the trolley and cargo advance together.

  3. Check the negative case

    Find the blocked test inside run_tests. Compare its position and turn with the known start. Examine its human-readable failure string.

    if blocked["cell"] != start["cell"] or blocked["tick"] != 0:

    Why it works A reliable game needs both valid actions and refused actions. A negative test catches moving into a wall or spending time when a move was rejected.

  4. Check waiting and a clean finish

    Read the wait test and the use of find_route. Then read the three outcomes the solve condition refuses: empty route, incomplete game and collision.

    Why it works A hint is useful only when the same rule engine can finish with its actions. Checking expected state is stronger than checking that a button printed something.

  5. Repeat the exact same inputs

    Read where final_a and final_b are created. Explain why changing the original start dictionary would count as a failure even if both final states matched.

    if final_a != final_b or start["tick"] != 0:

    Why it works Deterministic rules give the same answers from the same start and action list. The test additionally protects the start snapshot from accidental editing.

  6. Run, break and repair a test

    Press Test on each training deck. In a separate experiment copy, change the expected Wait tick from 1 to 2. Rerun the test and read the failure. Restore 1 and confirm the checks pass again.

    Why it works Seeing a deliberate failure proves the check is really running. Restoring the expected value leaves your project clean and ready to extend.

Watch the values change

  1. Run blocked move origin still (1, 1) and tick stays 0 on promenade
    What you see. Bulkhead check passes.
  2. Run Wait same cell with tick 1
    What you see. The wait check sees just the intended change.
  3. Replay two runs both drafts arrive at X with the same final dictionary
    What you see. The Test button reports four checks passed.

Predict before you run What would happen if the engine picked a random trolley route during each replay and you did not save the choice?

Reveal the answer

Starting with the same deck and actions would no longer guarantee the same final state. Save the choice in the starting state or keep the patrol fixed.

Complete checkpoint

Each of the three training decks reports four route checks passed. Changing the expected Wait tick demonstrates a readable, reversible failure.

main.gd

extends Control

const Rules = preload("res://route_rules.gd")
const LABEL_BLUE := Color("#b4d9e5")
const PAPER := Color("#fff1ca")

var deck: Dictionary
var available: Array[Dictionary]
var active := 0
var state: Dictionary
var heading: Label
var board: Label
var status: Label
var folder: VBoxContainer

func _ready() -> void:
    var backdrop := ColorRect.new()
    backdrop.color = Color("#071f30")
    backdrop.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
    backdrop.mouse_filter = Control.MOUSE_FILTER_IGNORE
    add_child(backdrop)
    folder = VBoxContainer.new()
    folder.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
    folder.offset_left = 22
    folder.offset_right = -22
    folder.offset_top = 14
    folder.offset_bottom = -12
    folder.add_theme_constant_override("separation", 8)
    add_child(folder)
    heading = make_label("", 27, PAPER)
    make_label("MIDNIGHT DECK DASH  /  TRAINING DECK", 15, LABEL_BLUE)
    board = make_label("", 28, PAPER)
    var mono := SystemFont.new()
    mono.font_names = PackedStringArray(["DejaVu Sans Mono", "Courier New", "monospace"])
    board.add_theme_font_override("font", mono)
    make_label("@ You    O Trolley    a Parcel    A Delivery    X Departure    # Wall    ≋ Hatch", 14, LABEL_BLUE)
    status = make_label("", 17, PAPER)
    status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
    status.custom_minimum_size.y = 48
    var controls := HBoxContainer.new()
    controls.add_theme_constant_override("separation", 6)
    folder.add_child(controls)
    make_button(controls, "North", _move.bind("N"))
    make_button(controls, "West", _move.bind("W"))
    make_button(controls, "South", _move.bind("S"))
    make_button(controls, "East", _move.bind("E"))
    make_button(controls, "Wait", _move.bind("WAIT"))
    make_button(controls, "Reset", _reset)
    make_button(controls, "Next deck", _next)
    make_button(controls, "Peek east", _peek)
    make_button(controls, "Hint", _hint)
    make_button(controls, "Test", _test)
    available = Rules.load_decks("res://decks.json")
    if available.is_empty():
        available = [Rules.first_deck()]
    _reset()

func make_label(words: String, px: int, ink: Color) -> Label:
    var label := Label.new()
    label.text = words
    label.add_theme_font_size_override("font_size", px)
    label.add_theme_color_override("font_color", ink)
    folder.add_child(label)
    return label

func make_button(parent: HBoxContainer, words: String, callback: Callable) -> void:
    var button := Button.new()
    button.text = words
    button.custom_minimum_size = Vector2(70, 40)
    button.pressed.connect(callback)
    parent.add_child(button)

func _reset() -> void:
    deck = available[active]
    state = Rules.initial_state(deck)
    refresh()

func _move(action: String) -> void:
    state = Rules.next_state(deck, state, action)
    refresh()

func refresh() -> void:
    heading.text = deck["title"]
    var view := ""
    var cart := Rules.cart_cell(deck, state["tick"])
    for row in range(deck["height"]):
        for col in range(deck["width"]):
            var cell := Vector2i(col, row)
            var mark := "."
            if deck["walls"].has(cell):
                mark = "#"
            elif cell == deck["exit"]:
                mark = "X"
            elif deck["pickups"].has(cell) and deck["pickups"][cell] not in state["delivered"] and state["carrying"] != deck["pickups"][cell]:
                mark = deck["pickups"][cell]
            elif deck["drops"].has(cell):
                mark = deck["drops"][cell].to_upper()
            elif deck["hatches"].has(cell):
                mark = "≋"
            if cell == cart:
                mark = "O"
            if cell == state["cell"]:
                mark = "!" if state["caught"] else "@"
            view += mark + " "
        view += "
"
    board.text = view.strip_edges()
    var cargo: String = state["carrying"].to_upper() if state["carrying"] != "" else "Empty"
    status.text = "Turn %d  •  Cargo: %s  •  %s" % [state["tick"], cargo, state["message"]]

func _next() -> void:
    active = (active + 1) % available.size()
    _reset()

func _peek() -> void:
    var trial := Rules.next_state(deck, state, "E")
    status.text = "If east: turn %d  •  %s  •  Live turn still %d." % [trial["tick"], trial["message"], state["tick"]]

func _hint() -> void:
    var route := Rules.find_route(deck, state)
    if state["complete"]:
        status.text = "Delivery complete!"
    elif route.is_empty():
        status.text = "No safe route from here. Reset to try again."
    else:
        status.text = "Safe hint: %s  •  %d turns to finish." % [route[0], route.size()]

func _test() -> void:
    status.text = Rules.run_tests(deck)

route_rules.gd

extends RefCounted

const DELTAS := {
    "N": Vector2i(0, -1), "E": Vector2i(1, 0),
    "S": Vector2i(0, 1), "W": Vector2i(-1, 0),
    "WAIT": Vector2i.ZERO
}

static func first_deck() -> Dictionary:
    return parse_level({
        "title": "Moonlit Promenade",
        "rows": ["#########", "#@..a.Ax#", "#.#...#.#", "#1.....1#", "#########"],
        "cart": [[3, 1], [4, 1], [4, 2], [3, 2]]
    })

static func initial_state(deck: Dictionary) -> Dictionary:
    return {
        "cell": deck["start"], "tick": 0, "carrying": "",
        "delivered": [], "caught": false, "complete": false,
        "message": "Deliver the parcel, then reach X."
    }

static func cart_cell(deck: Dictionary, tick: int) -> Vector2i:
    var patrol: Array = deck["cart"]
    return patrol[tick % patrol.size()]

static func on_floor(deck: Dictionary, cell: Vector2i) -> bool:
    return cell.x >= 0 and cell.y >= 0 and cell.x < deck["width"] and cell.y < deck["height"] and not deck["walls"].has(cell)

static func advance(deck: Dictionary, state: Dictionary, action: String) -> void:
    if state["caught"] or state["complete"]:
        return
    if not DELTAS.has(action):
        return
    var origin: Vector2i = state["cell"]
    var step: Vector2i = DELTAS[action]
    var arrival := origin + step
    if not on_floor(deck, arrival):
        state["message"] = "Bulkhead: no turn spent."
        return
    if action != "WAIT" and deck["hatches"].has(arrival):
        arrival = deck["hatches"][arrival]
    var old_cart := cart_cell(deck, state["tick"])
    state["cell"] = arrival
    state["tick"] += 1
    var new_cart := cart_cell(deck, state["tick"])
    var overtake := old_cart == arrival and new_cart == origin
    if arrival == new_cart or overtake:
        state["caught"] = true
        state["message"] = "Trolley in the lane. Reset to try again."
        return
    apply_delivery(deck, state)

static func apply_delivery(deck: Dictionary, state: Dictionary) -> void:
    var cell: Vector2i = state["cell"]
    var ready: String = deck["pickups"].get(cell, "")
    var destination: String = deck["drops"].get(cell, "")
    if state["carrying"] == "" and ready != "" and ready not in state["delivered"]:
        state["carrying"] = ready
        state["message"] = "Parcel %s aboard." % ready.to_upper()
    elif state["carrying"] != "" and state["carrying"] == destination:
        state["delivered"].append(destination)
        state["carrying"] = ""
        state["message"] = "Parcel delivered to %s." % destination.to_upper()
    else:
        state["message"] = "Turn %d." % state["tick"]
    if cell == deck["exit"] and state["delivered"].size() == deck["pickups"].size():
        state["complete"] = true
        state["message"] = "All parcels delivered. Departure ready!"

static func parse_level(raw: Dictionary) -> Dictionary:
    var rows: Variant = raw.get("rows", [])
    var patrol: Variant = raw.get("cart", [])
    if not rows is Array or rows.is_empty() or not patrol is Array or patrol.is_empty():
        return {}
    if not rows[0] is String:
        return {}
    var width: int = rows[0].length()
    var deck := {
        "title": str(raw.get("title", "Training Deck")), "width": width, "height": rows.size(),
        "start": Vector2i(-1, -1), "exit": Vector2i(-1, -1), "walls": {},
        "pickups": {}, "drops": {}, "hatches": {}, "cart": []
    }
    var ends := {"1": [], "2": []}
    for row in range(rows.size()):
        if not rows[row] is String or rows[row].length() != width:
            return {}
        for col in range(width):
            var cell := Vector2i(col, row)
            var tile: String = rows[row][col]
            match tile:
                "#": deck["walls"][cell] = true
                "@": deck["start"] = cell
                "x": deck["exit"] = cell
                "a", "b", "c": deck["pickups"][cell] = tile
                "A", "B", "C": deck["drops"][cell] = tile.to_lower()
                "1", "2": ends[tile].append(cell)
                ".": pass
                _: return {}
    if deck["start"].x < 0 or deck["exit"].x < 0:
        return {}
    for pair: Array in ends.values():
        if pair.size() == 2:
            deck["hatches"][pair[0]] = pair[1]
            deck["hatches"][pair[1]] = pair[0]
        elif not pair.is_empty():
            return {}
    for point: Variant in patrol:
        if not point is Array or point.size() != 2:
            return {}
        var cell := Vector2i(int(point[0]), int(point[1]))
        if not on_floor(deck, cell):
            return {}
        deck["cart"].append(cell)
    return deck

static func load_decks(path: String) -> Array[Dictionary]:
    var decks: Array[Dictionary] = []
    if not FileAccess.file_exists(path):
        return decks
    var data: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
    if not data is Array:
        return decks
    for entry: Variant in data:
        if entry is Dictionary:
            var deck := parse_level(entry)
            if not deck.is_empty():
                decks.append(deck)
    return decks

static func next_state(deck: Dictionary, before: Dictionary, action: String) -> Dictionary:
    var after := before.duplicate(true)
    advance(deck, after, action)
    return after

static func state_key(deck: Dictionary, state: Dictionary) -> String:
    var cycle: int = state["tick"] % deck["cart"].size()
    var delivered: Array = state["delivered"].duplicate()
    delivered.sort()
    return "%s|%d|%s|%s" % [state["cell"], cycle, state["carrying"], delivered]

static func find_route(deck: Dictionary, start: Dictionary) -> Array[String]:
    var queue: Array[Dictionary] = [{"state": start, "route": []}]
    var seen := {state_key(deck, start): true}
    var cursor := 0
    while cursor < queue.size():
        var item: Dictionary = queue[cursor]
        cursor += 1
        var current: Dictionary = item["state"]
        if current["complete"]:
            var answer: Array[String] = []
            answer.assign(item["route"])
            return answer
        for action: String in ["N", "E", "S", "W", "WAIT"]:
            var candidate := next_state(deck, current, action)
            var key := state_key(deck, candidate)
            if candidate["caught"] or seen.has(key):
                continue
            seen[key] = true
            var route: Array = item["route"].duplicate()
            route.append(action)
            queue.append({"state": candidate, "route": route})
    return []

static func replay(deck: Dictionary, actions: Array[String]) -> Dictionary:
    var state := initial_state(deck)
    for action: String in actions:
        state = next_state(deck, state, action)
    return state

static func run_tests(deck: Dictionary) -> String:
    var failures: Array[String] = []
    var start := initial_state(deck)
    var blocked := next_state(deck, start, "N")
    if blocked["cell"] != start["cell"] or blocked["tick"] != 0:
        failures.append("bulkhead did not stop the turn")
    var waited := next_state(deck, start, "WAIT")
    if waited["cell"] != start["cell"] or waited["tick"] != 1:
        failures.append("wait changed the wrong fields")
    var path := find_route(deck, start)
    var final_a := replay(deck, path)
    var final_b := replay(deck, path)
    if path.is_empty() or not final_a["complete"] or final_a["caught"]:
        failures.append("solver did not finish a clean run")
    if final_a != final_b or start["tick"] != 0:
        failures.append("same actions changed the result or the input")
    if failures.is_empty():
        return "Four route checks passed • %d turns." % path.size()
    return "Check: " + "; ".join(failures)

decks.json

[
  {
    "title": "Moonlit Promenade",
    "rows": [
      "#########",
      "#@..a.Ax#",
      "#.#...#.#",
      "#1.....1#",
      "#########"
    ],
    "cart": [
      [
        3,
        1
      ],
      [
        4,
        1
      ],
      [
        4,
        2
      ],
      [
        3,
        2
      ]
    ]
  },
  {
    "title": "Grand Atrium",
    "rows": [
      "#########",
      "#@..a..x#",
      "#.#.#.#.#",
      "#A1...1.#",
      "#########"
    ],
    "cart": [
      [
        3,
        1
      ],
      [
        5,
        1
      ],
      [
        5,
        2
      ],
      [
        3,
        2
      ]
    ]
  },
  {
    "title": "Service Deck",
    "rows": [
      "#########",
      "#@1....x#",
      "#.###.#.#",
      "#a.A.1..#",
      "#########"
    ],
    "cart": [
      [
        4,
        1
      ],
      [
        5,
        1
      ],
      [
        5,
        2
      ],
      [
        5,
        1
      ]
    ]
  }
]

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 ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules.
  2. const Rules = preload("res://route_rules.gd")Creates a constant named Rules. The expression prepares a resource at a fixed project path when the script is loaded.
  3. const LABEL_BLUE := Color("#b4d9e5")Creates a constant named LABEL_BLUE. The expression builds a colour from these values. Godot infers the type from the first value.
  4. const PAPER := Color("#fff1ca")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  5. var deck: DictionaryDeclares deck for later use. A colon followed by a type says which kind of value belongs here.
  6. var available: Array[Dictionary]Declares available for later use. A colon followed by a type says which kind of value belongs here.
  7. var active := 0Creates a variable named active. The expression uses the whole number 0. Godot infers the type from the first value.
  8. var state: DictionaryDeclares state for later use. A colon followed by a type says which kind of value belongs here.
  9. var heading: LabelDeclares heading for later use. A colon followed by a type says which kind of value belongs here.
  10. var board: LabelDeclares board for later use. A colon followed by a type says which kind of value belongs here.
  11. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  12. var folder: VBoxContainerDeclares folder for later use. A colon followed by a type says which kind of value belongs here.
  13. 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.
  14. var backdrop := ColorRect.new()Creates a variable named backdrop. The expression creates a new ColorRect object. Godot infers the type from the first value.
  15. backdrop.color = Color("#071f30")Stores the new value in backdrop.color. The expression builds a colour from these values.
  16. backdrop.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent.
  17. backdrop.mouse_filter = Control.MOUSE_FILTER_IGNOREUpdates backdrop.mouse_filter, which controls how this control participates in pointer and touch input. The expression reads Control.MOUSE_FILTER_IGNORE.
  18. add_child(backdrop)Adds the new node to the scene tree so that Godot can run and draw it.
  19. folder = VBoxContainer.new()Stores the new value in folder. The expression creates a new VBoxContainer object.
  20. folder.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent.
  21. folder.offset_left = 22Stores the new value in folder.offset_left. The expression uses the whole number 22.
  22. folder.offset_right = -22Stores the new value in folder.offset_right. The expression reads -22.
  23. folder.offset_top = 14Stores the new value in folder.offset_top. The expression uses the whole number 14.
  24. folder.offset_bottom = -12Stores the new value in folder.offset_bottom. The expression reads -12.
  25. folder.add_theme_constant_override("separation", 8)Calls folder.add_theme_constant_override with the values in its parentheses.
  26. add_child(folder)Adds the new node to the scene tree so that Godot can run and draw it.
  27. heading = make_label("", 27, PAPER)Stores the new value in heading. The expression calls make_label with the values in its parentheses.
  28. make_label("MIDNIGHT DECK DASH / TRAINING DECK", 15, LABEL_BLUE)Calls make_label with the values in its parentheses.
  29. board = make_label("", 28, PAPER)Stores the new value in board. The expression calls make_label with the values in its parentheses.
  30. var mono := SystemFont.new()Creates a variable named mono. The expression creates a new SystemFont object. Godot infers the type from the first value.
  31. mono.font_names = PackedStringArray(["DejaVu Sans Mono", "Courier New", "monospace"])Stores the new value in mono.font_names. The expression calls PackedStringArray with the values in its parentheses.
  32. board.add_theme_font_override("font", mono)Calls board.add_theme_font_override with the values in its parentheses.
  33. make_label("@ You O Trolley a Parcel A Delivery X Departure # Wall ≋ Hatch", 14, LABEL_BLUE)Calls make_label with the values in its parentheses.
  34. status = make_label("", 17, PAPER)Stores the new value in status. The expression calls make_label with the values in its parentheses.
  35. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTStores the new value in status.autowrap_mode. The expression reads TextServer.AUTOWRAP_WORD_SMART.
  36. status.custom_minimum_size.y = 48Stores the new value in status.custom_minimum_size.y. The expression uses the whole number 48.
  37. var controls := HBoxContainer.new()Creates a variable named controls. The expression creates a new HBoxContainer object. Godot infers the type from the first value.
  38. controls.add_theme_constant_override("separation", 6)Calls controls.add_theme_constant_override with the values in its parentheses.
  39. folder.add_child(controls)Adds the new node to the scene tree so that Godot can run and draw it.
  40. make_button(controls, "North", _move.bind("N"))Calls make_button with the values in its parentheses.
  41. make_button(controls, "West", _move.bind("W"))Calls make_button with the values in its parentheses.
  42. make_button(controls, "South", _move.bind("S"))Calls make_button with the values in its parentheses.
  43. make_button(controls, "East", _move.bind("E"))Calls make_button with the values in its parentheses.
  44. make_button(controls, "Wait", _move.bind("WAIT"))Calls make_button with the values in its parentheses.
  45. make_button(controls, "Reset", _reset)Calls make_button with the values in its parentheses.
  46. make_button(controls, "Next deck", _next)Calls make_button with the values in its parentheses.
  47. make_button(controls, "Peek east", _peek)Calls make_button with the values in its parentheses.
  48. make_button(controls, "Hint", _hint)Calls make_button with the values in its parentheses.
  49. make_button(controls, "Test", _test)Calls make_button with the values in its parentheses.
  50. available = Rules.load_decks("res://decks.json")Stores the new value in available. The expression calls Rules.load_decks with the values in its parentheses.
  51. if available.is_empty():Checks available.is_empty(). The indented instructions below run only if this test passes.
  52. available = [Rules.first_deck()]Stores the new value in available. The expression makes a list whose items keep their order.
  53. _reset()Calls _reset with the values in its parentheses.
  54. func make_label(words: String, px: int, ink: Color) -> 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.
  55. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  56. label.text = wordsUpdates label.text, which controls the words a player sees. The expression reads words.
  57. label.add_theme_font_size_override("font_size", px)Calls label.add_theme_font_size_override with the values in its parentheses.
  58. label.add_theme_color_override("font_color", ink)Calls label.add_theme_color_override with the values in its parentheses.
  59. folder.add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  60. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  61. func make_button(parent: HBoxContainer, words: String, callback: Callable) -> void: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.
  62. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  63. button.text = wordsUpdates button.text, which controls the words a player sees. The expression reads words.
  64. button.custom_minimum_size = Vector2(70, 40)Updates button.custom_minimum_size, which controls the smallest space the layout should reserve for this control. The expression packs x and y into one value.
  65. button.pressed.connect(callback)Links a signal to the function that should run when the event happens.
  66. parent.add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  67. func _reset() -> void:Defines reset, 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.
  68. deck = available[active]Stores the new value in deck. The expression looks up the item or key written between the square brackets.
  69. state = Rules.initial_state(deck)Stores the new value in state. The expression calls Rules.initial_state with the values in its parentheses.
  70. refresh()Calls refresh with the values in its parentheses.
  71. func _move(action: String) -> void:Defines move, 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.
  72. state = Rules.next_state(deck, state, action)Stores the new value in state. The expression calls Rules.next_state with the values in its parentheses.
  73. refresh()Calls refresh with the values in its parentheses.
  74. func refresh() -> 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.
  75. heading.text = deck["title"]Updates heading.text, which controls the words a player sees. The expression looks up the item or key written between the square brackets.
  76. var view := ""Creates a variable named view. The expression uses the text inside the quotes. Godot infers the type from the first value.
  77. var cart := Rules.cart_cell(deck, state["tick"])Creates a variable named cart. The expression calls Rules.cart_cell with the values in its parentheses. Godot infers the type from the first value.
  78. for row in range(deck["height"]):Repeats the indented instructions for each value in range(deck["height"]).
  79. for col in range(deck["width"]):Repeats the indented instructions for each value in range(deck["width"]).
  80. var cell := Vector2i(col, row)Creates a variable named cell. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  81. var mark := "."Creates a variable named mark. The expression uses the text inside the quotes. Godot infers the type from the first value.
  82. if deck["walls"].has(cell):Checks deck["walls"].has(cell). The indented instructions below run only if this test passes.
  83. mark = "#"Stores the new value in mark. The expression uses the text inside the quotes.
  84. elif cell == deck["exit"]:If the earlier branches did not run, checks cell == deck["exit"] next.
  85. mark = "X"Stores the new value in mark. The expression uses the text inside the quotes.
  86. elif deck["pickups"].has(cell) and deck["pickups"][cell] not in state["delivered"] and state["carrying"] != deck["pickups"][cell]:If the earlier branches did not run, checks deck["pickups"].has(cell) and deck["pickups"][cell] not in state["delivered"] and state["carrying"] != deck["pickups"][cell] next.
  87. mark = deck["pickups"][cell]Stores the new value in mark. The expression looks up the item or key written between the square brackets.
  88. elif deck["drops"].has(cell):If the earlier branches did not run, checks deck["drops"].has(cell) next.
  89. mark = deck["drops"][cell].to_upper()Stores the new value in mark. The expression looks up the item or key written between the square brackets.
  90. elif deck["hatches"].has(cell):If the earlier branches did not run, checks deck["hatches"].has(cell) next.
  91. mark = "≋"Stores the new value in mark. The expression uses the text inside the quotes.
  92. if cell == cart:Checks cell == cart. The indented instructions below run only if this test passes.
  93. mark = "O"Stores the new value in mark. The expression uses the text inside the quotes.
  94. if cell == state["cell"]:Checks cell == state["cell"]. The indented instructions below run only if this test passes.
  95. mark = "!" if state["caught"] else "@"Stores the new value in mark. The expression chooses one of two values by checking the condition in the middle.
  96. view += mark + " "Reads view, adds to its old value, then stores the result back in the same place.
  97. view += "Reads view, adds to its old value, then stores the result back in the same place.
  98. "Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  99. board.text = view.strip_edges()Updates board.text, which controls the words a player sees. The expression removes spacing at the start and end of the text.
  100. var cargo: String = state["carrying"].to_upper() if state["carrying"] != "" else "Empty"Creates a variable named cargo. The expression chooses one of two values by checking the condition in the middle. The type after the colon says what kind of value it can hold.
  101. status.text = "Turn %d • Cargo: %s • %s" % [state["tick"], cargo, state["message"]]Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  102. func _next() -> void:Defines next, 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.
  103. active = (active + 1) % available.size()Stores the new value in active. The expression calculates a new value from the expressions on either side of the operator.
  104. _reset()Calls _reset with the values in its parentheses.
  105. func _peek() -> void:Defines peek, 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.
  106. var trial := Rules.next_state(deck, state, "E")Creates a variable named trial. The expression calls Rules.next_state with the values in its parentheses. Godot infers the type from the first value.
  107. status.text = "If east: turn %d • %s • Live turn still %d." % [trial["tick"], trial["message"], state["tick"]]Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  108. func _hint() -> void:Defines hint, 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.
  109. var route := Rules.find_route(deck, state)Creates a variable named route. The expression calls Rules.find_route with the values in its parentheses. Godot infers the type from the first value.
  110. if state["complete"]:Checks state["complete"]. The indented instructions below run only if this test passes.
  111. status.text = "Delivery complete!"Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  112. elif route.is_empty():If the earlier branches did not run, checks route.is_empty() next.
  113. status.text = "No safe route from here. Reset to try again."Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  114. else:Runs the indented fallback instructions if none of the earlier tests passed.
  115. status.text = "Safe hint: %s • %d turns to finish." % [route[0], route.size()]Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  116. func _test() -> void:Defines test, 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.
  117. status.text = Rules.run_tests(deck)Updates status.text, which controls the words a player sees. The expression calls Rules.run_tests with the values in its parentheses.
Read route_rules.gd line by line
  1. extends RefCountedStarts with Godot's RefCounted type. This script gets the abilities of that type and adds the game's own rules.
  2. const DELTAS := {Creates a constant named DELTAS. The expression makes a dictionary that looks up values by key. Godot infers the type from the first value.
  3. "N": Vector2i(0, -1), "E": Vector2i(1, 0),Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  4. "S": Vector2i(0, 1), "W": Vector2i(-1, 0),Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  5. "WAIT": Vector2i.ZEROContinues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  6. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  7. static func first_deck() -> Dictionary:Defines first deck, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  8. return parse_level({Finishes the function and hands its result back to the caller. The expression calls parse_level with the values in its parentheses.
  9. "title": "Moonlit Promenade",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  10. "rows": ["#########", "#@..a.Ax#", "#.#...#.#", "#1.....1#", "#########"],Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  11. "cart": [[3, 1], [4, 1], [4, 2], [3, 2]]Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  12. })Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  13. static func initial_state(deck: Dictionary) -> Dictionary:Defines initial state, 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.
  14. return {Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  15. "cell": deck["start"], "tick": 0, "carrying": "",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  16. "delivered": [], "caught": false, "complete": false,Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  17. "message": "Deliver the parcel, then reach X."Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  18. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  19. static func cart_cell(deck: Dictionary, tick: int) -> Vector2i:Defines cart cell, 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. var patrol: Array = deck["cart"]Creates a variable named patrol. 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.
  21. return patrol[tick % patrol.size()]Finishes the function and hands its result back to the caller. The expression looks up the item or key written between the square brackets.
  22. static func on_floor(deck: Dictionary, cell: Vector2i) -> bool:Defines on floor, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  23. return cell.x >= 0 and cell.y >= 0 and cell.x < deck["width"] and cell.y < deck["height"] and not deck["walls"].has(cell)Finishes the function and hands its result back to the caller. The expression evaluates the test to see whether it is true or false.
  24. static func advance(deck: Dictionary, state: Dictionary, action: String) -> void:Defines advance, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  25. if state["caught"] or state["complete"]:Checks state["caught"] or state["complete"]. The indented instructions below run only if this test passes.
  26. returnFinishes the function right here. Any later instructions in this function are skipped.
  27. if not DELTAS.has(action):Checks not DELTAS.has(action). The indented instructions below run only if this test passes.
  28. returnFinishes the function right here. Any later instructions in this function are skipped.
  29. var origin: Vector2i = state["cell"]Creates a variable named origin. 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.
  30. var step: Vector2i = DELTAS[action]Creates a variable named step. 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.
  31. var arrival := origin + stepCreates a variable named arrival. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  32. if not on_floor(deck, arrival):Checks not on_floor(deck, arrival). The indented instructions below run only if this test passes.
  33. state["message"] = "Bulkhead: no turn spent."Stores the new value in state["message"]. The expression uses the text inside the quotes.
  34. returnFinishes the function right here. Any later instructions in this function are skipped.
  35. if action != "WAIT" and deck["hatches"].has(arrival):Checks action != "WAIT" and deck["hatches"].has(arrival). The indented instructions below run only if this test passes.
  36. arrival = deck["hatches"][arrival]Stores the new value in arrival. The expression looks up the item or key written between the square brackets.
  37. var old_cart := cart_cell(deck, state["tick"])Creates a variable named old_cart. The expression calls cart_cell with the values in its parentheses. Godot infers the type from the first value.
  38. state["cell"] = arrivalStores the new value in state["cell"]. The expression reads arrival.
  39. state["tick"] += 1Reads state["tick"], adds to its old value, then stores the result back in the same place.
  40. var new_cart := cart_cell(deck, state["tick"])Creates a variable named new_cart. The expression calls cart_cell with the values in its parentheses. Godot infers the type from the first value.
  41. var overtake := old_cart == arrival and new_cart == originCreates a variable named overtake. The expression evaluates the test to see whether it is true or false. Godot infers the type from the first value.
  42. if arrival == new_cart or overtake:Checks arrival == new_cart or overtake. The indented instructions below run only if this test passes.
  43. state["caught"] = trueStores the new value in state["caught"]. The expression uses the yes-or-no value true.
  44. state["message"] = "Trolley in the lane. Reset to try again."Stores the new value in state["message"]. The expression uses the text inside the quotes.
  45. returnFinishes the function right here. Any later instructions in this function are skipped.
  46. apply_delivery(deck, state)Calls apply_delivery with the values in its parentheses.
  47. static func apply_delivery(deck: Dictionary, state: Dictionary) -> void:Defines apply delivery, 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.
  48. var cell: Vector2i = state["cell"]Creates a variable named cell. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold.
  49. var ready: String = deck["pickups"].get(cell, "")Creates a variable named ready. 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.
  50. var destination: String = deck["drops"].get(cell, "")Creates a variable named destination. 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.
  51. if state["carrying"] == "" and ready != "" and ready not in state["delivered"]:Checks state["carrying"] == "" and ready != "" and ready not in state["delivered"]. The indented instructions below run only if this test passes.
  52. state["carrying"] = readyStores the new value in state["carrying"]. The expression reads ready.
  53. state["message"] = "Parcel %s aboard." % ready.to_upper()Stores the new value in state["message"]. The expression uses the text inside the quotes.
  54. elif state["carrying"] != "" and state["carrying"] == destination:If the earlier branches did not run, checks state["carrying"] != "" and state["carrying"] == destination next.
  55. state["delivered"].append(destination)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  56. state["carrying"] = ""Stores the new value in state["carrying"]. The expression uses the text inside the quotes.
  57. state["message"] = "Parcel delivered to %s." % destination.to_upper()Stores the new value in state["message"]. The expression uses the text inside the quotes.
  58. else:Runs the indented fallback instructions if none of the earlier tests passed.
  59. state["message"] = "Turn %d." % state["tick"]Stores the new value in state["message"]. The expression uses the text inside the quotes.
  60. if cell == deck["exit"] and state["delivered"].size() == deck["pickups"].size():Checks cell == deck["exit"] and state["delivered"].size() == deck["pickups"].size(). The indented instructions below run only if this test passes.
  61. state["complete"] = trueStores the new value in state["complete"]. The expression uses the yes-or-no value true.
  62. state["message"] = "All parcels delivered. Departure ready!"Stores the new value in state["message"]. The expression uses the text inside the quotes.
  63. static func parse_level(raw: Dictionary) -> Dictionary:Defines parse level, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  64. var rows: Variant = raw.get("rows", [])Creates a variable named rows. The expression looks up a named or indexed value, using a fallback when the call gives one. The type after the colon says what kind of value it can hold.
  65. var patrol: Variant = raw.get("cart", [])Creates a variable named patrol. The expression looks up a named or indexed value, using a fallback when the call gives one. The type after the colon says what kind of value it can hold.
  66. if not rows is Array or rows.is_empty() or not patrol is Array or patrol.is_empty():Checks not rows is Array or rows.is_empty() or not patrol is Array or patrol.is_empty(). The indented instructions below run only if this test passes.
  67. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  68. if not rows[0] is String:Checks not rows[0] is String. The indented instructions below run only if this test passes.
  69. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  70. var width: int = rows[0].length()Creates a variable named width. 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.
  71. var deck := {Creates a variable named deck. The expression makes a dictionary that looks up values by key. Godot infers the type from the first value.
  72. "title": str(raw.get("title", "Training Deck")), "width": width, "height": rows.size(),Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  73. "start": Vector2i(-1, -1), "exit": Vector2i(-1, -1), "walls": {},Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  74. "pickups": {}, "drops": {}, "hatches": {}, "cart": []Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  75. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  76. var ends := {"1": [], "2": []}Creates a variable named ends. The expression makes a dictionary that looks up values by key. Godot infers the type from the first value.
  77. for row in range(rows.size()):Repeats the indented instructions for each value in range(rows.size()).
  78. if not rows[row] is String or rows[row].length() != width:Checks not rows[row] is String or rows[row].length() != width. The indented instructions below run only if this test passes.
  79. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  80. for col in range(width):Repeats the indented instructions for each value in range(width).
  81. var cell := Vector2i(col, row)Creates a variable named cell. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  82. var tile: String = rows[row][col]Creates a variable named tile. 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.
  83. match tile:Compares tile to the patterns below and runs the first matching branch.
  84. "#": deck["walls"][cell] = trueContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  85. "@": deck["start"] = cellContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  86. "x": deck["exit"] = cellStores the new value in "x": deck["exit"]. The expression reads cell.
  87. "a", "b", "c": deck["pickups"][cell] = tileContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  88. "A", "B", "C": deck["drops"][cell] = tile.to_lower()Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  89. "1", "2": ends[tile].append(cell)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  90. ".": passContinues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  91. _: return {}Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  92. if deck["start"].x < 0 or deck["exit"].x < 0:Checks deck["start"].x < 0 or deck["exit"].x < 0. The indented instructions below run only if this test passes.
  93. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  94. for pair: Array in ends.values():Repeats the indented instructions for each value in ends.values().
  95. if pair.size() == 2:Checks pair.size() == 2. The indented instructions below run only if this test passes.
  96. deck["hatches"][pair[0]] = pair[1]Stores the new value in deck["hatches"][pair[0]]. The expression looks up the item or key written between the square brackets.
  97. deck["hatches"][pair[1]] = pair[0]Stores the new value in deck["hatches"][pair[1]]. The expression looks up the item or key written between the square brackets.
  98. elif not pair.is_empty():If the earlier branches did not run, checks not pair.is_empty() next.
  99. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  100. for point: Variant in patrol:Repeats the indented instructions for each value in patrol.
  101. if not point is Array or point.size() != 2:Checks not point is Array or point.size() != 2. The indented instructions below run only if this test passes.
  102. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  103. var cell := Vector2i(int(point[0]), int(point[1]))Creates a variable named cell. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  104. if not on_floor(deck, cell):Checks not on_floor(deck, cell). The indented instructions below run only if this test passes.
  105. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  106. deck["cart"].append(cell)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  107. return deckFinishes the function and hands its result back to the caller. The expression reads deck.
  108. static func load_decks(path: String) -> Array[Dictionary]:Defines load decks, 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.
  109. var decks: Array[Dictionary] = []Creates a variable named decks. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  110. if not FileAccess.file_exists(path):Checks not FileAccess.file_exists(path). The indented instructions below run only if this test passes.
  111. return decksFinishes the function and hands its result back to the caller. The expression reads decks.
  112. var data: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))Creates a variable named data. The expression tries to turn JSON text back into a value. The type after the colon says what kind of value it can hold.
  113. if not data is Array:Checks not data is Array. The indented instructions below run only if this test passes.
  114. return decksFinishes the function and hands its result back to the caller. The expression reads decks.
  115. for entry: Variant in data:Repeats the indented instructions for each value in data.
  116. if entry is Dictionary:Checks entry is Dictionary. The indented instructions below run only if this test passes.
  117. var deck := parse_level(entry)Creates a variable named deck. The expression calls parse_level with the values in its parentheses. Godot infers the type from the first value.
  118. if not deck.is_empty():Checks not deck.is_empty(). The indented instructions below run only if this test passes.
  119. decks.append(deck)Adds an item to the end of a list.
  120. return decksFinishes the function and hands its result back to the caller. The expression reads decks.
  121. static func next_state(deck: Dictionary, before: Dictionary, action: String) -> Dictionary:Defines next state, 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.
  122. var after := before.duplicate(true)Creates a variable named after. The expression copies the collection so a later change can leave the original alone. Godot infers the type from the first value.
  123. advance(deck, after, action)Calls advance with the values in its parentheses.
  124. return afterFinishes the function and hands its result back to the caller. The expression reads after.
  125. static func state_key(deck: Dictionary, 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.
  126. var cycle: int = state["tick"] % deck["cart"].size()Creates a variable named cycle. 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.
  127. var delivered: Array = state["delivered"].duplicate()Creates a variable named delivered. 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.
  128. delivered.sort()Calls delivered.sort with the values in its parentheses.
  129. return "%s|%d|%s|%s" % [state["cell"], cycle, state["carrying"], delivered]Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  130. static func find_route(deck: Dictionary, start: 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.
  131. var queue: Array[Dictionary] = [{"state": start, "route": []}]Creates a variable named queue. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  132. var seen := {state_key(deck, start): true}Creates a variable named seen. The expression makes a dictionary that looks up values by key. Godot infers the type from the first value.
  133. var cursor := 0Creates a variable named cursor. The expression uses the whole number 0. Godot infers the type from the first value.
  134. while cursor < queue.size():Keeps repeating while cursor < queue.size() stays true. The loop body should eventually change the result or leave with break.
  135. var item: Dictionary = queue[cursor]Creates a variable named item. 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.
  136. cursor += 1Reads cursor, adds to its old value, then stores the result back in the same place.
  137. var current: Dictionary = item["state"]Creates a variable named current. 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.
  138. if current["complete"]:Checks current["complete"]. The indented instructions below run only if this test passes.
  139. var answer: Array[String] = []Creates a variable named answer. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  140. answer.assign(item["route"])Calls answer.assign with the values in its parentheses.
  141. return answerFinishes the function and hands its result back to the caller. The expression reads answer.
  142. for action: String in ["N", "E", "S", "W", "WAIT"]:Repeats the indented instructions for each value in ["N", "E", "S", "W", "WAIT"].
  143. var candidate := next_state(deck, current, action)Creates a variable named candidate. The expression calls next_state with the values in its parentheses. Godot infers the type from the first value.
  144. var key := state_key(deck, candidate)Creates a variable named key. The expression calls state_key with the values in its parentheses. Godot infers the type from the first value.
  145. if candidate["caught"] or seen.has(key):Checks candidate["caught"] or seen.has(key). The indented instructions below run only if this test passes.
  146. continueSkips the rest of this turn through the loop and moves on to the next item.
  147. seen[key] = trueStores the new value in seen[key]. The expression uses the yes-or-no value true.
  148. var route: Array = item["route"].duplicate()Creates a variable named route. 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.
  149. route.append(action)Adds an item to the end of a list.
  150. queue.append({"state": candidate, "route": route})Adds an item to the end of a list.
  151. return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order.
  152. static func replay(deck: 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.
  153. var state := initial_state(deck)Creates a variable named state. The expression calls initial_state with the values in its parentheses. Godot infers the type from the first value.
  154. for action: String in actions:Repeats the indented instructions for each value in actions.
  155. state = next_state(deck, state, action)Stores the new value in state. The expression calls next_state with the values in its parentheses.
  156. return stateFinishes the function and hands its result back to the caller. The expression reads state.
  157. static func run_tests(deck: Dictionary) -> String:Defines run tests, 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.
  158. var failures: Array[String] = []Creates a variable named failures. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  159. var start := initial_state(deck)Creates a variable named start. The expression calls initial_state with the values in its parentheses. Godot infers the type from the first value.
  160. var blocked := next_state(deck, start, "N")Creates a variable named blocked. The expression calls next_state with the values in its parentheses. Godot infers the type from the first value.
  161. if blocked["cell"] != start["cell"] or blocked["tick"] != 0:Checks blocked["cell"] != start["cell"] or blocked["tick"] != 0. The indented instructions below run only if this test passes.
  162. failures.append("bulkhead did not stop the turn")Adds an item to the end of a list.
  163. var waited := next_state(deck, start, "WAIT")Creates a variable named waited. The expression calls next_state with the values in its parentheses. Godot infers the type from the first value.
  164. if waited["cell"] != start["cell"] or waited["tick"] != 1:Checks waited["cell"] != start["cell"] or waited["tick"] != 1. The indented instructions below run only if this test passes.
  165. failures.append("wait changed the wrong fields")Adds an item to the end of a list.
  166. var path := find_route(deck, start)Creates a variable named path. The expression calls find_route with the values in its parentheses. Godot infers the type from the first value.
  167. var final_a := replay(deck, path)Creates a variable named final_a. The expression calls replay with the values in its parentheses. Godot infers the type from the first value.
  168. var final_b := replay(deck, path)Creates a variable named final_b. The expression calls replay with the values in its parentheses. Godot infers the type from the first value.
  169. if path.is_empty() or not final_a["complete"] or final_a["caught"]:Checks path.is_empty() or not final_a["complete"] or final_a["caught"]. The indented instructions below run only if this test passes.
  170. failures.append("solver did not finish a clean run")Adds an item to the end of a list.
  171. if final_a != final_b or start["tick"] != 0:Checks final_a != final_b or start["tick"] != 0. The indented instructions below run only if this test passes.
  172. failures.append("same actions changed the result or the input")Adds an item to the end of a list.
  173. if failures.is_empty():Checks failures.is_empty(). The indented instructions below run only if this test passes.
  174. return "Four route checks passed • %d turns." % path.size()Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  175. return "Check: " + "; ".join(failures)Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.

decks.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 a custom deck's start square has no north wall, change the fixture to use a known blocked action for its layout before claiming the collision change broke it.

Try a change

Design an extra regression check for the two-way hatch. Assert that the landing cell is the partner and that the trip uses one turn.