Cruise Game 11 · Keep Sol inside the ship

Midnight Deck Dash · Lesson 11 of 50 · Beginner to intermediate · About 27 min

Sol's shift begins on the Promenade. The square plan from the first chapter tells you which passages are open. Turn that plan into a working movement rule.

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 Make the game reject moves through bulkheads and beyond the deck edge.

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/10 when the lesson builds on prior work, or copy the checkpoints/11 folder to try this lesson on its own. Read the file names in the steps before editing. Keep the checkpoint ZIP intact and make edits in an extracted working copy.

Propose a square. Add the direction to the courier's square. → Check the edge. Only read a row and column that exist. → Read the tile. A # blocks the candidate. → Commit a move. Store and draw the candidate only if it is open.
Propose a square → Check the edge → Read the tile → Commit a move
Godot checkpoint window for Keep Sol inside the ship
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Vector2i addition, string indexing, Boolean conditions, >= and <, not, return, Control coordinates.

  1. Load the lesson checkpoint

    Extract the lesson 11 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 bulkheads are crossed tiles and X identifies Sol.

    extends Control

    Why it works The scene attaches this script to a Control node. The board, buttons and dispatch text all use the same Control script. Use F8 to stop the running scene before editing.

  2. Read the floor plan

    In main.gd find DECK_ROWS. Count the rows from the top and positions from the left. Row 1, column 1 in code reads as #. Notice that the location report for players starts counting at 1.

    return DECK_ROWS[cell.y][cell.x]

    Why it works Each string is one row. The first entry of an Array is index 0, so a code position of (1, 1) is the second square across and down.

  3. Keep a square as two whole numbers

    Find START. Read its first number as the column and its second as the row. In _try_move, trace Sol at (0, 0) pressing Right to get a candidate of (1, 0).

    var candidate := courier + delta

    Why it works Vector2i keeps two integers together. Adding a direction produces a proposed square and leaves courier unchanged until the rule approves it.

  4. Check the row before reading it

    In _inside, read the row guard before the horizontal edge test. Press F5 and tap Left from START. Read the boundary message.

    if cell.y < 0 or cell.y >= DECK_ROWS.size():
    		return false

    Why it works The row bounds guard comes first so DECK_ROWS[cell.y] is only read for an existing row. Returning false exits the function immediately.

  5. Check the proposed tile

    From START press Right, then Down. Locate the _tile_at check that stops Sol at the crossed square. Follow both return statements above the line that changes courier.

    if _tile_at(candidate) == "#":

    Why it works Down proposes (1, 1). Its # means a bulkhead. The early return leaves the old square in place and refreshes only the status.

  6. Draw the same rule you use to move

    Find the blocked expression in _draw. On a practice copy, change the first # in the second row to a dot. Press F5, go Right then Down, and check that the crossed square becomes open and enterable.

    var blocked := DECK_ROWS[y][x] == "#"

    Why it works Movement and painting both read DECK_ROWS. A room designer can change the map once and see the same rule in both places.

Watch the values change

  1. Tap Left from START candidate is (-1, 0); _inside returns false
    What you see. Sol stays at (0, 0).
  2. Tap Right candidate is (1, 0); its tile is a dot
    What you see. Sol moves one square east.
  3. Tap Down candidate is (1, 1); its tile is #
    What you see. Sol stays at (1, 0) and the bulkhead message appears.

Predict before you run From START, what happens if you tap Up before searching the map for a #?

Reveal the answer

The boundary check rejects row -1 first. Sol stays put, and the script never reads a tile for that candidate.

Complete checkpoint

Left and Up at START are rejected. From START, Right moves east and the next Down is rejected by the bulkhead.

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 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

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

	_refresh()


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

	var report := "Crossed tiles are bulkheads."

	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 status_label: LabelName the on-screen label that will display the latest action feedback after _ready creates it.
  16. var ledger_label: LabelName the label that will display the current move count, carried parcel, deliveries and rating.
  17. func _ready() -> void:Godot calls this scene setup method after adding the Control node. Build labels and buttons here once.
  18. status_label = Label.new()Stores the new value in status_label. The expression creates a new Label object.
  19. 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.
  20. 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.
  21. 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.
  22. status_label.add_theme_color_override("font_color", Color("#ffea9f"))Calls status_label.add_theme_color_override with the values in its parentheses.
  23. status_label.add_theme_font_size_override("font_size", 17)Calls status_label.add_theme_font_size_override with the values in its parentheses.
  24. add_child(status_label)Add the feedback label to the running scene so Godot can show it on screen.
  25. ledger_label = Label.new()Stores the new value in ledger_label. The expression creates a new Label object.
  26. 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.
  27. 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.
  28. ledger_label.add_theme_color_override("font_color", Color("#e3f5f5"))Calls ledger_label.add_theme_color_override with the values in its parentheses.
  29. ledger_label.add_theme_font_size_override("font_size", 16)Calls ledger_label.add_theme_font_size_override with the values in its parentheses.
  30. add_child(ledger_label)Add the ledger to the Control scene so players can read the latest course state.
  31. _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.
  32. _connect_direction("Left", Vector2(583, 430), Vector2i.LEFT)Create a Left button that sends one tile west to the shared move function.
  33. _connect_direction("Down", Vector2(675, 430), Vector2i.DOWN)Create a Down button that sends one tile south to the shared move function.
  34. _connect_direction("Right", Vector2(767, 430), Vector2i.RIGHT)Create a Right button that sends one tile east to the shared move function.
  35. _refresh()Calls _refresh with the values in its parentheses.
  36. 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.
  37. var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value.
  38. button.text = captionUpdates button.text, which controls the words a player sees. The expression reads caption.
  39. button.position = pixelUpdates button.position, which controls the node's local x and y location. The expression reads pixel.
  40. button.size = dimensionsUpdates button.size, which controls the control's width and height. The expression reads dimensions.
  41. button.add_theme_font_size_override("font_size", 16)Calls button.add_theme_font_size_override with the values in its parentheses.
  42. add_child(button)Adds the new node to the scene tree so that Godot can run and draw it.
  43. return buttonFinishes the function and hands its result back to the caller. The expression reads button.
  44. 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.
  45. 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.
  46. 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.
  47. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  48. draw_rect(Rect2(Vector2.ZERO, size), Color("#081f31"))Paints a rectangle at the given position and size.
  49. draw_rect(Rect2(24, 96, 469, 373), Color("#183b4d"))Paints a rectangle at the given position and size.
  50. draw_rect(Rect2(513, 96, 421, 405), Color("#14374d"))Paints a rectangle at the given position and size.
  51. var font := ThemeDB.fallback_fontCreates a variable named font. The expression reads ThemeDB.fallback_font. Godot infers the type from the first value.
  52. 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.
  53. 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.
  54. 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.
  55. for y in range(DECK_ROWS.size()):Draw one row for each index from 0 to the row count minus one.
  56. 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.
  57. var cell := Vector2i(x, y)Bundle the current column and row into a game square.
  58. var pixel := BOARD_ORIGIN + Vector2(cell) * CELL_SIZEMultiply the tile address by the spacing, then add the screen offset to get its drawing location.
  59. 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.
  60. var colour := Color("#22424a") if blocked else Color("#4a6c61")Pick one paint colour for a bulkhead and another for a hallway after reading blocked.
  61. draw_rect(Rect2(pixel, Vector2(59, 59)), colour)Paints a rectangle at the given position and size.
  62. if blocked:Checks blocked. The indented instructions below run only if this test passes.
  63. 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.
  64. 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.
  65. var courier_pixel := BOARD_ORIGIN + Vector2(courier) * CELL_SIZEMove the courier's drawn symbol to the pixel origin of its current game square.
  66. 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.
  67. draw_circle(courier_center, 20.0, Color("#122734"))Paints a filled circle or outline in this node's local coordinates.
  68. draw_circle(courier_center, 16.0, Color("#fff0b5"))Paints a filled circle or outline in this node's local coordinates.
  69. 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.
  70. func _inside(cell: Vector2i) -> bool:Return true only for a tile address that exists in the floor plan.
  71. 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.
  72. return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false.
  73. 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.
  74. 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.
  75. return DECK_ROWS[cell.y][cell.x]Use the row first and the column second to retrieve one tile character.
  76. func _try_move(delta: Vector2i) -> void:Use one movement rule for both input methods. delta is the proposed step.
  77. var candidate := courier + deltaCalculate the possible next square. Hold it in a temporary variable until both movement guards approve.
  78. 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.
  79. status = "That is outside the deck."Stores the new value in status. The expression uses the text inside the quotes.
  80. _refresh()Calls _refresh with the values in its parentheses.
  81. returnFinishes the function right here. Any later instructions in this function are skipped.
  82. if _tile_at(candidate) == "#":Once you know the address exists, read its character. A # is a bulkhead and blocks this step.
  83. status = "A bulkhead blocks that square."Stores the new value in status. The expression uses the text inside the quotes.
  84. _refresh()Calls _refresh with the values in its parentheses.
  85. returnFinishes the function right here. Any later instructions in this function are skipped.
  86. courier = candidateCommit the checked move by replacing Sol's current square with the candidate.
  87. 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.
  88. _refresh()Calls _refresh with the values in its parentheses.
  89. 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.
  90. status_label.text = statusCopy the latest feedback text into the visible label.
  91. var report := "Crossed tiles are bulkheads."Creates a variable named report. The expression uses the text inside the quotes. Godot infers the type from the first value.
  92. ledger_label.text = reportPresent the current dispatch report in the visible ledger label.
  93. queue_redraw()Ask Godot to run _draw again using the new game state.
  94. func _input(event: InputEvent) -> void:Receive input events from Godot and translate recognised keyboard actions into the same rules the touch buttons call.
  95. if not event is InputEventKey:Pass on non-keyboard input. On-screen Button nodes handle touch presses through their own pressed signals.
  96. returnFinishes the function right here. Any later instructions in this function are skipped.
  97. var key := event as InputEventKeyTreat the checked event as a keyboard event so its pressed, echo and keycode data are available.
  98. if not key.pressed or key.echo:Ignore key releases and automatic repeats. A distinct press therefore asks for one move.
  99. returnFinishes the function right here. Any later instructions in this function are skipped.
  100. match key.keycode:Compare the key code against the branches below and run the matching command.
  101. KEY_UP:Starts the instructions for this branch. The indented lines belong together.
  102. _try_move(Vector2i.UP)Calls _try_move with the values in its parentheses.
  103. KEY_LEFT:Starts the instructions for this branch. The indented lines belong together.
  104. _try_move(Vector2i.LEFT)Calls _try_move with the values in its parentheses.
  105. KEY_DOWN:Starts the instructions for this branch. The indented lines belong together.
  106. _try_move(Vector2i.DOWN)Calls _try_move with the values in its parentheses.
  107. KEY_RIGHT:Starts the instructions for this branch. The indented lines belong together.
  108. _try_move(Vector2i.RIGHT)Calls _try_move with the values in its parentheses.
  109. _:Handles every match value that the branches above did not handle.
  110. returnFinishes the function right here. Any later instructions in this function are skipped.
  111. 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 a blocked tap still moves Sol, check that courier = candidate comes after both rejection branches and that each branch has a return at the same indent as its _refresh() call.

Try a change

Ages 10–12: change one bulkhead and test the new route in both directions. Ages 13–16: make one row shorter and explain how checking its own length keeps edge moves safe.