Mobile Game 13 · Turn the beam with a mirror

Museum of Lost Lights · Lesson 13 of 50 · Beginner to intermediate · About 36 min

To reach the sleeping exhibit, the beam has to turn. Give each mirror a two-way switch and calculate the new compass arrow.

A gouache painting of an Ocean Gallery with glass jellyfish exhibits, fossils and a deep teal floor.
What you’ll make Make the slash and backslash redirect the beam in two different directions.

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

Read the incoming ray. Keep the horizontal and vertical step as a pair. → Check the mirror slant. Slash is 0 and backslash is 1. → Reflect the ray. Slash swaps and flips signs; backslash swaps. → Walk in the new direction. Each loop turn reuses the updated step.
Read the incoming ray → Check the mirror slant → Reflect the ray → Walk in the new direction

Build it step by step

Language and tools in this lesson function parameters, return value, if, unary minus, orientation, conditional expression, string escape.

  1. Compare the two mirror positions

    Open the scene. Tap the mirror. Draw the two orientations on paper as / and a backslash. Find the 1 - orientation expression and use 0 and 1 in it.

    orientation = 1 - orientation

    Why it works orientation stores one of two integers. Subtracting it from one toggles the value. This is puzzle state, the information your program needs on the next turn.

  2. Write the slash rule

    Read the first return in _reflect. For east (1, 0), put 1 where it says heading.x and 0 where it says heading.y. Work out the two coordinates before running.

    return Vector2i(-heading.y, -heading.x)

    Why it works The slash swaps the two components and reverses their signs. For east, that gives (0, −1), which is north because row numbers increase downwards.

  3. Use the backslash rule for the other state

    Read the last return. Calculate the same east example with this version. Trace one further example entering the backslash from the south, so the beam is heading north.

    return Vector2i(heading.y, heading.x)

    Why it works The first return exits the function when slant is 0. For 1, the last return swaps x and y without changing their signs. East becomes south, while north becomes west.

  4. Put the result back into the running path

    Look in _trace_beam for the mirror condition. Compare this lesson’s line inside the condition with the break in lesson 12. Tap the mirror and follow the path upwards, then tap again and follow it downwards.

    heading = _reflect(heading, orientation)

    Why it works The function takes a direction and slant as arguments. Reassigning heading keeps the new result for the next iteration of the loop. The next candidate square now uses the reflected direction.

  5. Show state in both the tile and caption

    Open _tile_label and read the mirror’s return expression. Locate the caption assignment in _render. Check that the tile shape and message always agree.

    return "/" if orientation == 0 else "\\"

    Why it works A conditional expression chooses the first value if its condition is true and the else value otherwise. A backslash in a string literal is escaped by typing two backslashes to display one.

Watch the values change

  1. Arrive from the west The beam heads east (1, 0)
    What you see. The beam reaches mirror 12.
  2. Use slant 1 Swap the pair
    What you see. Direction (0, 1) visits 17 and 22.
  3. Tap for slant 0 Swap and negate the pair
    What you see. Direction (0, −1) visits 7 and 2.

Predict before you run A ray heads south (0, 1) into a slash. What direction comes out?

Reveal the answer

The slash returns (−1, 0), meaning west. It moves one column left and keeps the row.

Complete checkpoint

The beam goes south at first. One tap flips the mirror and sends the beam north towards the exhibit. Another tap sends it south again.

main.gd

extends Control


const WIDTH := 5
const HEIGHT := 5
const SOURCE := 10
const TARGET := 2
const MIRROR := 12

const EAST := Vector2i(1, 0)
const SOUTH := Vector2i(0, 1)
const NORTH := Vector2i(0, -1)
const WEST := Vector2i(-1, 0)

var grid: GridContainer
var status: Label
var tiles: Array[Button] = []
var active_path: Array[int] = []
var orientation := 1


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 = "Ocean Gallery · tap the mirror to turn it"
    subheading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
    page.add_child(subheading)

    grid = GridContainer.new()
    grid.columns = 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)

    _make_tiles()
    _render()


func _make_tiles() -> void:
    for index in range(WIDTH * 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 index == MIRROR:
        orientation = 1 - orientation
        _render()


func _to_index(cell: Vector2i) -> int:
    return cell.y * WIDTH + cell.x

func _to_cell(index: int) -> Vector2i:
    @warning_ignore("integer_division")
    var row := index / WIDTH
    return Vector2i(index % WIDTH, row)


func _inside(cell: Vector2i) -> bool:
    return cell.x >= 0 and cell.y >= 0 and cell.x < WIDTH and cell.y < HEIGHT


func _trace_beam() -> Array[int]:
    var travelled: Array[int] = []
    var cell := _to_cell(SOURCE)
    var heading: Vector2i = EAST
    for step in range(WIDTH * HEIGHT * 4):
        var spot := _to_index(cell)
        travelled.append(spot)

        if spot == MIRROR:
            heading = _reflect(heading, orientation)

        var next_cell := cell + heading
        if not _inside(next_cell):
            break
        cell = next_cell
    return travelled

func _reflect(heading: Vector2i, slant: int) -> Vector2i:
    if slant == 0:
        return Vector2i(-heading.y, -heading.x)
    return Vector2i(heading.y, heading.x)


func _render() -> void:
    active_path = _trace_beam()
    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")
    status.text = "The mirror sends light up." if orientation == 0 else "The mirror sends light down."

func _tile_label(index: int) -> String:
    if index == SOURCE:
        return "Lamp"
    if index == TARGET:
        return "Goal"
    if index == MIRROR:
        return "/" if orientation == 0 else "\\"
    if active_path.has(index):
        return "Beam"
    return str(index)

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 WIDTH := 5Creates a constant named WIDTH. The expression uses the whole number 5. Godot infers the type from the first value.
  3. const HEIGHT := 5Creates a constant named HEIGHT. The expression uses the whole number 5. Godot infers the type from the first value.
  4. const SOURCE := 10Creates a constant named SOURCE. The expression uses the whole number 10. Godot infers the type from the first value.
  5. const TARGET := 2Creates a constant named TARGET. The expression uses the whole number 2. Godot infers the type from the first value.
  6. const MIRROR := 12Creates a constant named MIRROR. The expression uses the whole number 12. Godot infers the type from the first value.
  7. const EAST := Vector2i(1, 0)Creates a constant named EAST. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  8. const SOUTH := Vector2i(0, 1)Creates a constant named SOUTH. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  9. const NORTH := Vector2i(0, -1)Creates a constant named NORTH. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  10. const WEST := Vector2i(-1, 0)Creates a constant named WEST. The expression packs whole-number x and y into one grid position. Godot infers the type from the first value.
  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 orientation := 1Creates a variable named orientation. The expression uses the whole number 1. Godot infers the type from the first value.
  16. 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.
  17. var background := ColorRect.new()Creates a variable named background. The expression creates a new ColorRect object. Godot infers the type from the first value.
  18. background.color = Color("#102a3b")Stores the new value in background.color. The expression builds a colour from these values.
  19. 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.
  20. add_child(background)Adds the new node to the scene tree so that Godot can run and draw it.
  21. background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent.
  22. var centre := CenterContainer.new()Creates a variable named centre. The expression creates a new CenterContainer object. Godot infers the type from the first value.
  23. add_child(centre)Adds the new node to the scene tree so that Godot can run and draw it.
  24. centre.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Positions this Control relative to the bounds of its parent.
  25. var page := VBoxContainer.new()Creates a variable named page. The expression creates a new VBoxContainer object. Godot infers the type from the first value.
  26. page.add_theme_constant_override("separation", 8)Calls page.add_theme_constant_override with the values in its parentheses.
  27. centre.add_child(page)Adds the new node to the scene tree so that Godot can run and draw it.
  28. var heading := Label.new()Creates a variable named heading. The expression creates a new Label object. Godot infers the type from the first value.
  29. heading.text = "Museum of Lost Lights"Updates heading.text, which controls the words a player sees. The expression uses the text inside the quotes.
  30. heading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in heading.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER.
  31. heading.add_theme_font_size_override("font_size", 26)Calls heading.add_theme_font_size_override with the values in its parentheses.
  32. page.add_child(heading)Adds the new node to the scene tree so that Godot can run and draw it.
  33. var subheading := Label.new()Creates a variable named subheading. The expression creates a new Label object. Godot infers the type from the first value.
  34. subheading.text = "Ocean Gallery · tap the mirror to turn it"Updates subheading.text, which controls the words a player sees. The expression uses the text inside the quotes.
  35. subheading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in subheading.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER.
  36. page.add_child(subheading)Adds the new node to the scene tree so that Godot can run and draw it.
  37. grid = GridContainer.new()Stores the new value in grid. The expression creates a new GridContainer object.
  38. grid.columns = WIDTHStores the new value in grid.columns. The expression reads WIDTH.
  39. grid.size_flags_horizontal = Control.SIZE_SHRINK_CENTERStores the new value in grid.size_flags_horizontal. The expression reads Control.SIZE_SHRINK_CENTER.
  40. page.add_child(grid)Adds the new node to the scene tree so that Godot can run and draw it.
  41. status = Label.new()Stores the new value in status. The expression creates a new Label object.
  42. status.custom_minimum_size.x = 460Stores the new value in status.custom_minimum_size.x. The expression uses the whole number 460.
  43. status.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTERStores the new value in status.horizontal_alignment. The expression reads HORIZONTAL_ALIGNMENT_CENTER.
  44. page.add_child(status)Adds the new node to the scene tree so that Godot can run and draw it.
  45. _make_tiles()Calls _make_tiles with the values in its parentheses.
  46. _render()Calls _render with the values in its parentheses.
  47. 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.
  48. for index in range(WIDTH * HEIGHT):Repeats the indented instructions for each value in range(WIDTH * HEIGHT).
  49. var tile := Button.new()Creates a variable named tile. The expression creates a new Button object. Godot infers the type from the first value.
  50. 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.
  51. tile.focus_mode = Control.FOCUS_ALLStores the new value in tile.focus_mode. The expression reads Control.FOCUS_ALL.
  52. tile.pressed.connect(_tap_tile.bind(index))Links a signal to the function that should run when the event happens.
  53. tiles.append(tile)Adds an item to the end of a list.
  54. grid.add_child(tile)Adds the new node to the scene tree so that Godot can run and draw it.
  55. 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.
  56. if index == MIRROR:Checks index == MIRROR. The indented instructions below run only if this test passes.
  57. orientation = 1 - orientationStores the new value in orientation. The expression calculates a new value from the expressions on either side of the operator.
  58. _render()Calls _render with the values in its parentheses.
  59. func _to_index(cell: Vector2i) -> int:Defines to index, 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.
  60. return cell.y * WIDTH + cell.xFinishes 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.
  61. func _to_cell(index: int) -> Vector2i:Defines to 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.
  62. @warning_ignore("integer_division")This annotation gives Godot extra information about the declaration that follows.
  63. var row := index / 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.
  64. return Vector2i(index % WIDTH, row)Finishes the function and hands its result back to the caller. The expression packs whole-number x and y into one grid position.
  65. func _inside(cell: Vector2i) -> bool:Defines inside, 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. return cell.x >= 0 and cell.y >= 0 and cell.x < WIDTH and cell.y < HEIGHTFinishes the function and hands its result back to the caller. The expression evaluates the test to see whether it is true or false.
  67. 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.
  68. var travelled: Array[int] = []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.
  69. var cell := _to_cell(SOURCE)Creates a variable named cell. The expression calls _to_cell with the values in its parentheses. Godot infers the type from the first value.
  70. var heading: Vector2i = EASTCreates a variable named heading. The expression reads EAST. The type after the colon says what kind of value it can hold.
  71. for step in range(WIDTH * HEIGHT * 4):Repeats the indented instructions for each value in range(WIDTH * HEIGHT * 4).
  72. var spot := _to_index(cell)Creates a variable named spot. The expression calls _to_index with the values in its parentheses. Godot infers the type from the first value.
  73. travelled.append(spot)Adds an item to the end of a list.
  74. if spot == MIRROR:Checks spot == MIRROR. The indented instructions below run only if this test passes.
  75. heading = _reflect(heading, orientation)Stores the new value in heading. The expression calls _reflect with the values in its parentheses.
  76. var next_cell := cell + headingCreates a variable named next_cell. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  77. if not _inside(next_cell):Checks not _inside(next_cell). The indented instructions below run only if this test passes.
  78. breakLeaves the loop immediately and continues with code after the loop.
  79. cell = next_cellStores the new value in cell. The expression reads next_cell.
  80. return travelledFinishes the function and hands its result back to the caller. The expression reads travelled.
  81. func _reflect(heading: Vector2i, slant: int) -> Vector2i: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.
  82. if slant == 0:Checks slant == 0. The indented instructions below run only if this test passes.
  83. return Vector2i(-heading.y, -heading.x)Finishes the function and hands its result back to the caller. The expression packs whole-number x and y into one grid position.
  84. return Vector2i(heading.y, heading.x)Finishes the function and hands its result back to the caller. The expression packs whole-number x and y into one grid position.
  85. 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.
  86. active_path = _trace_beam()Stores the new value in active_path. The expression calls _trace_beam with the values in its parentheses.
  87. for index in range(tiles.size()):Repeats the indented instructions for each value in range(tiles.size()).
  88. 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.
  89. 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.
  90. 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.
  91. status.text = "The mirror sends light up." if orientation == 0 else "The mirror sends light down."Updates status.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  92. 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.
  93. if index == SOURCE:Checks index == SOURCE. The indented instructions below run only if this test passes.
  94. return "Lamp"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  95. if index == TARGET:Checks index == TARGET. The indented instructions below run only if this test passes.
  96. return "Goal"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  97. if index == MIRROR:Checks index == MIRROR. The indented instructions below run only if this test passes.
  98. return "/" if orientation == 0 else "\\"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.
  99. if active_path.has(index):Checks active_path.has(index). The indented instructions below run only if this test passes.
  100. return "Beam"Finishes the function and hands its result back to the caller. The expression uses the text inside the quotes.
  101. 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.

Find and fix a bug

If the ray always turns down, check the slant comparison and ensure you reassign heading from _reflect. If it leaves at a diagonal, check both Vector2i components are taken from the previous heading.

Try a change

Draw a four-direction chart for each mirror. For a stretch, choose a different lamp and mirror position on the board and predict which gallery edge both slants will reach.