Mobile Game 22 · Catch a ray that goes in circles

Museum of Lost Lights · Lesson 22 of 50 · Intermediate · About 35 min

The next room has a path that can return to the splitter. A ray could keep circling while the player waits. You will give each branch its own trail, stop that branch at the first repeat and show the player how to fix the puzzle.

A gouache painting of a Fossil Gallery with amber lights, tall prehistoric skeleton displays and a dark stone floor.
What you’ll make Detect a looping beam by checking whether the same ray revisits a tile facing the same direction.

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

Read ray and trail. A queued ray carries the states from its current path. → Ask seen.has(ray). Identical tile and direction mean the route would repeat. → Copy and mark. A fresh dictionary records the next step without editing another branch. → Tell the player. Return the loop flag and show a clear hint.
Read ray and trail → Ask seen.has(ray) → Copy and mark → Tell the player

Build it step by step

Language and tools in this lesson Dictionary.has, duplicate, Vector2i keys, continue, while, boolean flags, per-branch state, if.

  1. Open the returning-ray layout

    Import this lesson’s project, open main.gd and find DEMO. Put a finger on tile 8 in a four-by-six grid. Draw its first move east into splitter 9. Keep your sketch near the screen.

    Why it works The starting orientation deliberately makes part of the light repeat. A small example with a known bug makes the new rule testable.

  2. Carry a trail with the ray

    In _trace, compare the prior Vector2i queue to the new queue of dictionaries. In the first item, add a ray and a blank seen dictionary. Find the two matching keys again after pop_front.

    var pending: Array[Dictionary] = [{"ray": Vector2i(int(level.source), int(level.direction)), "seen": {}}]

    Why it works A dictionary keeps these named pieces together. Each pending ray arrives with the path history needed to detect its own loop.

  3. Test both position and direction

    Read the popped dictionary’s ray and seen values. Use seen.has(ray) to check whether this pair appeared before. Set loop_found and continue when it did.

    if seen.has(ray):

    Why it works The light can safely cross a tile a second time from a different direction. A tile and direction together identify an exact repeated situation.

  4. Pass on a fresh trail

    Add trail below the check, duplicate the incoming dictionary and write the current ray into the new one. When the splitter queues both branches, give both this trail. Each branch will make its next copy before adding a mark.

    var trail := seen.duplicate()

    Why it works A copy avoids changing the trail shared by other branches. Two beams that meet after taking different routes do not automatically count as a loop.

  5. Connect the flag to the window

    Keep loop_found in the dictionary returned by _trace. Find _refresh below it. Put the loop warning after the usual status message is set. Press F6 and read the warning before tapping.

    if beam.loop:

    Why it works The solver reports a fact. The screen translates the fact into a message the player can understand.

  6. Break the cycle and recheck

    Tap the splitter at row 2, column 4. Compare your sketch with the screen. Tap it again to reproduce the loop and make sure the game still accepts input.

    Why it works Reproducing and clearing the same problem twice is a better test than checking only the solved direction.

Watch the values change

  1. Launch the starting layout. The returned route reaches the same source-direction pair again.
    What you see. The repeat is detected, and the current branch ends.
  2. Tap the splitter once. Its reflected beam points north, away from the looping mirrors.
    What you see. The second exhibit wakes and the warning disappears.
  3. Tap the splitter again. The branch once more reaches its own earlier ray state.
    What you see. The warning returns without freezing the game.

Predict before you run Two rays both visit tile 9. One heads east and one heads north. Does that pair alone count as a loop?

Reveal the answer

No. Their direction values differ. A loop is detected by revisiting the same tile and direction along the same branch.

Complete checkpoint

The game displays a loop warning on launch. Rotating the splitter wakes both exhibits and removes the warning.

main.gd

extends Control

const STEPS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
const TURNS: Array = [[1, 0, 3, 2], [3, 2, 1, 0]]
const ORIGIN := Vector2(32, 139)
const PITCH := 78
const TILE := 70
const DEMO: Dictionary = {"title": "The returning ray", "width": 6, "height": 4, "source": 8, "direction": 1, "mirrors": {"7": 0, "13": 1, "15": 0}, "splitters": {"9": 1}, "targets": [3, 11], "walls": []}


var level: Dictionary
var turns: Dictionary = {}
var beam: Dictionary
var tile_buttons: Dictionary = {}
var board_layer: Control
var status: Label


func _ready() -> void:
	_add_label(Vector2(31, 21), "MUSEUM OF LOST LIGHTS", 29)
	_add_label(Vector2(32, 64), "Catch a ray that goes in circles", 15)
	status = _add_label(Vector2(576, 174), "", 17)
	status.custom_minimum_size = Vector2(302, 141)
	status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART

	board_layer = Control.new()
	board_layer.mouse_filter = Control.MOUSE_FILTER_IGNORE
	add_child(board_layer)
	_load_level(DEMO)

func _add_label(at: Vector2, text: String, text_size: int) -> Label:
	var label := Label.new()
	label.position = at
	label.text = text
	label.add_theme_font_size_override("font_size", text_size)
	label.add_theme_color_override("font_color", Color("#fff1d4"))
	add_child(label)
	return label

func _load_level(data: Dictionary) -> void:
	level = data
	turns.clear()

	tile_buttons.clear()
	for child in board_layer.get_children():
		child.queue_free()
	for tile in range(int(level.width) * int(level.height)):
		var is_mirror := _turn_at(level.mirrors, tile) >= 0
		var is_splitter := _turn_at(level.splitters, tile) >= 0
		if is_mirror or is_splitter:
			var button := Button.new()
			button.position = _cell(tile)
			button.size = Vector2(TILE, TILE)
			button.tooltip_text = "Rotate " + ("splitter" if is_splitter else "mirror")
			button.pressed.connect(_turn_tile.bind(tile))
			board_layer.add_child(button)
			tile_buttons[tile] = button
	_refresh()

func _turn_at(layout: Dictionary, tile: int) -> int:
	return int(layout.get(str(tile), -1))

func _orientation(tile: int, state: Dictionary) -> int:
	var start := _turn_at(level.mirrors, tile)
	if start < 0:
		start = _turn_at(level.splitters, tile)
	return int(state.get(tile, start))

func _turn_tile(tile: int) -> void:

	turns[tile] = 1 - _orientation(tile, turns)
	_refresh()


func _trace(state: Dictionary) -> Dictionary:
	var segments: Array[Vector2i] = []
	var lit: Array[int] = []
	var loop_found := false
	var pending: Array[Dictionary] = [{"ray": Vector2i(int(level.source), int(level.direction)), "seen": {}}]
	while not pending.is_empty():
		var item: Dictionary = pending.pop_front()
		var ray: Vector2i = item.ray
		var seen: Dictionary = item.seen
		if seen.has(ray):
			loop_found = true
			continue
		var trail := seen.duplicate()
		trail[ray] = true
		var tile := ray.x
		var direction := ray.y
		var coordinates := Vector2i(tile % int(level.width), floori(float(tile) / int(level.width)))
		var next_position := coordinates + STEPS[direction]
		if not Rect2i(0, 0, int(level.width), int(level.height)).has_point(next_position):
			continue
		var next_tile := next_position.y * int(level.width) + next_position.x
		segments.append(Vector2i(tile, next_tile))
		if level.targets.has(next_tile) and not lit.has(next_tile):
			lit.append(next_tile)
		if level.walls.has(next_tile):
			continue
		var splitter := _turn_at(level.splitters, next_tile)
		if splitter >= 0:
			pending.append({"ray": Vector2i(next_tile, direction), "seen": trail})
			var branch: int = TURNS[_orientation(next_tile, state)][direction]
			pending.append({"ray": Vector2i(next_tile, branch), "seen": trail})
		else:
			var mirror := _turn_at(level.mirrors, next_tile)
			var onward: int = TURNS[_orientation(next_tile, state)][direction] if mirror >= 0 else direction
			pending.append({"ray": Vector2i(next_tile, onward), "seen": trail})
	return {"segments": segments, "lit": lit, "loop": loop_found}

func _refresh() -> void:
	beam = _trace(turns)
	for tile in tile_buttons:
		var mirrored := _orientation(tile, turns)
		var button: Button = tile_buttons[tile]
		var glyph := "/" if mirrored == 0 else "\\"
		button.text = ("Split " if _turn_at(level.splitters, tile) >= 0 else "") + glyph
	var complete: bool = beam.lit.size() == level.targets.size()
	var message := "All exhibits awake!" if complete else "Tap a mirror or splitter to turn it."
	if beam.loop:
		message = "A ray repeated a step. Turn the splitter to break the loop."
	status.text = "%s\n\nExhibits awake: %d of %d\n%s" % [level.title, beam.lit.size(), level.targets.size(), message]

	queue_redraw()

func _cell(tile: int) -> Vector2:
	var col := tile % int(level.width)
	var row := floori(float(tile) / int(level.width))
	return ORIGIN + Vector2(col, row) * PITCH

func _center(tile: int) -> Vector2:
	return _cell(tile) + Vector2(TILE * 0.5, TILE * 0.5)

func _draw() -> void:
	draw_rect(Rect2(Vector2.ZERO, Vector2(900, 540)), Color("#132b3c"))

	if level.is_empty():
		return
	for column in range(int(level.width)):
		draw_string(ThemeDB.fallback_font, _cell(column) + Vector2(30, -8), str(column + 1), HORIZONTAL_ALIGNMENT_LEFT, -1, 13, Color("#f0d096"))
	for row in range(int(level.height)):
		draw_string(ThemeDB.fallback_font, _cell(row * int(level.width)) + Vector2(-17, 43), str(row + 1), HORIZONTAL_ALIGNMENT_LEFT, -1, 13, Color("#f0d096"))
	for tile in range(int(level.width) * int(level.height)):
		var box := Rect2(_cell(tile), Vector2(TILE, TILE))
		draw_rect(box, Color("#1d4859"))
		draw_rect(box, Color("#63858b"), false, 1.0)
		if tile == int(level.source):
			draw_circle(box.get_center(), 17.0, Color("#ffcc79"))
		elif level.targets.has(tile):
			var awake: bool = beam.get("lit", []).has(tile)
			draw_circle(box.get_center(), 16.0, Color("#9effd5") if awake else Color("#526580"))
			draw_arc(box.get_center(), 20.0, 0.0, TAU, 24, Color("#fbf0d1"), 2.0, true)
	for segment in beam.get("segments", []):
		draw_line(_center(segment.x), _center(segment.y), Color("#8cf5de"), 4.0, true)

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 STEPS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]Creates a constant named STEPS. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  3. const TURNS: Array = [[1, 0, 3, 2], [3, 2, 1, 0]]Creates a constant named TURNS. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  4. const ORIGIN := Vector2(32, 139)Creates a constant named ORIGIN. The expression packs x and y into one value. Godot infers the type from the first value.
  5. const PITCH := 78Creates a constant named PITCH. The expression uses the whole number 78. Godot infers the type from the first value.
  6. const TILE := 70Creates a constant named TILE. The expression uses the whole number 70. Godot infers the type from the first value.
  7. const DEMO: Dictionary = {"title": "The returning ray", "width": 6, "height": 4, "source": 8, "direction": 1, "mirrors": {"7": 0, "13": 1, "15": 0}, "splitters": {"9": 1}, "targets": [3, 11], "walls": []}Creates a constant named DEMO. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold.
  8. var level: DictionaryDeclares level for later use. A colon followed by a type says which kind of value belongs here.
  9. var turns: Dictionary = {}Creates a variable named turns. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold.
  10. var beam: DictionaryDeclares beam for later use. A colon followed by a type says which kind of value belongs here.
  11. var tile_buttons: Dictionary = {}Creates a variable named tile_buttons. The expression makes a dictionary that looks up values by key. The type after the colon says what kind of value it can hold.
  12. var board_layer: ControlDeclares board_layer for later use. A colon followed by a type says which kind of value belongs here.
  13. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  14. 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.
  15. _add_label(Vector2(31, 21), "MUSEUM OF LOST LIGHTS", 29)Calls _add_label with the values in its parentheses.
  16. _add_label(Vector2(32, 64), "Catch a ray that goes in circles", 15)Calls _add_label with the values in its parentheses.
  17. status = _add_label(Vector2(576, 174), "", 17)Stores the new value in status. The expression calls _add_label with the values in its parentheses.
  18. status.custom_minimum_size = Vector2(302, 141)Updates status.custom_minimum_size, which controls the smallest space the layout should reserve for this control. The expression packs x and y into one value.
  19. status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTStores the new value in status.autowrap_mode. The expression reads TextServer.AUTOWRAP_WORD_SMART.
  20. board_layer = Control.new()Stores the new value in board_layer. The expression creates a new Control object.
  21. board_layer.mouse_filter = Control.MOUSE_FILTER_IGNOREUpdates board_layer.mouse_filter, which controls how this control participates in pointer and touch input. The expression reads Control.MOUSE_FILTER_IGNORE.
  22. add_child(board_layer)Adds the new node to the scene tree so that Godot can run and draw it.
  23. _load_level(DEMO)Calls _load_level with the values in its parentheses.
  24. func _add_label(at: Vector2, text: String, text_size: int) -> Label:Defines add 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.
  25. var label := Label.new()Creates a variable named label. The expression creates a new Label object. Godot infers the type from the first value.
  26. label.position = atUpdates label.position, which controls the node's local x and y location. The expression reads at.
  27. label.text = textUpdates label.text, which controls the words a player sees. The expression reads text.
  28. label.add_theme_font_size_override("font_size", text_size)Calls label.add_theme_font_size_override with the values in its parentheses.
  29. label.add_theme_color_override("font_color", Color("#fff1d4"))Calls label.add_theme_color_override with the values in its parentheses.
  30. add_child(label)Adds the new node to the scene tree so that Godot can run and draw it.
  31. return labelFinishes the function and hands its result back to the caller. The expression reads label.
  32. func _load_level(data: Dictionary) -> void:Defines load level, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  33. level = dataStores the new value in level. The expression reads data.
  34. turns.clear()Empties this collection.
  35. tile_buttons.clear()Empties this collection.
  36. for child in board_layer.get_children():Repeats the indented instructions for each value in board_layer.get_children().
  37. child.queue_free()Asks Godot to remove this node safely at the end of the frame.
  38. for tile in range(int(level.width) * int(level.height)):Repeats the indented instructions for each value in range(int(level.width) * int(level.height)).
  39. var is_mirror := _turn_at(level.mirrors, tile) >= 0Creates a variable named is_mirror. The expression calls _turn_at with the values in its parentheses. Godot infers the type from the first value.
  40. var is_splitter := _turn_at(level.splitters, tile) >= 0Creates a variable named is_splitter. The expression calls _turn_at with the values in its parentheses. Godot infers the type from the first value.
  41. if is_mirror or is_splitter:Checks is_mirror or is_splitter. The indented instructions below run only if this test passes.
  42. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  43. button.position = _cell(tile)Updates button.position, which controls the node's local x and y location. The expression calls _cell with the values in its parentheses.
  44. button.size = Vector2(TILE, TILE)Updates button.size, which controls the control's width and height. The expression packs x and y into one value.
  45. button.tooltip_text = "Rotate " + ("splitter" if is_splitter else "mirror")Stores the new value in button.tooltip_text. The expression chooses one of two values by checking the condition in the middle.
  46. button.pressed.connect(_turn_tile.bind(tile))Links a signal to the function that should run when the event happens.
  47. board_layer.add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  48. tile_buttons[tile] = buttonStores the new value in tile_buttons[tile]. The expression reads button.
  49. _refresh()Calls _refresh with the values in its parentheses.
  50. func _turn_at(layout: Dictionary, tile: int) -> int:Defines turn 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.
  51. return int(layout.get(str(tile), -1))Finishes the function and hands its result back to the caller. The expression converts a suitable value to a whole number.
  52. func _orientation(tile: int, state: Dictionary) -> int:Defines orientation, 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.
  53. var start := _turn_at(level.mirrors, tile)Creates a variable named start. The expression calls _turn_at with the values in its parentheses. Godot infers the type from the first value.
  54. if start < 0:Checks start < 0. The indented instructions below run only if this test passes.
  55. start = _turn_at(level.splitters, tile)Stores the new value in start. The expression calls _turn_at with the values in its parentheses.
  56. return int(state.get(tile, start))Finishes the function and hands its result back to the caller. The expression converts a suitable value to a whole number.
  57. func _turn_tile(tile: int) -> void:Defines turn 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.
  58. turns[tile] = 1 - _orientation(tile, turns)Stores the new value in turns[tile]. The expression calculates a new value from the expressions on either side of the operator.
  59. _refresh()Calls _refresh with the values in its parentheses.
  60. func _trace(state: 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.
  61. var segments: Array[Vector2i] = []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.
  62. 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.
  63. 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.
  64. var pending: Array[Dictionary] = [{"ray": Vector2i(int(level.source), int(level.direction)), "seen": {}}]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.
  65. 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.
  66. var item: Dictionary = pending.pop_front()Creates a variable named item. The expression takes the first item out of the list and returns it. The type after the colon says what kind of value it can hold.
  67. var ray: Vector2i = item.rayCreates a variable named ray. The expression reads item.ray. The type after the colon says what kind of value it can hold.
  68. var seen: Dictionary = item.seenCreates a variable named seen. The expression reads item.seen. The type after the colon says what kind of value it can hold.
  69. if seen.has(ray):Checks seen.has(ray). The indented instructions below run only if this test passes.
  70. loop_found = trueStores the new value in loop_found. The expression uses the yes-or-no value true.
  71. continueSkips the rest of this turn through the loop and moves on to the next item.
  72. var trail := seen.duplicate()Creates a variable named trail. The expression copies the collection so a later change can leave the original alone. Godot infers the type from the first value.
  73. trail[ray] = trueStores the new value in trail[ray]. The expression uses the yes-or-no value true.
  74. var tile := ray.xCreates a variable named tile. The expression reads ray.x. Godot infers the type from the first value.
  75. var direction := ray.yCreates a variable named direction. The expression reads ray.y. Godot infers the type from the first value.
  76. var coordinates := Vector2i(tile % int(level.width), floori(float(tile) / int(level.width)))Creates a variable named coordinates. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  77. var next_position := coordinates + STEPS[direction]Creates a variable named next_position. The expression looks up the item or key written between the square brackets. Godot infers the type from the first value.
  78. if not Rect2i(0, 0, int(level.width), int(level.height)).has_point(next_position):Checks not Rect2i(0, 0, int(level.width), int(level.height)).has_point(next_position). The indented instructions below run only if this test passes.
  79. continueSkips the rest of this turn through the loop and moves on to the next item.
  80. var next_tile := next_position.y * int(level.width) + next_position.xCreates a variable named next_tile. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  81. segments.append(Vector2i(tile, next_tile))Adds an item to the end of a list.
  82. if level.targets.has(next_tile) and not lit.has(next_tile):Checks level.targets.has(next_tile) and not lit.has(next_tile). The indented instructions below run only if this test passes.
  83. lit.append(next_tile)Adds an item to the end of a list.
  84. if level.walls.has(next_tile):Checks level.walls.has(next_tile). The indented instructions below run only if this test passes.
  85. continueSkips the rest of this turn through the loop and moves on to the next item.
  86. var splitter := _turn_at(level.splitters, next_tile)Creates a variable named splitter. The expression calls _turn_at with the values in its parentheses. Godot infers the type from the first value.
  87. if splitter >= 0:Checks splitter >= 0. The indented instructions below run only if this test passes.
  88. pending.append({"ray": Vector2i(next_tile, direction), "seen": trail})Adds an item to the end of a list.
  89. var branch: int = TURNS[_orientation(next_tile, state)][direction]Creates a variable named branch. 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.
  90. pending.append({"ray": Vector2i(next_tile, branch), "seen": trail})Adds an item to the end of a list.
  91. else:Runs the indented fallback instructions if none of the earlier tests passed.
  92. var mirror := _turn_at(level.mirrors, next_tile)Creates a variable named mirror. The expression calls _turn_at with the values in its parentheses. Godot infers the type from the first value.
  93. var onward: int = TURNS[_orientation(next_tile, state)][direction] if mirror >= 0 else directionCreates a variable named onward. The expression chooses one of two values by checking the condition in the middle. The type after the colon says what kind of value it can hold.
  94. pending.append({"ray": Vector2i(next_tile, onward), "seen": trail})Adds an item to the end of a list.
  95. 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.
  96. func _refresh() -> void:Defines refresh, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  97. beam = _trace(turns)Stores the new value in beam. The expression calls _trace with the values in its parentheses.
  98. for tile in tile_buttons:Repeats the indented instructions for each value in tile_buttons.
  99. var mirrored := _orientation(tile, turns)Creates a variable named mirrored. The expression calls _orientation with the values in its parentheses. Godot infers the type from the first value.
  100. var button: Button = tile_buttons[tile]Creates a variable named button. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold.
  101. var glyph := "/" if mirrored == 0 else "\\"Creates a variable named glyph. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  102. button.text = ("Split " if _turn_at(level.splitters, tile) >= 0 else "") + glyphUpdates button.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  103. var complete: bool = beam.lit.size() == level.targets.size()Creates a variable named complete. The expression counts the items in this collection. The type after the colon says what kind of value it can hold.
  104. var message := "All exhibits awake!" if complete else "Tap a mirror or splitter to turn it."Creates a variable named message. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  105. if beam.loop:Checks beam.loop. The indented instructions below run only if this test passes.
  106. message = "A ray repeated a step. Turn the splitter to break the loop."Stores the new value in message. The expression uses the text inside the quotes.
  107. status.text = "%s\n\nExhibits awake: %d of %d\n%s" % [level.title, beam.lit.size(), level.targets.size(), message]Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  108. queue_redraw()Asks Godot to call _draw again on a later frame so the screen matches the new state.
  109. func _cell(tile: int) -> Vector2:Defines cell, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  110. var col := tile % int(level.width)Creates a variable named col. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  111. var row := floori(float(tile) / int(level.width))Creates a variable named row. The expression calls floori with the values in its parentheses. Godot infers the type from the first value.
  112. return ORIGIN + Vector2(col, row) * PITCHFinishes the function and hands its result back to the caller. The expression calculates a new value from the expressions on either side of the operator.
  113. func _center(tile: int) -> Vector2:Defines center, 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.
  114. return _cell(tile) + Vector2(TILE * 0.5, TILE * 0.5)Finishes the function and hands its result back to the caller. The expression calls _cell with the values in its parentheses.
  115. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  116. draw_rect(Rect2(Vector2.ZERO, Vector2(900, 540)), Color("#132b3c"))Paints a rectangle at the given position and size.
  117. if level.is_empty():Checks level.is_empty(). The indented instructions below run only if this test passes.
  118. returnFinishes the function right here. Any later instructions in this function are skipped.
  119. for column in range(int(level.width)):Repeats the indented instructions for each value in range(int(level.width)).
  120. draw_string(ThemeDB.fallback_font, _cell(column) + Vector2(30, -8), str(column + 1), HORIZONTAL_ALIGNMENT_LEFT, -1, 13, Color("#f0d096"))Paints a piece of text with a font at a position measured from the node's origin.
  121. for row in range(int(level.height)):Repeats the indented instructions for each value in range(int(level.height)).
  122. draw_string(ThemeDB.fallback_font, _cell(row * int(level.width)) + Vector2(-17, 43), str(row + 1), HORIZONTAL_ALIGNMENT_LEFT, -1, 13, Color("#f0d096"))Paints a piece of text with a font at a position measured from the node's origin.
  123. for tile in range(int(level.width) * int(level.height)):Repeats the indented instructions for each value in range(int(level.width) * int(level.height)).
  124. var box := Rect2(_cell(tile), Vector2(TILE, TILE))Creates a variable named box. The expression describes a position and a size. Godot infers the type from the first value.
  125. draw_rect(box, Color("#1d4859"))Paints a rectangle at the given position and size.
  126. draw_rect(box, Color("#63858b"), false, 1.0)Paints a rectangle at the given position and size.
  127. if tile == int(level.source):Checks tile == int(level.source). The indented instructions below run only if this test passes.
  128. draw_circle(box.get_center(), 17.0, Color("#ffcc79"))Paints a filled circle or outline in this node's local coordinates.
  129. elif level.targets.has(tile):If the earlier branches did not run, checks level.targets.has(tile) next.
  130. var awake: bool = beam.get("lit", []).has(tile)Creates a variable named awake. 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.
  131. draw_circle(box.get_center(), 16.0, Color("#9effd5") if awake else Color("#526580"))Paints a filled circle or outline in this node's local coordinates.
  132. draw_arc(box.get_center(), 20.0, 0.0, TAU, 24, Color("#fbf0d1"), 2.0, true)Calls draw_arc with the values in its parentheses.
  133. for segment in beam.get("segments", []):Repeats the indented instructions for each value in beam.get("segments", []).
  134. draw_line(_center(segment.x), _center(segment.y), Color("#8cf5de"), 4.0, true)Paints a line between two points with the chosen colour and width.

Find and fix a bug

If a beam that crosses another beam creates an unexpected warning, check that the key is the whole ray and that you duplicate seen before writing to it.

Try a change

Guided: show the returning route on a paper board. Stretch: design two branches that cross at one tile and explain why crossing is different from repeating the same state.