Mobile Game 08 · Build the board from rows and columns

Museum of Lost Lights · Lesson 08 of 50 · Beginner · About 43 min

The museum floor is about to become a puzzle. Label the tiles, then teach the script how to find a tile after someone taps it.

A gouache painting of an Ocean Gallery with glass jellyfish exhibits, fossils and a deep teal floor.
What you’ll make Use nested loops to build a 3-by-3 grid of buttons. Remember which cell the player chose with Vector2i.

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

Repeat for each row. The outer loop controls y. → Repeat for each column. The inner loop controls x. → Bind a coordinate. Each button remembers one position. → Name the selected tile. The label shows the position and index.
Repeat for each row → Repeat for each column → Bind a coordinate → Name the selected tile

Build it step by step

Language and tools in this lesson for, in, range, GridContainer, Vector2i, Callable.bind, coordinate, index.

  1. Set up the size and the point

    Import Lesson 08 and run the scene. Find COLUMNS, ROWS and the line that first sets selected. Look at the top left tile and check its label.

    var selected: Vector2i = Vector2i(0, 0)

    Why it works Vector2i keeps two whole numbers, x and y, in one value. For a grid, x tells you the column and y tells you the row. The first of each is zero.

  2. Build one row at a time

    Read the outer loop that uses row, then the inner loop that uses column. Sketch the order in which the first four buttons are made.

    for row in range(ROWS):
    		for column in range(COLUMNS):

    Why it works range(3) gives the loop the numbers 0, 1 and 2. The inner loop makes a full row for each outer turn. GridContainer wraps controls after it has added three to the same row.

  3. Keep each tile’s address

    Find the line that connects the tile’s signal. Tap two different cells in the game. Look for evidence that the function got the position of each one.

    tile.pressed.connect(pick_cell.bind(cell))

    Why it works The pressed signal itself supplies no cell. bind wraps the callable with this tile’s cell as an extra argument. When the tile asks Godot to call it, pick_cell receives that particular coordinate.

  4. Turn a coordinate into one index

    Read the calculation for index. Test the second row, rightmost tile. Note the difference between the coordinate in its own tile and the tile number across the whole grid.

    var index := selected.y * COLUMNS + selected.x

    Why it works Multiply by the width to count every tile in the earlier rows. Add x to count across the selected row. This gives each coordinate a single number.

  5. Compare a second board size

    Stop and change COLUMNS from 3 to 4. Save and run. Count the buttons and tap (2,1) again. Explain how the index changed.

    Why it works The loop, the visual grid and the index calculation all read COLUMNS. The empty spaces and labels will line up because they use the same size.

Watch the values change

  1. Start the first outer turn row = 0 and column loops over 0, 1, 2
    What you see. The first three tiles appear across the top.
  2. Finish building the grid The outer loop reaches row 2
    What you see. The 3-by-3 floor has nine tiles.
  3. Tap (2,1) The bound cell is Vector2i(2, 1)
    What you see. selected now holds column 2, row 1.
  4. Update the readout 1 × 3 + 2 is 5
    What you see. The tile index shows 5.

Predict before you run What index should you see at (1,2) on the original three-column board?

Reveal the answer

The index is 7. Two complete rows occupy six cells and one more position gets you to (1,2).

Complete checkpoint

The game shows nine labelled tiles. Tapping 2,1 gives Column 2, row 1 • Tile index 5.

main.gd

extends Control

const COLUMNS: int = 3
const ROWS: int = 3
var selected: Vector2i = Vector2i(0, 0)
var sign: Label

func _ready() -> void:
	make_heading()
	sign = Label.new()
	sign.position = Vector2(54, 105)
	sign.add_theme_font_size_override("font_size", 24)
	add_child(sign)

	var grid := GridContainer.new()
	grid.columns = COLUMNS
	grid.position = Vector2(54, 161)
	grid.add_theme_constant_override("h_separation", 8)
	grid.add_theme_constant_override("v_separation", 8)
	add_child(grid)
	for row in range(ROWS):
		for column in range(COLUMNS):
			var cell := Vector2i(column, row)
			var tile := Button.new()
			tile.text = "%d,%d" % [cell.x, cell.y]
			tile.custom_minimum_size = Vector2(82, 68)
			tile.add_theme_font_size_override("font_size", 23)
			tile.pressed.connect(pick_cell.bind(cell))
			grid.add_child(tile)
	update_sign()

func pick_cell(cell: Vector2i) -> void:
	selected = cell
	update_sign()

func update_sign() -> void:
	var index := selected.y * COLUMNS + selected.x
	sign.text = "Column %d, row %d   •   Tile index %d" % [selected.x, selected.y, index]

func make_heading() -> void:
	var heading := Label.new()
	heading.text = "Ocean Gallery · Mark the floor"
	heading.position = Vector2(52, 36)
	heading.add_theme_font_size_override("font_size", 38)
	heading.add_theme_color_override("font_color", Color("#ffe1a8"))
	add_child(heading)

GDScript line by line

Follow the line numbers, including the indent at the start of each line. Find the code the game will run first, then look for the function that reacts when you tap or change something.

Read main.gd line by line
  1. extends ControlThe scene root behaves like a Control, the kind of Godot node used for a game’s text, controls and other interface pieces.
  2. const COLUMNS: int = 3Let the width be shared by both the visual grid and the tile-number formula.
  3. const ROWS: int = 3Let the row loop create this many rows.
  4. var selected: Vector2i = Vector2i(0, 0)Start selected at the column 0, row 0 tile. Vector2i stores these coordinates as two whole numbers.
  5. var sign: LabelKeep the readout reference available after _ready returns so later taps can update it.
  6. func _ready() -> void:Godot automatically calls this setup function after bringing this node and its children into the scene. The code below it prepares the first frame.
  7. make_heading()Build the title before the room makes its other controls.
  8. sign = Label.new()Stores the new value in sign. The expression creates a new Label object.
  9. sign.position = Vector2(54, 105)Use two numbers to give this control its position, measured right and down from the root.
  10. sign.add_theme_font_size_override("font_size", 24)Set a larger or smaller font here without changing the typography on the other controls.
  11. add_child(sign)Adds the new node to the scene tree so that Godot can run and draw it.
  12. var grid := GridContainer.new()Create a container that lays out child controls in rows of a fixed width.
  13. grid.columns = COLUMNSSet the number of controls that can sit across one visual row before wrapping.
  14. grid.position = Vector2(54, 161)Use two numbers to give this control its position, measured right and down from the root.
  15. grid.add_theme_constant_override("h_separation", 8)Leave eight pixels between tiles next to one another horizontally.
  16. grid.add_theme_constant_override("v_separation", 8)Leave eight pixels of space between rows.
  17. add_child(grid)Attach the board’s container to the scene before putting controls inside it.
  18. for row in range(ROWS):Loop over row numbers zero to ROWS minus one. Each outer turn prepares a full row.
  19. for column in range(COLUMNS):Within the active row, count across the columns from zero through COLUMNS minus one.
  20. var cell := Vector2i(column, row)Store this cell as an x and y coordinate. x is its column number and y is its row number.
  21. var tile := Button.new()Make a fresh Button for this particular cell before the loop moves on.
  22. tile.text = "%d,%d" % [cell.x, cell.y]Put x into the first number gap and y into the second, producing text such as 2,1.
  23. tile.custom_minimum_size = Vector2(82, 68)Use a wide and tall enough button area to make all nine coordinates comfortable to tap.
  24. tile.add_theme_font_size_override("font_size", 23)Set a larger or smaller font here without changing the typography on the other controls.
  25. tile.pressed.connect(pick_cell.bind(cell))Attach this tile’s address to the function it will call when pressed. Each button now has a different argument ready for its own tap.
  26. grid.add_child(tile)Add the new tile in order. The grid puts it into the next available row position.
  27. update_sign()Display the initial selection after finishing all the button creation.
  28. func pick_cell(cell: Vector2i) -> void:Accept the coordinate stored in the particular button connection.
  29. selected = cellReplace the previous selection with the coordinate of the latest tile tap.
  30. update_sign()Use the new selection to refresh the label immediately.
  31. func update_sign() -> void:Read which cell is selected to produce the three values shown on the panel.
  32. var index := selected.y * COLUMNS + selected.xMultiply by the width to count completed rows, then add selected.x to count across the current row.
  33. sign.text = "Column %d, row %d • Tile index %d" % [selected.x, selected.y, index]Put the column, row and calculated tile number into the three whole-number gaps in the sign.
  34. func make_heading() -> void:Group the instructions that make the panel title. The room calls this once at startup.
  35. var heading := Label.new()Create a Label node and keep a reference under the name heading so the next lines all customise the same sign.
  36. heading.text = "Ocean Gallery · Mark the floor"Show the name of this museum task above its controls.
  37. heading.position = Vector2(52, 36)Put the title 52 pixels to the right and 36 pixels down from the root’s upper-left corner.
  38. heading.add_theme_font_size_override("font_size", 38)Set this heading’s font size to 38. The other labels keep their own sizes.
  39. heading.add_theme_color_override("font_color", Color("#ffe1a8"))Give only this label a warm gold text colour. The six characters after # describe red, green and blue light.
  40. add_child(heading)Connect the title to the scene tree so Godot can display it.

Find and fix a bug

If every tile reports the same position, check that cell is made inside the inner loop and passed to pick_cell.bind(cell) on the same turn. If the board wraps in the wrong place check grid.columns.

Try a change

Ages 10–12: Tap the four corners and note their indexes. Ages 13–16: Find the inverse rule for a tile index using whole-number division and remainder. Check your rule on all nine tiles.