Museum of Lost Lights · Lesson 40 of 50 · Advanced · About 36 min
A polished game needs predictable mirrors. An automated test can check all eight straight-in turns in seconds.

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/39 when the lesson builds on prior work, or copy the checkpoints/40 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 enum, Array, for, size, ==, and, assert.
-
Run the whole table
Import lesson 40 in Godot and press F5. Choose Run all mirror checks. Look for the complete pass count.
Why it works A set of known examples lets you spot when any mirror rule changes unexpectedly.
-
Compare a case with the drawing
Open main.gd and find CASES. For the first line, draw a slash mirror on a grid. Move north, up from the bottom, and trace the movement as it leaves east.
[Direction.NORTH, true, Direction.EAST]Why it works The test row is an independent claim. It holds an incoming direction, the kind of diagonal and an expected result.
-
Test actual against expected
Find the loop in run_checks. Read case[0] as incoming, case[1] as slash and case[2] as expected. Identify the line that calculates actual.
var actual := reflect(case[0], case[1])Why it works Array indexes count from zero. Comparing the result with the expected answer turns a visual guess into a test you can run repeatedly.
-
Switch on and observe the mistake
Press Toggle the practice bug and run checks again. Read the first mismatch. On paper, draw its expected direction before looking at reflect.
if introduce_bug and not slash and incoming == Direction.EAST:Why it works The built-in practice bug changes only one direction. The first mismatch prints enough information to locate the bad branch without searching the whole project.
-
Switch it off and rerun
Turn the practice bug off and run the checks. Find the assert near the bottom and open Godot's Debugger panel in the editor.
assert(passed == CASES.size(), first_failure)Why it works An assert is a statement that checks a condition during a debug run. The status still reports success or failure in a release build, where that assertion is not used.
-
Use the same idea on a level
Choose a puzzle from earlier lessons. Write the orientations you start with, the taps you want to make and the exhibits that must finish lit.
Why it works The same input and expected-output pattern also helps with save reloads, undo steps and complete level solutions.
Watch the values change
-
Run with bug off Each actual direction equals the expected direction.
What you see. 8 of 8 checks pass. -
Toggle and run East into a backslash returns north instead of south.
What you see. 7 of 8 pass and the first mismatch is printed. -
Toggle off and rerun The deliberate error branch no longer applies.
What you see. 8 of 8 pass again.
Predict before you run If you only test the four slash directions, will the practice bug be reported?
Reveal the answer
No. The added mistake only affects a backslash mirror. You need a test for east into a backslash to spot it.
Complete checkpoint
Initial run reports 8 of 8. The added mistake reports 7 of 8 and the mismatch. The fixed run returns to 8 of 8.
main.gd
extends Control
enum Direction { NORTH, EAST, SOUTH, WEST }
const SLASH_TURNS := [Direction.EAST, Direction.NORTH, Direction.WEST, Direction.SOUTH]
const BACKSLASH_TURNS := [Direction.WEST, Direction.SOUTH, Direction.EAST, Direction.NORTH]
const NAMES := ["north", "east", "south", "west"]
const CASES := [
[Direction.NORTH, true, Direction.EAST],
[Direction.EAST, true, Direction.NORTH],
[Direction.SOUTH, true, Direction.WEST],
[Direction.WEST, true, Direction.SOUTH],
[Direction.NORTH, false, Direction.WEST],
[Direction.EAST, false, Direction.SOUTH],
[Direction.SOUTH, false, Direction.EAST],
[Direction.WEST, false, Direction.NORTH]
]
var introduce_bug := false
var readout: Label
func _ready() -> void:
var panel := make_panel("40 · Run repeatable mirror checks")
make_label(panel, "Run the test bench, toggle the practice bug and run again.")
readout = make_label(panel, "Ready for eight checks.")
make_button(panel, "Run all mirror checks", run_checks)
make_button(panel, "Toggle the practice bug", toggle_practice_bug)
func reflect(incoming: int, slash: bool) -> int:
if introduce_bug and not slash and incoming == Direction.EAST:
return Direction.NORTH
return SLASH_TURNS[incoming] if slash else BACKSLASH_TURNS[incoming]
func run_checks() -> void:
var passed := 0
var first_failure := ""
for case in CASES:
var actual := reflect(case[0], case[1])
if actual == case[2]:
passed += 1
elif first_failure.is_empty():
first_failure = "First mismatch: %s enters, expected %s, got %s." % [
NAMES[case[0]], NAMES[case[2]], NAMES[actual]
]
readout.text = "%d of %d checks passed. %s" % [passed, CASES.size(), first_failure]
if not introduce_bug:
assert(passed == CASES.size(), first_failure)
func toggle_practice_bug() -> void:
introduce_bug = not introduce_bug
readout.text = "Practice bug on." if introduce_bug else "Practice bug off."
func make_panel(heading: String, width: float = 580.0) -> VBoxContainer:
var margin := MarginContainer.new()
margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 24)
add_child(margin)
var centring := CenterContainer.new()
margin.add_child(centring)
var panel := VBoxContainer.new()
panel.custom_minimum_size.x = width
panel.add_theme_constant_override("separation", 12)
centring.add_child(panel)
make_label(panel, heading, 28)
return panel
func make_label(parent: Control, message: String, size: int = 18) -> Label:
var label := Label.new()
label.text = message
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
label.add_theme_font_size_override("font_size", size)
parent.add_child(label)
return label
func make_button(parent: Control, caption: String, handle_press: Callable) -> Button:
var button := Button.new()
button.text = caption
button.custom_minimum_size.y = 52
button.pressed.connect(handle_press)
parent.add_child(button)
return button
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 ControlGive this script the layout and input abilities of Godot's Control node. The code below turns the root Control into a particular museum practice scene. -
enum Direction { NORTH, EAST, SOUTH, WEST }Create named choices in clockwise order, numbered from zero. These numbers are also positions in the lookup arrays below. -
const SLASH_TURNS := [Direction.EAST, Direction.NORTH, Direction.WEST, Direction.SOUTH]Write the outgoing directions for a slash mirror in incoming north, east, south and west order. -
const BACKSLASH_TURNS := [Direction.WEST, Direction.SOUTH, Direction.EAST, Direction.NORTH]Write the four outputs for a backslash mirror in the same incoming order. -
const NAMES := ["north", "east", "south", "west"]Creates a constant named NAMES. The expression makes a list whose items keep their order. Godot infers the type from the first value. -
const CASES := [Start the array of checks. Each inner list holds an incoming direction, a mirror shape and the expected result. -
[Direction.NORTH, true, Direction.EAST],Test a beam travelling north into a slash mirror. Store east as the separately expected outgoing direction. -
[Direction.EAST, true, Direction.NORTH],Test a beam travelling east into a slash mirror. Store north as the separately expected outgoing direction. -
[Direction.SOUTH, true, Direction.WEST],Test a beam travelling south into a slash mirror. Store west as the separately expected outgoing direction. -
[Direction.WEST, true, Direction.SOUTH],Test a beam travelling west into a slash mirror. Store south as the separately expected outgoing direction. -
[Direction.NORTH, false, Direction.WEST],Test a beam travelling north into a backslash mirror. Store west as the separately expected outgoing direction. -
[Direction.EAST, false, Direction.SOUTH],Test a beam travelling east into a backslash mirror. Store south as the separately expected outgoing direction. -
[Direction.SOUTH, false, Direction.EAST],Test a beam travelling south into a backslash mirror. Store east as the separately expected outgoing direction. -
[Direction.WEST, false, Direction.NORTH]Test a beam travelling west into a backslash mirror. Store north as the separately expected outgoing direction. -
]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
var introduce_bug := falseCreates a variable named introduce_bug. The expression uses the yes-or-no value false. Godot infers the type from the first value. -
var readout: LabelDeclares readout for later use. A colon followed by a type says which kind of value belongs here. -
func _ready() -> void:Godot calls this function once when the node is ready. The indented setup creates the interface and gives its controls their starting values. -
var panel := make_panel("40 · Run repeatable mirror checks")Creates a variable named panel. The expression calls make_panel with the values in its parentheses. Godot infers the type from the first value. -
make_label(panel, "Run the test bench, toggle the practice bug and run again.")Calls make_label with the values in its parentheses. -
readout = make_label(panel, "Ready for eight checks.")Stores the new value in readout. The expression calls make_label with the values in its parentheses. -
make_button(panel, "Run all mirror checks", run_checks)Calls make_button with the values in its parentheses. -
make_button(panel, "Toggle the practice bug", toggle_practice_bug)Calls make_button with the values in its parentheses. -
func reflect(incoming: int, slash: bool) -> int:Defines reflect, 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 introduce_bug and not slash and incoming == Direction.EAST:Take the deliberate error branch only when the practice bug is on and an eastbound beam hits a backslash mirror. -
return Direction.NORTHIntentionally return the wrong new direction for this one demonstration. The test row still expects south. -
return SLASH_TURNS[incoming] if slash else BACKSLASH_TURNS[incoming]Pick the lookup list for the requested mirror shape and read the output at the incoming direction's position. -
func run_checks() -> void:Defines run checks, 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 passed := 0Creates a variable named passed. The expression uses the whole number 0. Godot infers the type from the first value. -
var first_failure := ""Creates a variable named first_failure. The expression uses the text inside the quotes. Godot infers the type from the first value. -
for case in CASES:Run one complete test for each independently stated expected answer. -
var actual := reflect(case[0], case[1])Pass the row's first item as incoming and the second as the mirror shape. Keep the actual answer returned by the rule. -
if actual == case[2]:Compare the function result to the independent expected direction in the third slot of the test row. -
passed += 1Add this success to the whole-number count of passing test rows. -
elif first_failure.is_empty():When the result is wrong, record it only if this is the first mismatch. Keep later failures from overwriting the earliest clue. -
first_failure = "First mismatch: %s enters, expected %s, got %s." % [Stores the new value in first_failure. The expression uses the text inside the quotes. -
NAMES[case[0]], NAMES[case[2]], NAMES[actual]Convert the incoming, expected and received direction indexes into readable names for the first-mismatch message. -
]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
readout.text = "%d of %d checks passed. %s" % [passed, CASES.size(), first_failure]Display how many tests passed, how many went through the loop and the mismatch message if there was one. -
if not introduce_bug:Checks not introduce_bug. The indented instructions below run only if this test passes. -
assert(passed == CASES.size(), first_failure)During a debug run, flag an unexpected failure by requiring the pass total to match the number of cases and reporting the stored mismatch. -
func toggle_practice_bug() -> void:Defines toggle practice bug, 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. -
introduce_bug = not introduce_bugStores the new value in introduce_bug. The expression reads not introduce_bug. -
readout.text = "Practice bug on." if introduce_bug else "Practice bug off."Updates readout.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle. -
func make_panel(heading: String, width: float = 580.0) -> VBoxContainer:Make a helper that takes the heading text and the panel's minimum width. If the caller omits the width, use 580 game pixels. Return the laid-out panel so the caller can add more controls. -
var margin := MarginContainer.new()Create a container that can reserve clear space between the game controls and the window edges. -
margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Choose the preset that aligns the margin's edges with all four edges of the parent Control. -
for side in ["left", "right", "top", "bottom"]:Visit the four names in order so the following indented line can set one margin on each trip through the loop. -
margin.add_theme_constant_override("margin_" + side, 24)Join margin_ to the current side's name. Set that edge to 24 game pixels, and repeat for the other sides. -
add_child(margin)Connect the completed margin container to the lesson's scene root so it can lay out its children. -
var centring := CenterContainer.new()Make a container that will centre the controls within the available space. -
margin.add_child(centring)Give the centring container the space inside the extra border, then let it place the panel within that space. -
var panel := VBoxContainer.new()Create a container that arranges its child controls in one vertical column. -
panel.custom_minimum_size.x = widthAsk the layout for at least the selected width, where x is the horizontal part of the size. -
panel.add_theme_constant_override("separation", 12)Leave 12 game pixels of space between each pair of controls in the vertical panel. -
centring.add_child(panel)Attach the vertical column to the centring container. Godot can now place the whole column together. -
make_label(panel, heading, 28)Put the supplied heading at the top of the column and ask for a larger 28-pixel font. -
return panelHand the panel reference back to the caller so it can add labels or buttons under the heading. -
func make_label(parent: Control, message: String, size: int = 18) -> Label:Accept the parent control, text to show and optional font size. Return the new Label so the caller can update it later. -
var label := Label.new()Make a new empty Label, which is Godot's text display node. -
label.text = messageCopy the incoming message into the label's visible words. -
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTLet the label wrap lines at sensible places so a long message can fit when the layout is narrow. -
label.add_theme_font_size_override("font_size", size)Set the chosen size on this one label so other text can keep different sizes. -
parent.add_child(label)Add the label to the supplied parent. It becomes part of that panel's layout and can appear on screen. -
return labelReturn the exact label you created so the caller can change its text without building a second label. -
func make_button(parent: Control, caption: String, handle_press: Callable) -> Button:Build and return one Button. The arguments identify its parent, the words on it and the action to run after pressing it. -
var button := Button.new()Create a Godot Button that supports pointer, touch and keyboard activation. -
button.text = captionPut the supplied caption on the visible control. -
button.custom_minimum_size.y = 52Reserve at least 52 game pixels vertically so the control remains a comfortable target. -
button.pressed.connect(handle_press)Connect the pressed signal to the supplied callable. Godot waits for activation before running the action. -
parent.add_child(button)Attach the Button to its parent and let that container position it. -
return buttonGive the finished Button to the caller, which can keep a reference to set focus or change the caption later.
Find and fix a bug
If the same wrong direction appears to pass, check that CASES holds a separately considered answer. Using reflect to generate your expected answers would let the same error appear twice.
Try a change
Ages 10–12 can draw and explain the one failed case. Ages 13–16 can add a table of full board positions, including a mirror loop that must end without freezing.