Museum of Lost Lights · Lesson 18 of 50 · Intermediate · About 45 min
Let the museum’s floor plans and the lantern’s light rules be different jobs. The screen can ask for a result from a solver without teaching it how to draw buttons.

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

Build it step by step
Language and tools in this lesson preload, RefCounted, static func, Dictionary result, while, pop_back, continue, visited ray state.
-
Find the two scripts in Godot
In the FileSystem dock open main.gd and beam_solver.gd. In a manual build, use the FileSystem dock’s New Script command or create the file in the project directory, then add the preload near the top of main.gd. Compare the two scripts’ first lines.
const BeamSolver = preload("res://beam_solver.gd")Why it works Control can arrange and display UI. RefCounted holds rules without taking a place in the scene tree. preload loads the known local script as the game loads, so the main script can call it directly.
-
Describe a ray as an address and direction
Read trace’s first lines. Match width and height to the current room. Look at pending and use ray.x for the starting tile address and ray.y for the heading number.
static func trace(layout: Dictionary, rotations: Dictionary) -> Dictionary:Why it works This Vector2i is a pair of ray values. It carries an address and heading together, distinct from a floor coordinate. trace is static so it needs neither a solver instance nor screen nodes.
-
Follow a pending ray
Read the while loop until the section that checks the gallery boundary. Take the last item off the pending array. Find how the address becomes a cell again, then add the heading’s Vector2i.
var ray: Vector2i = pending.pop_back()Why it works while repeats while its condition is true. pop_back returns and removes the last ray. If a ray reaches the same tile with the same heading again, visited records that repetition and continue skips processing it again.
-
Record purposeful outcomes
Find segments.append, the wall check and the target check in order. Watch the trace on paper from 12 to 7 to 2 in Ocean. Say which segment arrives at a target.
return {"segments": segments, "lit": lit, "loop": loop_found}Why it works A segment dictionary records the two ends of one move. A wall ends that path. A target is added to lit only once, then absorbs the ray. The result includes both the route and which targets woke.
-
Draw what the solver returned
In main.gd open _trace_beam. Find the solver call, reading of outcome and loop that collects segment destinations. Run both museum rooms and replay the winning turns from lesson 17.
var outcome := BeamSolver.trace(layout, rotations)Why it works The game receives a Dictionary and reads two keys. It turns those facts into highlighted squares and win text. The solver and the screen now share a result without sharing UI work.
-
Treat the direction table like a map
At the top of beam_solver.gd inspect HEADINGS, SLASH and BACKSLASH. Point to east as index 1. Read SLASH[1], then use the first number to choose the new direction.
return SLASH[heading]Why it works The order is north, east, south, west. Table lookup uses a heading number as an array position and returns the reflected heading’s number.
Watch the values change
-
Start Ocean pending starts with address 10 and heading 1
What you see. The first segment joins 10 to 11. -
Turn mirror 12 to slash Reflected heading number is 0 (north)
What you see. Segments go from 12 to 7, then 7 to 2. -
Pass the result to the screen lit contains [2]
What you see. The matching target count gives a win.
Predict before you run Why might a ray be allowed to reach the same tile twice when its heading differs?
Reveal the answer
A ray heading east will visit a different next square from one heading north. visited tracks the pair of address and heading, so it catches exact repeated states.
Complete checkpoint
Both museum rooms work as before. The game calls BeamSolver.trace for beam segments and target hits, while the main script displays results.
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]},
]
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 "\\"
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 := turnables.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)
func _orientation_at(index: int) -> int:
return int(rotations.get(index, layout["mirrors"].get(index, 0)))
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 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)
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
-
extends ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules. -
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. -
{"name": "Ocean Gallery", "width": 5, "height": 5, "source": 10,Starts a list or dictionary used as part of the instruction above. -
"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. -
{"name": "Fossil Passage", "width": 5, "height": 5, "source": 10,Starts a list or dictionary used as part of the instruction above. -
"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. -
]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
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. -
var grid: GridContainerDeclares grid for later use. A colon followed by a type says which kind of value belongs here. -
var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here. -
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. -
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. -
var won := falseCreates a variable named won. The expression uses the yes-or-no value false. Godot infers the type from the first value. -
var room_index := 0Creates a variable named room_index. The expression uses the whole number 0. Godot infers the type from the first value. -
var layout: DictionaryDeclares layout for later use. A colon followed by a type says which kind of value belongs here. -
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. -
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. -
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. -
var background := ColorRect.new()Creates a variable named background. The expression creates a new ColorRect object. Godot infers the type from the first value. -
background.color = Color("#102a3b")Stores the new value in background.color. The expression builds a colour from these values. -
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. -
add_child(background)Adds the new node to the scene tree so that Godot can run and draw it. -
background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent. -
var centre := CenterContainer.new()Creates a variable named centre. The expression creates a new CenterContainer object. Godot infers the type from the first value. -
add_child(centre)Adds the new node to the scene tree so that Godot can run and draw it. -
centre.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent. -
var page := VBoxContainer.new()Creates a variable named page. The expression creates a new VBoxContainer object. Godot infers the type from the first value. -
page.add_theme_constant_override("separation", 8)Calls page.add_theme_constant_override with the values in its parentheses. -
centre.add_child(page)Adds the new node to the scene tree so that Godot can run and draw it. -
var heading := Label.new()Creates a variable named heading. The expression creates a new Label object. Godot infers the type from the first value. -
heading.text = "Museum of Lost Lights"Updates heading.text, which controls the words a player sees. The expression uses the text inside the quotes. -
heading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in heading.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER. -
heading.add_theme_font_size_override("font_size", 26)Calls heading.add_theme_font_size_override with the values in its parentheses. -
page.add_child(heading)Adds the new node to the scene tree so that Godot can run and draw it. -
var subheading := Label.new()Creates a variable named subheading. The expression creates a new Label object. Godot infers the type from the first value. -
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. -
subheading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in subheading.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER. -
page.add_child(subheading)Adds the new node to the scene tree so that Godot can run and draw it. -
grid = GridContainer.new()Stores the new value in grid. The expression creates a new GridContainer object. -
grid.columns = int(ROOMS[0]["width"])Stores the new value in grid.columns. The expression converts a suitable value to a whole number. -
grid.size_flags_horizontal = Control.SIZE_SHRINK_CENTERStores the new value in grid.size_flags_horizontal. The expression reads Control.SIZE_SHRINK_CENTER. -
page.add_child(grid)Adds the new node to the scene tree so that Godot can run and draw it. -
status = Label.new()Stores the new value in status. The expression creates a new Label object. -
status.custom_minimum_size.x = 460Stores the new value in status.custom_minimum_size.x. The expression uses the whole number 460. -
status.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in status.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER. -
page.add_child(status)Adds the new node to the scene tree so that Godot can run and draw it. -
var actions := HBoxContainer.new()Creates a variable named actions. The expression creates a new HBoxContainer object. Godot infers the type from the first value. -
actions.alignment = BoxContainer.ALIGNMENT_CENTERUpdates actions.alignment, which controls how the control aligns its contents. The expression reads BoxContainer.ALIGNMENT_CENTER. -
page.add_child(actions)Adds the new node to the scene tree so that Godot can run and draw it. -
_add_action(actions, "Hint", _show_hint)Calls _add_action with the values in its parentheses. -
_add_action(actions, "Reset", _reset)Calls _add_action with the values in its parentheses. -
_add_action(actions, "Help", _show_help)Calls _add_action with the values in its parentheses. -
_add_action(actions, "Next room", _next_room)Calls _add_action with the values in its parentheses. -
_load_room(0)Calls _load_room with the values in its parentheses. -
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. -
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"])). -
var tile := Button.new()Creates a variable named tile. The expression creates a new Button object. Godot infers the type from the first value. -
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. -
tile.focus_mode = Control.FOCUS_ALLStores the new value in tile.focus_mode. The expression reads Control.FOCUS_ALL. -
tile.pressed.connect(_tap_tile.bind(index))Links a signal to the function that should run when the event happens. -
tiles.append(tile)Adds an item to the end of a list. -
grid.add_child(tile)Adds the new node to the scene tree so that Godot can run and draw it. -
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. -
if won or not _can_turn(index):Checks won or not _can_turn(index). The indented instructions below run only if this test passes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
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. -
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. -
_render()Calls _render with the values in its parentheses. -
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. -
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. -
lit_targets = outcome["lit"]Stores the new value in lit_targets. The expression looks up the item or key written between the square brackets. -
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. -
for segment: Dictionary in outcome["segments"]:Repeats the indented instructions for each value in outcome["segments"]. -
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. -
if not travelled.has(tile):Checks not travelled.has(tile). The indented instructions below run only if this test passes. -
travelled.append(tile)Adds an item to the end of a list. -
return travelledFinishes the function and hands its result back to the caller. The expression reads travelled. -
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. -
active_path = _trace_beam()Stores the new value in active_path. The expression calls _trace_beam with the values in its parentheses. -
won = lit_targets.size() == layout["targets"].size()Stores the new value in won. The expression counts the items in this collection. -
for index in range(tiles.size()):Repeats the indented instructions for each value in range(tiles.size()). -
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. -
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. -
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. -
if won:Checks won. The indented instructions below run only if this test passes. -
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. -
else:Runs the indented fallback instructions if none of the earlier tests passed. -
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. -
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. -
if index == int(layout["source"]):Checks index == int(layout["source"]). The indented instructions below run only if this test passes. -
return "Lamp"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes. -
if layout["targets"].has(index):Checks layout["targets"].has(index). The indented instructions below run only if this test passes. -
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. -
if _can_turn(index):Checks _can_turn(index). The indented instructions below run only if this test passes. -
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. -
return slashFinishes the function and hands its result back to the caller. The expression reads slash. -
if active_path.has(index):Checks active_path.has(index). The indented instructions below run only if this test passes. -
return "Beam"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes. -
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. -
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. -
var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value. -
button.text = captionUpdates button.text, which controls the words a player sees. The expression reads caption. -
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. -
button.pressed.connect(action)Links a signal to the function that should run when the event happens. -
row.add_child(button)Adds the new node to the scene tree so that Godot can run and draw it. -
return buttonFinishes the function and hands its result back to the caller. The expression reads button. -
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. -
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. -
var choices := turnables.keys()Creates a variable named choices. The expression calls turnables.keys with the values in its parentheses. Godot infers the type from the first value. -
if choices.is_empty():Checks choices.is_empty(). The indented instructions below run only if this test passes. -
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. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
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. -
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. -
rotations.clear()Empties this collection. -
_render()Calls _render with the values in its parentheses. -
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. -
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. -
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. -
if not won:Checks not won. The indented instructions below run only if this test passes. -
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. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
_load_room((room_index + 1) % ROOMS.size())Calls _load_room with the values in its parentheses. -
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. -
room_index = indexStores the new value in room_index. The expression reads index. -
layout = ROOMS[index]Stores the new value in layout. The expression looks up the item or key written between the square brackets. -
rotations.clear()Empties this collection. -
for old_tile in tiles:Repeats the indented instructions for each value in tiles. -
grid.remove_child(old_tile)Calls grid.remove_child with the values in its parentheses. -
old_tile.queue_free()Asks Godot to remove this node safely at the end of the frame. -
tiles.clear()Empties this collection. -
grid.columns = int(layout["width"])Stores the new value in grid.columns. The expression converts a suitable value to a whole number. -
_make_tiles()Calls _make_tiles with the values in its parentheses. -
_render()Calls _render with the values in its parentheses. -
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. -
return layout["mirrors"].has(index)Finishes the function and hands its result back to the caller. The expression looks up the item or key written between the square brackets. -
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. -
return int(rotations.get(index, layout["mirrors"].get(index, 0)))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
-
extends RefCountedStarts with Godot's RefCounted type. This script gets the abilities of that type and adds the game's own rules. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
if visited.has(ray):Checks visited.has(ray). The indented instructions below run only if this test passes. -
loop_found = trueStores the new value in loop_found. The expression uses the yes-or-no value true. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
visited[ray] = trueStores the new value in visited[ray]. The expression uses the yes-or-no value true. -
@warning_ignore("integer_division")This annotation gives Godot extra information about the declaration that follows. -
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. -
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. -
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. -
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. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
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. -
segments.append({"from": ray.x, "to": tile})Adds an item to the end of a list. -
if walls.has(tile):Checks walls.has(tile). The indented instructions below run only if this test passes. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
if targets.has(tile):Checks targets.has(tile). The indented instructions below run only if this test passes. -
if not lit.has(tile):Checks not lit.has(tile). The indented instructions below run only if this test passes. -
lit.append(tile)Adds an item to the end of a list. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
var direction := ray.yCreates a variable named direction. The expression reads ray.y. Godot infers the type from the first value. -
if mirrors.has(tile):Checks mirrors.has(tile). The indented instructions below run only if this test passes. -
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. -
direction = _reflected(direction, slant)Stores the new value in direction. The expression calls _reflected with the values in its parentheses. -
pending.append(Vector2i(tile, direction))Adds an item to the end of a list. -
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. -
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. -
if slant == 0:Checks slant == 0. The indented instructions below run only if this test passes. -
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. -
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 Godot reports that it cannot load the resource, check beam_solver.gd is in the same project folder as main.gd and the preload uses res://beam_solver.gd. For a dark beam with a valid result, check that _trace_beam adds each segment’s to address.
Try a change
Pretend a new room has a wall at tile 11. Draw which segments appear before it stops. Stretch: add the walls key with [11] to a practice room and compare the result.