Cruise Game 12 · Count legal steps

Midnight Deck Dash · Lesson 12 of 50 · Beginner to intermediate · About 28 min

The dispatch desk logs steps along the deck. A tap against a wall changes the feedback and leaves the delivery route count as it was.

A straight teak promenade with a cream cabin wall on one side and a ship railing above the moonlit ocean on the other.
What you’ll make Connect keyboard arrows and touch buttons to one move rule and count accepted moves.

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

Button or key. Gather one direction from either control. → Same rule. Send the direction to _try_move. → Accepted step. Increase turns after the guards. → Refresh the ledger. Format the new count as a string.
Button or key → Same rule → Accepted step → Refresh the ledger

Build it step by step

Language and tools in this lesson integer variables, +=, function parameters, Callable.bind, pressed.connect, match, key.echo, string interpolation.

  1. Load the lesson checkpoint

    Extract the lesson 12 checkpoint. In Godot Project Manager choose Import, then select project.godot. Open the scene from the FileSystem dock and select its Control root. Open main.gd in the Script workspace. Press F5. The dispatch ledger shows Moves: 0.

    extends Control

    Why it works The scene attaches this script to a Control node. This checkpoint uses the wall and edge guards from the previous lesson. Use F8 to stop the running scene before editing.

  2. Give the count a starting value

    Find var turns near courier. Check that the number starts at zero. Type in a different starting number as an experiment, run, and then change it back to zero.

    var turns := 0

    Why it works The variable remembers how many accepted moves have happened. The := tells Godot to infer the integer type from 0.

  3. Put the count after the guards

    Read from the top of _try_move to turns += 1. Use F5 to try Left, Right, Down. Record the number after each attempt.

    courier = candidate
    
    	turns += 1

    Why it works The early returns reject bad candidates. The += operation reads the existing count, adds one and stores the result only after courier moves.

  4. Connect a button to a direction

    Find _connect_direction in the Script workspace. Look up the four calls in _ready. For Left, point to the caption, screen position and Vector2i.LEFT value. Click the button to test it.

    button.pressed.connect(_try_move.bind(delta))

    Why it works Every Button has a pressed signal. bind stores the one direction the callback needs, so the four buttons can use the same _try_move function.

  5. Feed arrow keys into the same rule

    In _input, read the match for a Right arrow. Test a physical Right key and the on-screen Right button separately. Hold the key briefly and look for repeated steps.

    if not key.pressed or key.echo:
    		return

    Why it works match sends each recognised key to its branch. The pressed and echo checks count a real press once and skip the operating system's repeated key events.

  6. Show the count in the ledger

    Find _refresh. Print the expected integer on paper for three inputs, then compare with the Moves label. On a copy, change Moves to Steps and view the revised label.

    var report := "Moves: %d" % turns

    Why it works The %d placeholder asks for a number. After the game rule runs, _refresh puts the latest string into ledger_label.text and requests a new drawing.

Watch the values change

  1. Tap Left from START edge is invalid; turns stays 0
    What you see. The ledger still shows Moves: 0.
  2. Press Right the courier moves to (1, 0); turns becomes 1
    What you see. The ledger shows Moves: 1.
  3. Tap Down a bulkhead rejects (1, 1)
    What you see. The ledger still shows Moves: 1.

Predict before you run From START, will Right, Down, Right count as one, two or three moves?

Reveal the answer

Two. Both Right moves along row 0 are legal, and the Down attempt to (1, 1) is rejected.

Complete checkpoint

The on-screen and keyboard arrows use the same wall rule. The counter changes only when Sol changes square.

main.gd

extends Control

# The map has the same 7 columns and 5 rows as the first deck sketch.
const DECK_ROWS: Array[String] = [
	".......",
	".##....",
	"...#...",
	"...#...",
	".......",
]
const START := Vector2i(0, 0)
const CELL_SIZE := 62
const BOARD_ORIGIN := Vector2(38, 123)

var courier := START
var status := "Use the arrows or tap a direction."
var turns := 0

var status_label: Label
var ledger_label: Label


func _ready() -> void:
	status_label = Label.new()
	status_label.position = Vector2(535, 189)
	status_label.size = Vector2(370, 68)
	status_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	status_label.add_theme_color_override("font_color", Color("#ffea9f"))
	status_label.add_theme_font_size_override("font_size", 17)
	add_child(status_label)

	ledger_label = Label.new()
	ledger_label.position = Vector2(535, 278)
	ledger_label.size = Vector2(355, 105)
	ledger_label.add_theme_color_override("font_color", Color("#e3f5f5"))
	ledger_label.add_theme_font_size_override("font_size", 16)
	add_child(ledger_label)

	_connect_direction("Up", Vector2(675, 375), Vector2i.UP)
	_connect_direction("Left", Vector2(583, 430), Vector2i.LEFT)
	_connect_direction("Down", Vector2(675, 430), Vector2i.DOWN)
	_connect_direction("Right", Vector2(767, 430), Vector2i.RIGHT)
	_refresh()


func _make_button(caption: String, pixel: Vector2, dimensions: Vector2) -> Button:
	var button := Button.new()
	button.text = caption
	button.position = pixel
	button.size = dimensions
	button.add_theme_font_size_override("font_size", 16)
	add_child(button)
	return button


func _connect_direction(caption: String, pixel: Vector2, delta: Vector2i) -> void:
	var button := _make_button(caption, pixel, Vector2(84, 48))
	button.pressed.connect(_try_move.bind(delta))


func _draw() -> void:
	draw_rect(Rect2(Vector2.ZERO, size), Color("#081f31"))
	draw_rect(Rect2(24, 96, 469, 373), Color("#183b4d"))
	draw_rect(Rect2(513, 96, 421, 405), Color("#14374d"))
	var font := ThemeDB.fallback_font
	draw_string(font, Vector2(37, 44), "MIDNIGHT DECK DASH", HORIZONTAL_ALIGNMENT_LEFT, -1, 30, Color("#e9f0f2"))
	draw_string(font, Vector2(38, 73), "Cruise school  /  Promenade delivery shift", HORIZONTAL_ALIGNMENT_LEFT, -1, 17, Color("#adced5"))
	draw_string(font, Vector2(535, 119), "SHIPBOARD DISPATCH", HORIZONTAL_ALIGNMENT_LEFT, -1, 16, Color("#8edcd6"))
	for y in range(DECK_ROWS.size()):
		for x in range(DECK_ROWS[y].length()):
			var cell := Vector2i(x, y)
			var pixel := BOARD_ORIGIN + Vector2(cell) * CELL_SIZE
			var blocked := DECK_ROWS[y][x] == "#"
			var colour := Color("#22424a") if blocked else Color("#4a6c61")
			draw_rect(Rect2(pixel, Vector2(59, 59)), colour)
			if blocked:
				draw_line(pixel + Vector2(12, 12), pixel + Vector2(47, 47), Color("#688d90"), 4.0)
				draw_line(pixel + Vector2(12, 47), pixel + Vector2(47, 12), Color("#688d90"), 4.0)

	var courier_pixel := BOARD_ORIGIN + Vector2(courier) * CELL_SIZE
	var courier_center := courier_pixel + Vector2(29, 29)
	draw_circle(courier_center, 20.0, Color("#122734"))
	draw_circle(courier_center, 16.0, Color("#fff0b5"))
	draw_string(font, courier_pixel + Vector2(22, 35), "X", HORIZONTAL_ALIGNMENT_LEFT, -1, 18, Color("#10242f"))


func _inside(cell: Vector2i) -> bool:
	if cell.y < 0 or cell.y >= DECK_ROWS.size():
		return false
	return cell.x >= 0 and cell.x < DECK_ROWS[cell.y].length()


func _tile_at(cell: Vector2i) -> String:
	return DECK_ROWS[cell.y][cell.x]


func _try_move(delta: Vector2i) -> void:

	var candidate := courier + delta
	if not _inside(candidate):
		status = "That is outside the deck."
		_refresh()
		return
	if _tile_at(candidate) == "#":
		status = "A bulkhead blocks that square."
		_refresh()
		return

	courier = candidate

	turns += 1

	status = "Moved to column %d, row %d." % [courier.x + 1, courier.y + 1]

	_refresh()


func _refresh() -> void:
	status_label.text = status

	var report := "Moves: %d" % turns

	ledger_label.text = report
	queue_redraw()


func _input(event: InputEvent) -> void:
	if not event is InputEventKey:
		return
	var key := event as InputEventKey
	if not key.pressed or key.echo:
		return
	match key.keycode:
		KEY_UP:
			_try_move(Vector2i.UP)
		KEY_LEFT:
			_try_move(Vector2i.LEFT)
		KEY_DOWN:
			_try_move(Vector2i.DOWN)
		KEY_RIGHT:
			_try_move(Vector2i.RIGHT)

		_:
			return
	get_viewport().set_input_as_handled()

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 ControlGive the lesson scene a Control base so it can lay out interface nodes, draw the floor plan and handle player input.
  2. # The map has the same 7 columns and 5 rows as the first deck sketch.A comment for the reader. Godot skips it when it runs the code.
  3. const DECK_ROWS: Array[String] = [Keep the deck layout as an ordered array of strings. Each string is one row. A dot is walkable; a # is a bulkhead.
  4. ".......",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  5. ".##....",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  6. "...#...",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  7. "...#...",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  8. ".......",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  9. ]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  10. const START := Vector2i(0, 0)Name the opening square. Vector2i stores a pair of whole numbers, with column first and row second.
  11. const CELL_SIZE := 62Space tile origins 62 drawing pixels apart. This is a screen measurement; Sol's position is still measured in tiles.
  12. const BOARD_ORIGIN := Vector2(38, 123)Place the top-left board tile at screen pixel (38, 123), below the course banner.
  13. var courier := STARTStart Sol on the named starting square. courier is a variable because it will change when a move succeeds.
  14. var status := "Use the arrows or tap a direction."Creates a variable named status. The expression uses the text inside the quotes. Godot infers the type from the first value.
  15. var turns := 0Open the shift with zero accepted moves. Godot infers an integer from the zero.
  16. var status_label: LabelName the on-screen label that will display the latest action feedback after _ready creates it.
  17. var ledger_label: LabelName the label that will display the current move count, carried parcel, deliveries and rating.
  18. func _ready() -> void:Godot calls this scene setup method after adding the Control node. Build labels and buttons here once.
  19. status_label = Label.new()Stores the new value in status_label. The expression creates a new Label object.
  20. status_label.position = Vector2(535, 189)Updates status_label.position, which controls the node's local x and y location. The expression packs x and y into one value.
  21. status_label.size = Vector2(370, 68)Updates status_label.size, which controls the control's width and height. The expression packs x and y into one value.
  22. status_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTAllow feedback such as the wrong-station message to wrap onto the next line rather than overflowing the dispatch panel.
  23. status_label.add_theme_color_override("font_color", Color("#ffea9f"))Calls status_label.add_theme_color_override with the values in its parentheses.
  24. status_label.add_theme_font_size_override("font_size", 17)Calls status_label.add_theme_font_size_override with the values in its parentheses.
  25. add_child(status_label)Add the feedback label to the running scene so Godot can show it on screen.
  26. ledger_label = Label.new()Stores the new value in ledger_label. The expression creates a new Label object.
  27. ledger_label.position = Vector2(535, 278)Updates ledger_label.position, which controls the node's local x and y location. The expression packs x and y into one value.
  28. ledger_label.size = Vector2(355, 105)Updates ledger_label.size, which controls the control's width and height. The expression packs x and y into one value.
  29. ledger_label.add_theme_color_override("font_color", Color("#e3f5f5"))Calls ledger_label.add_theme_color_override with the values in its parentheses.
  30. ledger_label.add_theme_font_size_override("font_size", 16)Calls ledger_label.add_theme_font_size_override with the values in its parentheses.
  31. add_child(ledger_label)Add the ledger to the Control scene so players can read the latest course state.
  32. _connect_direction("Up", Vector2(675, 375), Vector2i.UP)Create the Up touch button. Vector2(675, 375) is the label's pixel position; Vector2i.UP is the step of one tile north.
  33. _connect_direction("Left", Vector2(583, 430), Vector2i.LEFT)Create a Left button that sends one tile west to the shared move function.
  34. _connect_direction("Down", Vector2(675, 430), Vector2i.DOWN)Create a Down button that sends one tile south to the shared move function.
  35. _connect_direction("Right", Vector2(767, 430), Vector2i.RIGHT)Create a Right button that sends one tile east to the shared move function.
  36. _refresh()Calls _refresh with the values in its parentheses.
  37. func _make_button(caption: String, pixel: Vector2, dimensions: Vector2) -> Button:Defines make button, 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.
  38. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  39. button.text = captionUpdates button.text, which controls the words a player sees. The expression reads caption.
  40. button.position = pixelUpdates button.position, which controls the node's local x and y location. The expression reads pixel.
  41. button.size = dimensionsUpdates button.size, which controls the control's width and height. The expression reads dimensions.
  42. button.add_theme_font_size_override("font_size", 16)Calls button.add_theme_font_size_override with the values in its parentheses.
  43. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  44. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  45. func _connect_direction(caption: String, pixel: Vector2, delta: Vector2i) -> void:Defines connect direction, 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.
  46. var button := _make_button(caption, pixel, Vector2(84, 48))Creates a variable named button. The expression calls _make_button with the values in its parentheses. Godot infers the type from the first value.
  47. button.pressed.connect(_try_move.bind(delta))Attach this button's own direction to the shared movement callback. A press now calls _try_move with the saved delta.
  48. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  49. draw_rect(Rect2(Vector2.ZERO, size), Color("#081f31"))Paints a rectangle at the given position and size.
  50. draw_rect(Rect2(24, 96, 469, 373), Color("#183b4d"))Paints a rectangle at the given position and size.
  51. draw_rect(Rect2(513, 96, 421, 405), Color("#14374d"))Paints a rectangle at the given position and size.
  52. var font := ThemeDB.fallback_fontCreates a variable named font. The expression reads ThemeDB.fallback_font. Godot infers the type from the first value.
  53. draw_string(font, Vector2(37, 44), "MIDNIGHT DECK DASH", HORIZONTAL_ALIGNMENT_LEFT, -1, 30, Color("#e9f0f2"))Paints a piece of text with a font at a position measured from the node's origin.
  54. draw_string(font, Vector2(38, 73), "Cruise school / Promenade delivery shift", HORIZONTAL_ALIGNMENT_LEFT, -1, 17, Color("#adced5"))Paints a piece of text with a font at a position measured from the node's origin.
  55. draw_string(font, Vector2(535, 119), "SHIPBOARD DISPATCH", HORIZONTAL_ALIGNMENT_LEFT, -1, 16, Color("#8edcd6"))Paints a piece of text with a font at a position measured from the node's origin.
  56. for y in range(DECK_ROWS.size()):Draw one row for each index from 0 to the row count minus one.
  57. for x in range(DECK_ROWS[y].length()):Inside each row, visit its own columns. Looking up each row's length helps if a later room has rows of different lengths.
  58. var cell := Vector2i(x, y)Bundle the current column and row into a game square.
  59. var pixel := BOARD_ORIGIN + Vector2(cell) * CELL_SIZEMultiply the tile address by the spacing, then add the screen offset to get its drawing location.
  60. var blocked := DECK_ROWS[y][x] == "#"Set a true-or-false flag by comparing the characters. Use it to paint a crossed tile when the cell is a bulkhead.
  61. var colour := Color("#22424a") if blocked else Color("#4a6c61")Pick one paint colour for a bulkhead and another for a hallway after reading blocked.
  62. draw_rect(Rect2(pixel, Vector2(59, 59)), colour)Paints a rectangle at the given position and size.
  63. if blocked:Checks blocked. The indented instructions below run only if this test passes.
  64. draw_line(pixel + Vector2(12, 12), pixel + Vector2(47, 47), Color("#688d90"), 4.0)Paints a line between two points with the chosen colour and width.
  65. draw_line(pixel + Vector2(12, 47), pixel + Vector2(47, 12), Color("#688d90"), 4.0)Paints a line between two points with the chosen colour and width.
  66. var courier_pixel := BOARD_ORIGIN + Vector2(courier) * CELL_SIZEMove the courier's drawn symbol to the pixel origin of its current game square.
  67. var courier_center := courier_pixel + Vector2(29, 29)Creates a variable named courier_center. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value.
  68. draw_circle(courier_center, 20.0, Color("#122734"))Paints a filled circle or outline in this node's local coordinates.
  69. draw_circle(courier_center, 16.0, Color("#fff0b5"))Paints a filled circle or outline in this node's local coordinates.
  70. draw_string(font, courier_pixel + Vector2(22, 35), "X", HORIZONTAL_ALIGNMENT_LEFT, -1, 18, Color("#10242f"))Paints a piece of text with a font at a position measured from the node's origin.
  71. func _inside(cell: Vector2i) -> bool:Return true only for a tile address that exists in the floor plan.
  72. if cell.y < 0 or cell.y >= DECK_ROWS.size():Reject rows before the first row and at or beyond the number of rows. The row is checked before it is indexed.
  73. return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false.
  74. return cell.x >= 0 and cell.x < DECK_ROWS[cell.y].length()Now that the row exists, accept the column only when it lies between zero and the row's last character.
  75. func _tile_at(cell: Vector2i) -> String:Defines tile 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.
  76. return DECK_ROWS[cell.y][cell.x]Use the row first and the column second to retrieve one tile character.
  77. func _try_move(delta: Vector2i) -> void:Use one movement rule for both input methods. delta is the proposed step.
  78. var candidate := courier + deltaCalculate the possible next square. Hold it in a temporary variable until both movement guards approve.
  79. if not _inside(candidate):Check the candidate's address before reading the map. The return below leaves the courier unchanged if the address is outside.
  80. status = "That is outside the deck."Stores the new value in status. The expression uses the text inside the quotes.
  81. _refresh()Calls _refresh with the values in its parentheses.
  82. returnFinishes the function right here. Any later instructions in this function are skipped.
  83. if _tile_at(candidate) == "#":Once you know the address exists, read its character. A # is a bulkhead and blocks this step.
  84. status = "A bulkhead blocks that square."Stores the new value in status. The expression uses the text inside the quotes.
  85. _refresh()Calls _refresh with the values in its parentheses.
  86. returnFinishes the function right here. Any later instructions in this function are skipped.
  87. courier = candidateCommit the checked move by replacing Sol's current square with the candidate.
  88. turns += 1Add one and store it back in turns. Only legal moves reach this line.
  89. status = "Moved to column %d, row %d." % [courier.x + 1, courier.y + 1]Stores the new value in status. The expression uses the text inside the quotes.
  90. _refresh()Calls _refresh with the values in its parentheses.
  91. 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.
  92. status_label.text = statusCopy the latest feedback text into the visible label.
  93. var report := "Moves: %d" % turnsCreates a variable named report. The expression uses the text inside the quotes. Godot infers the type from the first value.
  94. ledger_label.text = reportPresent the current dispatch report in the visible ledger label.
  95. queue_redraw()Ask Godot to run _draw again using the new game state.
  96. func _input(event: InputEvent) -> void:Receive input events from Godot and translate recognised keyboard actions into the same rules the touch buttons call.
  97. if not event is InputEventKey:Pass on non-keyboard input. On-screen Button nodes handle touch presses through their own pressed signals.
  98. returnFinishes the function right here. Any later instructions in this function are skipped.
  99. var key := event as InputEventKeyTreat the checked event as a keyboard event so its pressed, echo and keycode data are available.
  100. if not key.pressed or key.echo:Ignore key releases and automatic repeats. A distinct press therefore asks for one move.
  101. returnFinishes the function right here. Any later instructions in this function are skipped.
  102. match key.keycode:Compare the key code against the branches below and run the matching command.
  103. KEY_UP:Starts the instructions for this branch. The indented lines belong together.
  104. _try_move(Vector2i.UP)Calls _try_move with the values in its parentheses.
  105. KEY_LEFT:Starts the instructions for this branch. The indented lines belong together.
  106. _try_move(Vector2i.LEFT)Calls _try_move with the values in its parentheses.
  107. KEY_DOWN:Starts the instructions for this branch. The indented lines belong together.
  108. _try_move(Vector2i.DOWN)Calls _try_move with the values in its parentheses.
  109. KEY_RIGHT:Starts the instructions for this branch. The indented lines belong together.
  110. _try_move(Vector2i.RIGHT)Calls _try_move with the values in its parentheses.
  111. _:Handles every match value that the branches above did not handle.
  112. returnFinishes the function right here. Any later instructions in this function are skipped.
  113. get_viewport().set_input_as_handled()Mark a recognised key as already used so later input callbacks do not reuse that event.

Find and fix a bug

If an attempt against a wall increases the count, move turns += 1 below both invalid-move branches. If a single held key repeats movement, make sure the key.echo guard remains in _input.

Try a change

Ages 10–12: find a three-step route and confirm the number using a mix of taps and keys. Ages 13–16: add an alternative key for Right and trace why it still updates turns exactly once.