Mobile Game 19 · Split the light to wake two exhibits

Museum of Lost Lights · Lesson 19 of 50 · Intermediate · About 44 min

In the Space Lanterns room, one beam must reach two dark exhibits. A splitter can pass light straight through while reflecting a second beam.

A gouache painting of a Fossil Gallery with amber lights, tall prehistoric skeleton displays and a dark stone floor.
What you’ll make Build a splitter that lets one ray become two and solve a room with two exhibits.

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

Reach a splitter. One ray enters from the west. → Keep the straight ray. Continue east towards target 14. → Add a reflected ray. Send the second ray south to mirror 17. → Check two exhibits. Both lit addresses are needed for a win.
Reach a splitter → Keep the straight ray → Add a reflected ray → Check two exhibits

Build it step by step

Language and tools in this lesson pending work list, append, Dictionary.get, or, multiple targets, Boolean completion.

  1. Sketch the new room’s layout

    Open ROOMS and find Space Lanterns. Mark the lamp 10, splitter 12, mirror 17, and targets 14 and 19. Draw the east path and the two possible reflection directions from 12.

    "direction": 1, "mirrors": {17: 1}, "splitters": {12: 0}, "targets": [14, 19]},

    Why it works splitters is a second dictionary of rotatable pieces. The room’s targets array lists two exhibits this time. Both are needed for completion.

  2. Allow rooms with and without splitters

    In beam_solver.gd locate the assignment to splitters. Trace it once with the Space card, then once with Ocean. Open _can_turn in main.gd and read the or check aloud.

    var splitters: Dictionary = layout.get("splitters", {})

    Why it works Dictionary.get takes a fallback as a second argument. Empty braces mean an empty Dictionary. or accepts a tile if it is in either piece table.

  3. Keep the straight ray and add the bounce

    Find the splitter branch in trace. Pause on the two pending.append lines. Follow a ray entering an orientation-1 splitter from the west. Name the two heading numbers added.

    pending.append(Vector2i(tile, bounced))

    Why it works The first append stores the reflected ray when a splitter is present. The second append adds the continuation with its existing heading. Their shared tile address tells each ray where to begin its next step.

  4. Show a splitter as a special piece

    Run the game, solve Ocean and Fossil and press Next room. Locate the tile with the Split label and press it. Follow its reflected branch down to tile 17.

    return "Split " + slash

    Why it works The label uses turnability to show a slant, then adds a Split name when the layout’s splitter keys contain that address. The same input handler changes slants for either piece kind.

  5. Make both exhibits count

    In _render review the size comparison. Starting in Space, check which goal is already awake. Turn splitter 12 and verify the second exhibit becomes Awake before the completion message appears.

    won = lit_targets.size() == layout["targets"].size()

    Why it works Each distinct lit target is recorded once, so an equal count means all required targets have been reached. Rebuilding the result on every turn also handles a ray that goes dark again.

Watch the values change

  1. Open Space Lanterns Splitter 12 begins at slant 0
    What you see. Straight east reaches 14. The reflected branch goes north.
  2. Turn splitter 12 Slant 1 keeps east and reflects south
    What you see. Light also passes through tile 17, whose backslash turns it east.
  3. Reach both targets lit contains 14 and 19
    What you see. The second exhibit wakes and Space Lanterns completes.

Predict before you run If mirror 17 were a slash when splitter 12 reflects south, would the Space Lanterns room complete?

Reveal the answer

No. A south ray reflects west on a slash. The east branch still reaches 14, but the new reflected path misses target 19.

Complete checkpoint

The first two rooms still work. In Space Lanterns, one turn on splitter 12 changes a single lit exhibit into two, completing the room.

main.gd

extends Control


const ROOMS := [
    {"name": "Ocean Gallery", "width": 5, "height": 5, "source": 10,
        "direction": 1, "mirrors": {12: 1}, "targets": [2]},
    {"name": "Fossil Passage", "width": 5, "height": 5, "source": 10,
        "direction": 1, "mirrors": {12: 1, 7: 1}, "targets": [9]},
    {"name": "Space Lanterns", "width": 5, "height": 5, "source": 10,
        "direction": 1, "mirrors": {17: 1}, "splitters": {12: 0}, "targets": [14, 19]},
]

const BeamSolver = preload("res://beam_solver.gd")

var grid: GridContainer
var status: Label
var tiles: Array[Button] = []
var active_path: Array[int] = []
var won := false
var room_index := 0
var layout: Dictionary
var rotations: Dictionary = {}
var lit_targets: Array = []


func _ready() -> void:
    var background := ColorRect.new()
    background.color = Color("#102a3b")
    background.mouse_filter = Control.MOUSE_FILTER_IGNORE
    add_child(background)
    background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)

    var centre := CenterContainer.new()
    add_child(centre)
    centre.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)

    var page := VBoxContainer.new()
    page.add_theme_constant_override("separation", 8)
    centre.add_child(page)

    var heading := Label.new()
    heading.text = "Museum of Lost Lights"
    heading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
    heading.add_theme_font_size_override("font_size", 26)
    page.add_child(heading)

    var subheading := Label.new()
    subheading.text = "Tap or keyboard-focus a mirror. Press the mirror to turn it."
    subheading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
    page.add_child(subheading)

    grid = GridContainer.new()
    grid.columns = int(ROOMS[0]["width"])
    grid.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
    page.add_child(grid)

    status = Label.new()
    status.custom_minimum_size.x = 460
    status.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
    page.add_child(status)

    var actions := HBoxContainer.new()
    actions.alignment = BoxContainer.ALIGNMENT_CENTER
    page.add_child(actions)
    _add_action(actions, "Hint", _show_hint)
    _add_action(actions, "Reset", _reset)
    _add_action(actions, "Help", _show_help)
    _add_action(actions, "Next room", _next_room)
    _load_room(0)


func _make_tiles() -> void:
    for index in range(int(layout["width"]) * int(layout["height"])):
        var tile := Button.new()
        tile.custom_minimum_size = Vector2(60, 48)
        tile.focus_mode = Control.FOCUS_ALL
        tile.pressed.connect(_tap_tile.bind(index))
        tiles.append(tile)
        grid.add_child(tile)


func _tap_tile(index: int) -> void:

    if won or not _can_turn(index):
        return
    var current := _orientation_at(index)
    rotations[index] = 1 - current
    _render()


func _trace_beam() -> Array[int]:
    var outcome := BeamSolver.trace(layout, rotations)
    lit_targets = outcome["lit"]
    var travelled: Array[int] = [int(layout["source"])]
    for segment: Dictionary in outcome["segments"]:
        var tile := int(segment["to"])
        if not travelled.has(tile):
            travelled.append(tile)
    return travelled


func _render() -> void:
    active_path = _trace_beam()
    won = lit_targets.size() == layout["targets"].size()
    for index in range(tiles.size()):
        var tile := tiles[index]
        tile.text = _tile_label(index)
        tile.modulate = Color("#9fece7") if active_path.has(index) else Color("#e8dcb9")

    if won:
        status.text = "%s complete!" % str(layout["name"])
    else:
        status.text = "%s · turn a mirror to guide the beam." % str(layout["name"])

func _tile_label(index: int) -> String:
    if index == int(layout["source"]):
        return "Lamp"
    if layout["targets"].has(index):
        return "Awake" if lit_targets.has(index) else "Goal"
    if _can_turn(index):
        var slash := "/" if _orientation_at(index) == 0 else "\\"
        if layout.get("splitters", {}).has(index):
            return "Split " + slash
        return slash
    if active_path.has(index):
        return "Beam"
    return str(index)


func _add_action(row: HBoxContainer, caption: String, action: Callable) -> Button:
    var button := Button.new()
    button.text = caption
    button.custom_minimum_size = Vector2(72, 36)
    button.pressed.connect(action)
    row.add_child(button)
    return button


func _show_hint() -> void:
    var turnables: Dictionary = layout["mirrors"]
    var choices: Array = turnables.keys() + layout.get("splitters", {}).keys()
    if choices.is_empty():
        status.text = "Follow the lamp beam in this room."
        return
    status.text = "Try one tile at a time. Mirror tile: %s." % str(choices[0])


func _reset() -> void:
    rotations.clear()
    _render()

func _show_help() -> void:
    status.text = "Tap the mirror. A keyboard player can use Tab, then Enter."

func _next_room() -> void:
    if not won:
        status.text = "Wake the exhibits before visiting the next room."
        return
    _load_room((room_index + 1) % ROOMS.size())


func _load_room(index: int) -> void:
    room_index = index
    layout = ROOMS[index]
    rotations.clear()
    for old_tile in tiles:
        grid.remove_child(old_tile)
        old_tile.queue_free()
    tiles.clear()
    grid.columns = int(layout["width"])
    _make_tiles()
    _render()


func _can_turn(index: int) -> bool:
    return layout["mirrors"].has(index) or layout.get("splitters", {}).has(index)


func _orientation_at(index: int) -> int:
    var starter := int(layout["mirrors"].get(index, layout.get("splitters", {}).get(index, 0)))
    return int(rotations.get(index, starter))

beam_solver.gd

extends RefCounted

const HEADINGS := [Vector2i(0, -1), Vector2i(1, 0), Vector2i(0, 1), Vector2i(-1, 0)]
const SLASH := [1, 0, 3, 2]
const BACKSLASH := [3, 2, 1, 0]


static func trace(layout: Dictionary, rotations: Dictionary) -> Dictionary:
    var width := int(layout["width"])
    var height := int(layout["height"])
    var mirrors: Dictionary = layout["mirrors"]
    var splitters: Dictionary = layout.get("splitters", {})
    var targets: Array = layout["targets"]
    var walls: Array = layout.get("walls", [])
    var pending: Array[Vector2i] = [Vector2i(int(layout["source"]), int(layout["direction"]))]
    var segments: Array[Dictionary] = []
    var lit: Array[int] = []
    var visited: Dictionary = {}
    var loop_found := false

    while not pending.is_empty():
        var ray: Vector2i = pending.pop_back()
        if visited.has(ray):
            loop_found = true
            continue
        visited[ray] = true

        @warning_ignore("integer_division")
        var row := ray.x / width
        var cell := Vector2i(ray.x % width, row)
        var next: Vector2i = cell + HEADINGS[ray.y]
        if not Rect2i(0, 0, width, height).has_point(next):
            continue

        var tile := next.y * width + next.x
        segments.append({"from": ray.x, "to": tile})
        if walls.has(tile):
            continue
        if targets.has(tile):
            if not lit.has(tile):
                lit.append(tile)
            continue

        var direction := ray.y
        if mirrors.has(tile):
            var slant := int(rotations.get(tile, mirrors[tile]))
            direction = _reflected(direction, slant)
        if splitters.has(tile):
            var splitter_slant := int(rotations.get(tile, splitters[tile]))
            var bounced := _reflected(direction, splitter_slant)
            pending.append(Vector2i(tile, bounced))
        pending.append(Vector2i(tile, direction))

    return {"segments": segments, "lit": lit, "loop": loop_found}


static func _reflected(heading: int, slant: int) -> int:
    if slant == 0:
        return SLASH[heading]
    return BACKSLASH[heading]

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 ROOMS := [Creates a constant named ROOMS. The expression makes a list whose items keep their order. Godot infers the type from the first value.
  3. {"name": "Ocean Gallery", "width": 5, "height": 5, "source": 10,Starts a list or dictionary used as part of the instruction above.
  4. "direction": 1, "mirrors": {12: 1}, "targets": [2]},Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  5. {"name": "Fossil Passage", "width": 5, "height": 5, "source": 10,Starts a list or dictionary used as part of the instruction above.
  6. "direction": 1, "mirrors": {12: 1, 7: 1}, "targets": [9]},Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  7. {"name": "Space Lanterns", "width": 5, "height": 5, "source": 10,Starts a list or dictionary used as part of the instruction above.
  8. "direction": 1, "mirrors": {17: 1}, "splitters": {12: 0}, "targets": [14, 19]},Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  9. ]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  10. const BeamSolver = preload("res://beam_solver.gd")Creates a constant named BeamSolver. The expression prepares a resource at a fixed project path when the script is loaded.
  11. var grid: GridContainerDeclares grid for later use. A colon followed by a type says which kind of value belongs here.
  12. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  13. var tiles: Array[Button] = []Creates a variable named tiles. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  14. var active_path: Array[int] = []Creates a variable named active_path. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  15. var won := falseCreates a variable named won. The expression uses the yes-or-no value false. Godot infers the type from the first value.
  16. var room_index := 0Creates a variable named room_index. The expression uses the whole number 0. Godot infers the type from the first value.
  17. var layout: DictionaryDeclares layout for later use. A colon followed by a type says which kind of value belongs here.
  18. var rotations: Dictionary = {}Creates a variable named rotations. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold.
  19. var lit_targets: Array = []Creates a variable named lit_targets. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  20. 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.
  21. var background := ColorRect.new()Creates a variable named background. The expression creates a new ColorRect object. Godot infers the type from the first value.
  22. background.color = Color("#102a3b")Stores the new value in background.color. The expression builds a colour from these values.
  23. background.mouse_filter = Control.MOUSE_FILTER_IGNOREUpdates background.mouse_filter, which controls how this control participates in pointer and touch input. The expression reads Control.MOUSE_FILTER_IGNORE.
  24. add_child(background)Adds the new node to the scene tree so that Godot can run and draw it.
  25. background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent.
  26. var centre := CenterContainer.new()Creates a variable named centre. The expression creates a new CenterContainer object. Godot infers the type from the first value.
  27. add_child(centre)Adds the new node to the scene tree so that Godot can run and draw it.
  28. centre.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent.
  29. var page := VBoxContainer.new()Creates a variable named page. The expression creates a new VBoxContainer object. Godot infers the type from the first value.
  30. page.add_theme_constant_override("separation", 8)Calls page.add_theme_constant_override with the values in its parentheses.
  31. centre.add_child(page)Adds the new node to the scene tree so that Godot can run and draw it.
  32. var heading := Label.new()Creates a variable named heading. The expression creates a new Label object. Godot infers the type from the first value.
  33. heading.text = "Museum of Lost Lights"Updates heading.text, which controls the words a player sees. The expression uses the text inside the quotes.
  34. heading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in heading.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER.
  35. heading.add_theme_font_size_override("font_size", 26)Calls heading.add_theme_font_size_override with the values in its parentheses.
  36. page.add_child(heading)Adds the new node to the scene tree so that Godot can run and draw it.
  37. var subheading := Label.new()Creates a variable named subheading. The expression creates a new Label object. Godot infers the type from the first value.
  38. subheading.text = "Tap or keyboard-focus a mirror. Press the mirror to turn it."Updates subheading.text, which controls the words a player sees. The expression uses the text inside the quotes.
  39. subheading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in subheading.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER.
  40. page.add_child(subheading)Adds the new node to the scene tree so that Godot can run and draw it.
  41. grid = GridContainer.new()Stores the new value in grid. The expression creates a new GridContainer object.
  42. grid.columns = int(ROOMS[0]["width"])Stores the new value in grid.columns. The expression converts a suitable value to a whole number.
  43. grid.size_flags_horizontal = Control.SIZE_SHRINK_CENTERStores the new value in grid.size_flags_horizontal. The expression reads Control.SIZE_SHRINK_CENTER.
  44. page.add_child(grid)Adds the new node to the scene tree so that Godot can run and draw it.
  45. status = Label.new()Stores the new value in status. The expression creates a new Label object.
  46. status.custom_minimum_size.x = 460Stores the new value in status.custom_minimum_size.x. The expression uses the whole number 460.
  47. status.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in status.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER.
  48. page.add_child(status)Adds the new node to the scene tree so that Godot can run and draw it.
  49. var actions := HBoxContainer.new()Creates a variable named actions. The expression creates a new HBoxContainer object. Godot infers the type from the first value.
  50. actions.alignment = BoxContainer.ALIGNMENT_CENTERUpdates actions.alignment, which controls how the control aligns its contents. The expression reads BoxContainer.ALIGNMENT_CENTER.
  51. page.add_child(actions)Adds the new node to the scene tree so that Godot can run and draw it.
  52. _add_action(actions, "Hint", _show_hint)Calls _add_action with the values in its parentheses.
  53. _add_action(actions, "Reset", _reset)Calls _add_action with the values in its parentheses.
  54. _add_action(actions, "Help", _show_help)Calls _add_action with the values in its parentheses.
  55. _add_action(actions, "Next room", _next_room)Calls _add_action with the values in its parentheses.
  56. _load_room(0)Calls _load_room with the values in its parentheses.
  57. func _make_tiles() -> void:Defines make tiles, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  58. for index in range(int(layout["width"]) * int(layout["height"])):Repeats the indented instructions for each value in range(int(layout["width"]) * int(layout["height"])).
  59. var tile := Button.new()Creates a variable named tile. The expression creates a new Button object. Godot infers the type from the first value.
  60. tile.custom_minimum_size = Vector2(60, 48)Updates tile.custom_minimum_size, which controls the smallest space the layout should reserve for this control. The expression packs x and y into one value.
  61. tile.focus_mode = Control.FOCUS_ALLStores the new value in tile.focus_mode. The expression reads Control.FOCUS_ALL.
  62. tile.pressed.connect(_tap_tile.bind(index))Links a signal to the function that should run when the event happens.
  63. tiles.append(tile)Adds an item to the end of a list.
  64. grid.add_child(tile)Adds the new node to the scene tree so that Godot can run and draw it.
  65. func _tap_tile(index: int) -> void:Defines tap tile, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  66. if won or not _can_turn(index):Checks won or not _can_turn(index). The indented instructions below run only if this test passes.
  67. returnFinishes the function right here. Any later instructions in this function are skipped.
  68. var current := _orientation_at(index)Creates a variable named current. The expression calls _orientation_at with the values in its parentheses. Godot infers the type from the first value.
  69. rotations[index] = 1 - currentStores the new value in rotations[index]. The expression calculates a new value from the expressions on either side of the operator.
  70. _render()Calls _render with the values in its parentheses.
  71. func _trace_beam() -> Array[int]:Defines trace beam, 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. var outcome := BeamSolver.trace(layout, rotations)Creates a variable named outcome. The expression calls BeamSolver.trace with the values in its parentheses. Godot infers the type from the first value.
  73. lit_targets = outcome["lit"]Stores the new value in lit_targets. The expression looks up the item or key written between the square brackets.
  74. var travelled: Array[int] = [int(layout["source"])]Creates a variable named travelled. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  75. for segment: Dictionary in outcome["segments"]:Repeats the indented instructions for each value in outcome["segments"].
  76. var tile := int(segment["to"])Creates a variable named tile. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  77. if not travelled.has(tile):Checks not travelled.has(tile). The indented instructions below run only if this test passes.
  78. travelled.append(tile)Adds an item to the end of a list.
  79. return travelledFinishes the function and hands its result back to the caller. The expression reads travelled.
  80. func _render() -> void:Defines render, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  81. active_path = _trace_beam()Stores the new value in active_path. The expression calls _trace_beam with the values in its parentheses.
  82. won = lit_targets.size() == layout["targets"].size()Stores the new value in won. The expression counts the items in this collection.
  83. for index in range(tiles.size()):Repeats the indented instructions for each value in range(tiles.size()).
  84. var tile := tiles[index]Creates a variable named tile. The expression looks up the item or key written between the square brackets. Godot infers the type from the first value.
  85. tile.text = _tile_label(index)Updates tile.text, which controls the words a player sees. The expression calls _tile_label with the values in its parentheses.
  86. tile.modulate = Color("#9fece7") if active_path.has(index) else Color("#e8dcb9")Updates tile.modulate, which controls the colour and transparency used to tint this node and its children. The expression builds a colour from these values.
  87. if won:Checks won. The indented instructions below run only if this test passes.
  88. status.text = "%s complete!" % str(layout["name"])Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  89. else:Runs the indented fallback instructions if none of the earlier tests passed.
  90. status.text = "%s · turn a mirror to guide the beam." % str(layout["name"])Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  91. func _tile_label(index: int) -> String:Defines tile 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.
  92. if index == int(layout["source"]):Checks index == int(layout["source"]). The indented instructions below run only if this test passes.
  93. return "Lamp"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  94. if layout["targets"].has(index):Checks layout["targets"].has(index). The indented instructions below run only if this test passes.
  95. return "Awake" if lit_targets.has(index) else "Goal"Finishes the function and hands its result back to the caller. The expression chooses one of two values by checking the condition in the middle.
  96. if _can_turn(index):Checks _can_turn(index). The indented instructions below run only if this test passes.
  97. var slash := "/" if _orientation_at(index) == 0 else "\\"Creates a variable named slash. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  98. if layout.get("splitters", {}).has(index):Checks layout.get("splitters", {}).has(index). The indented instructions below run only if this test passes.
  99. return "Split " + slashFinishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  100. return slashFinishes the function and hands its result back to the caller. The expression reads slash.
  101. if active_path.has(index):Checks active_path.has(index). The indented instructions below run only if this test passes.
  102. return "Beam"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  103. return str(index)Finishes the function and hands its result back to the caller. The expression turns a value into text for a player message.
  104. func _add_action(row: HBoxContainer, caption: String, action: Callable) -> Button:Defines add 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.
  105. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  106. button.text = captionUpdates button.text, which controls the words a player sees. The expression reads caption.
  107. button.custom_minimum_size = Vector2(72, 36)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.
  108. button.pressed.connect(action)Links a signal to the function that should run when the event happens.
  109. row.add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  110. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  111. func _show_hint() -> void:Defines show 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.
  112. var turnables: Dictionary = layout["mirrors"]Creates a variable named turnables. 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.
  113. var choices: Array = turnables.keys() + layout.get("splitters", {}).keys()Creates a variable named choices. The expression calls turnables.keys with the values in its parentheses. The type after the colon says what kind of value it can hold.
  114. if choices.is_empty():Checks choices.is_empty(). The indented instructions below run only if this test passes.
  115. status.text = "Follow the lamp beam in this room."Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  116. returnFinishes the function right here. Any later instructions in this function are skipped.
  117. status.text = "Try one tile at a time. Mirror tile: %s." % str(choices[0])Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  118. 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.
  119. rotations.clear()Empties this collection.
  120. _render()Calls _render with the values in its parentheses.
  121. func _show_help() -> void:Defines show help, 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. status.text = "Tap the mirror. A keyboard player can use Tab, then Enter."Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  123. func _next_room() -> void:Defines next room, 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.
  124. if not won:Checks not won. The indented instructions below run only if this test passes.
  125. status.text = "Wake the exhibits before visiting the next room."Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  126. returnFinishes the function right here. Any later instructions in this function are skipped.
  127. _load_room((room_index + 1) % ROOMS.size())Calls _load_room with the values in its parentheses.
  128. func _load_room(index: int) -> void:Defines load room, 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.
  129. room_index = indexStores the new value in room_index. The expression reads index.
  130. layout = ROOMS[index]Stores the new value in layout. The expression looks up the item or key written between the square brackets.
  131. rotations.clear()Empties this collection.
  132. for old_tile in tiles:Repeats the indented instructions for each value in tiles.
  133. grid.remove_child(old_tile)Calls grid.remove_child with the values in its parentheses.
  134. old_tile.queue_free()Asks Godot to remove this node safely at the end of the frame.
  135. tiles.clear()Empties this collection.
  136. grid.columns = int(layout["width"])Stores the new value in grid.columns. The expression converts a suitable value to a whole number.
  137. _make_tiles()Calls _make_tiles with the values in its parentheses.
  138. _render()Calls _render with the values in its parentheses.
  139. func _can_turn(index: int) -> bool:Defines can turn, 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.
  140. return layout["mirrors"].has(index) or layout.get("splitters", {}).has(index)Finishes the function and hands its result back to the caller. The expression evaluates the test to see whether it is true or false.
  141. func _orientation_at(index: int) -> int:Defines orientation at, 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.
  142. var starter := int(layout["mirrors"].get(index, layout.get("splitters", {}).get(index, 0)))Creates a variable named starter. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  143. return int(rotations.get(index, starter))Finishes the function and hands its result back to the caller. The expression converts a suitable value to a whole number.
Read beam_solver.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 HEADINGS := [Vector2i(0, -1), Vector2i(1, 0), Vector2i(0, 1), Vector2i(-1, 0)]Creates a constant named HEADINGS. The expression makes a list whose items keep their order. Godot infers the type from the first value.
  3. const SLASH := [1, 0, 3, 2]Creates a constant named SLASH. The expression makes a list whose items keep their order. Godot infers the type from the first value.
  4. const BACKSLASH := [3, 2, 1, 0]Creates a constant named BACKSLASH. The expression makes a list whose items keep their order. Godot infers the type from the first value.
  5. static func trace(layout: Dictionary, rotations: Dictionary) -> Dictionary:Defines trace, 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.
  6. var width := int(layout["width"])Creates a variable named width. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  7. var height := int(layout["height"])Creates a variable named height. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  8. var mirrors: Dictionary = layout["mirrors"]Creates a variable named mirrors. 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.
  9. var splitters: Dictionary = layout.get("splitters", {})Creates a variable named splitters. 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.
  10. var targets: Array = layout["targets"]Creates a variable named targets. 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.
  11. var walls: Array = layout.get("walls", [])Creates a variable named walls. 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.
  12. var pending: Array[Vector2i] = [Vector2i(int(layout["source"]), int(layout["direction"]))]Creates a variable named pending. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  13. var segments: Array[Dictionary] = []Creates a variable named segments. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  14. var lit: Array[int] = []Creates a variable named lit. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  15. var visited: Dictionary = {}Creates a variable named visited. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold.
  16. var loop_found := falseCreates a variable named loop_found. The expression uses the yes-or-no value false. Godot infers the type from the first value.
  17. while not pending.is_empty():Keeps repeating while not pending.is_empty() stays true. The loop body should eventually change the result or leave with break.
  18. var ray: Vector2i = pending.pop_back()Creates a variable named ray. The expression takes the final item out of the list and returns it. The type after the colon says what kind of value it can hold.
  19. if visited.has(ray):Checks visited.has(ray). The indented instructions below run only if this test passes.
  20. loop_found = trueStores the new value in loop_found. The expression uses the yes-or-no value true.
  21. continueSkips the rest of this turn through the loop and moves on to the next item.
  22. visited[ray] = trueStores the new value in visited[ray]. The expression uses the yes-or-no value true.
  23. @warning_ignore("integer_division")This annotation gives Godot extra information about the declaration that follows.
  24. var row := ray.x / widthCreates a variable named row. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  25. var cell := Vector2i(ray.x % width, 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.
  26. var next: Vector2i = cell + HEADINGS[ray.y]Creates a variable named next. 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.
  27. if not Rect2i(0, 0, width, height).has_point(next):Checks not Rect2i(0, 0, width, height).has_point(next). The indented instructions below run only if this test passes.
  28. continueSkips the rest of this turn through the loop and moves on to the next item.
  29. var tile := next.y * width + next.xCreates a variable named tile. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  30. segments.append({"from": ray.x, "to": tile})Adds an item to the end of a list.
  31. if walls.has(tile):Checks walls.has(tile). The indented instructions below run only if this test passes.
  32. continueSkips the rest of this turn through the loop and moves on to the next item.
  33. if targets.has(tile):Checks targets.has(tile). The indented instructions below run only if this test passes.
  34. if not lit.has(tile):Checks not lit.has(tile). The indented instructions below run only if this test passes.
  35. lit.append(tile)Adds an item to the end of a list.
  36. continueSkips the rest of this turn through the loop and moves on to the next item.
  37. var direction := ray.yCreates a variable named direction. The expression reads ray.y. Godot infers the type from the first value.
  38. if mirrors.has(tile):Checks mirrors.has(tile). The indented instructions below run only if this test passes.
  39. var slant := int(rotations.get(tile, mirrors[tile]))Creates a variable named slant. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  40. direction = _reflected(direction, slant)Stores the new value in direction. The expression calls _reflected with the values in its parentheses.
  41. if splitters.has(tile):Checks splitters.has(tile). The indented instructions below run only if this test passes.
  42. var splitter_slant := int(rotations.get(tile, splitters[tile]))Creates a variable named splitter_slant. The expression converts a suitable value to a whole number. Godot infers the type from the first value.
  43. var bounced := _reflected(direction, splitter_slant)Creates a variable named bounced. The expression calls _reflected with the values in its parentheses. Godot infers the type from the first value.
  44. pending.append(Vector2i(tile, bounced))Adds an item to the end of a list.
  45. pending.append(Vector2i(tile, direction))Adds an item to the end of a list.
  46. return {"segments": segments, "lit": lit, "loop": loop_found}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  47. static func _reflected(heading: int, slant: int) -> int:Defines reflected, 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. if slant == 0:Checks slant == 0. The indented instructions below run only if this test passes.
  49. return SLASH[heading]Finishes the function and hands its result back to the caller. The expression looks up the item or key written between the square brackets.
  50. return BACKSLASH[heading]Finishes the function and hands its result back to the caller. The expression looks up the item or key written between the square brackets.

Find and fix a bug

If only the reflected ray appears, check that the straight pending.append is outside the splitter if body and uses direction. If one target lights twice, check that trace tests lit.has before appending.

Try a change

Sketch a room in which the splitter solves two paths of different lengths. Stretch: test an added wall that blocks only one branch and predict which exhibit still wakes.