Midnight Deck Dash · Lesson 18 of 50 · Beginner to intermediate · About 29 min
The night shift can begin again at the same time with the same deck. Restart reloads the current shift's progress values inside the existing scene.

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

Build it step by step
Language and tools in this lesson reset functions, constants versus variables, Array.clear, button signal connection, reproducible tests, state initialization.
-
Load the lesson checkpoint
Extract the lesson 18 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. Undo and Restart sit at the top of the dispatch panel.
extends ControlWhy it works The scene attaches this script to a Control node. Restart resets game data while keeping the current scene and button connections. Use F8 to stop the running scene before editing.
-
Connect the new button
In _ready, find the Restart button setup next to Undo. Press F5 and check that both controls are visible. Compare the signal connection with a direction button and say why this one needs no direction.
restart_button.pressed.connect(_restart)Why it works _restart takes no argument. pressed can connect straight to it and each tap starts one reset.
-
Return the courier to the starting square
Move Sol to any open square and tap Restart. Compare the old square with START at the top of the script.
courier = START turns = 0Why it works START is the fixed opening square, so assigning it to courier resets the location without replacing the map or setting new button positions.
-
Return both parcels
Collect S and tap Restart. The S circle should appear again at (5, 1). Deliver S, then tap Restart and confirm both pickups are available.
carried_mark = "" delivered.clear()Why it works The pickup data never changes. Clearing carried_mark and the delivered array makes the drawing code show the original pickup circles again.
-
Clear the finish flag and history
Finish both deliveries using the route from lesson 16. Tap Restart, then tap Undo without moving again. Try a Right move afterwards.
shift_finished = false history.clear()Why it works Resetting shift_finished allows a fresh move. Clearing history prevents an Undo from reaching into the previous playthrough.
-
Compare two matching runs
Press Restart and play Right five times, then Down three times. Record all three ledger lines. Restart and repeat the same moves to confirm the result is the same.
_refresh()Why it works A reliable reset gives a testable starting state. Identical legal inputs on this deck should produce the same ending square, delivery count and turn count.
Watch the values change
-
Make any delivery turns and delivered values have changed
What you see. The ledger shows progress from the original shift. -
Tap Restart position, count, carried mark, deliveries and flags reset
What you see. Sol returns to START and both pickup circles appear. -
Tap Undo before moving history was cleared by Restart
What you see. No old move can return. -
Press Right a new snapshot starts the new shift
What you see. The board accepts a fresh step and shows Moves: 1.
Predict before you run Which data can stay unchanged when you restart: DECK_ROWS or delivered?
Reveal the answer
DECK_ROWS stays fixed, because it describes the layout. The delivered array tracks the current run and is cleared.
Complete checkpoint
Restart returns Sol and both parcels to the start, clears the ledger and opens a new Undo history.
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)
const STATIONS: Dictionary = {
"S": Vector2i(5, 3),
"T": Vector2i(6, 4),
}
const STATION_NAMES: Dictionary = {
"S": "Sun Deck",
"T": "Night Theatre",
}
const PICKUPS: Dictionary = {
"S": Vector2i(5, 1),
"T": Vector2i(1, 3),
}
var courier := START
var status := "Use the arrows or tap a direction."
var turns := 0
var carried_mark := ""
var delivered: Array[String] = []
var shift_finished := false
var history: Array[Dictionary] = []
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)
var undo_button := _make_button("Undo", Vector2(535, 130), Vector2(94, 44))
undo_button.pressed.connect(_undo)
var restart_button := _make_button("Restart", Vector2(643, 130), Vector2(100, 44))
restart_button.pressed.connect(_restart)
_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)
for raw_mark in STATIONS.keys():
var mark := str(raw_mark)
var station: Vector2i = STATIONS[mark]
var dock_pixel := BOARD_ORIGIN + Vector2(station) * CELL_SIZE
_draw_marker(font, dock_pixel, mark, true)
for raw_mark in PICKUPS.keys():
var mark := str(raw_mark)
if mark == carried_mark:
continue
if mark in delivered:
continue
var parcel_cell: Vector2i = PICKUPS[mark]
var parcel_pixel := BOARD_ORIGIN + Vector2(parcel_cell) * CELL_SIZE
_draw_marker(font, parcel_pixel, mark, false)
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 _draw_marker(font: Font, pixel: Vector2, mark: String, is_station: bool) -> void:
var centre := pixel + Vector2(29, 29)
var colour := Color("#8be2d1") if mark == "S" else Color("#f2ad98")
if is_station:
draw_rect(Rect2(pixel + Vector2(7, 7), Vector2(44, 44)), colour, false, 3.0)
else:
draw_circle(centre, 19.0, colour)
var ink := colour if is_station else Color("#10242f")
draw_string(font, pixel + Vector2(23, 35), mark, HORIZONTAL_ALIGNMENT_LEFT, -1, 18, ink)
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:
if shift_finished:
status = "The shift is complete."
_refresh()
return
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
history.append(_snapshot())
courier = candidate
turns += 1
status = "Moved to column %d, row %d." % [courier.x + 1, courier.y + 1]
_resolve_landing()
_refresh()
func _resolve_landing() -> void:
if carried_mark != "":
var intended_dock: Vector2i = STATIONS[carried_mark]
if courier == intended_dock:
var delivered_mark := carried_mark
delivered.append(delivered_mark)
carried_mark = ""
status = "%s parcel delivered." % STATION_NAMES[delivered_mark]
if delivered.size() == PICKUPS.size():
shift_finished = true
status = "Shift complete."
return
if courier in STATIONS.values():
status = "Wrong station. Keep this parcel for %s." % STATION_NAMES[carried_mark]
return
for raw_mark in PICKUPS.keys():
var mark := str(raw_mark)
if courier != PICKUPS[mark]:
continue
if mark in delivered:
return
if carried_mark != "":
status = "Hands full. Deliver %s first." % carried_mark
return
carried_mark = mark
status = "Picked up %s for %s." % [mark, STATION_NAMES[mark]]
return
func _snapshot() -> Dictionary:
return {
"courier": courier,
"turns": turns,
"carried": carried_mark,
"delivered": delivered.duplicate(),
"finished": shift_finished,
}
func _undo() -> void:
if history.is_empty():
status = "No move to undo yet."
_refresh()
return
var previous: Dictionary = history.pop_back()
courier = previous["courier"]
turns = previous["turns"]
carried_mark = previous["carried"]
delivered.assign(previous["delivered"])
shift_finished = previous["finished"]
status = "Last legal move reversed."
_refresh()
func _restart() -> void:
courier = START
turns = 0
carried_mark = ""
delivered.clear()
shift_finished = false
history.clear()
status = "New shift. Parcels are ready at their original spots."
_refresh()
func _refresh() -> void:
status_label.text = status
var report := "Moves: %d" % turns
var hands := "empty" if carried_mark == "" else carried_mark
report += "\nCarried parcel: %s" % hands
report += "\nDelivered: %d / %d" % [delivered.size(), PICKUPS.size()]
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
-
extends ControlGive the lesson scene a Control base so it can lay out interface nodes, draw the floor plan and handle player input. -
# 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. -
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. -
".......",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
".##....",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"...#...",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"...#...",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
".......",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
const START := Vector2i(0, 0)Name the opening square. Vector2i stores a pair of whole numbers, with column first and row second. -
const CELL_SIZE := 62Space tile origins 62 drawing pixels apart. This is a screen measurement; Sol's position is still measured in tiles. -
const BOARD_ORIGIN := Vector2(38, 123)Place the top-left board tile at screen pixel (38, 123), below the course banner. -
const STATIONS: Dictionary = {Store each receiving square under its parcel's mark. Reuse this table for the drawing and for delivery checks. -
"S": Vector2i(5, 3),Put the Sun Deck receiver in column 5 and row 3 when counted from zero. -
"T": Vector2i(6, 4),Put the Night Theatre receiver in column 6 and row 4 when counted from zero. -
}Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
const STATION_NAMES: Dictionary = {Look up a full station name using a short parcel mark, so dispatch messages can use words rather than single letters. -
"S": "Sun Deck",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"T": "Night Theatre",Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
}Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
const PICKUPS: Dictionary = {Keep the original location of each parcel in a table keyed by its mark. Restart can show these locations again without rebuilding the table. -
"S": Vector2i(5, 1),Place the Sun Deck parcel on the square (5, 1). Sol must walk to this square to pick it up. -
"T": Vector2i(1, 3),Place the Night Theatre parcel on the square (1, 3). Its receiver is across the deck. -
}Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
var courier := STARTStart Sol on the named starting square. courier is a variable because it will change when a move succeeds. -
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. -
var turns := 0Open the shift with zero accepted moves. Godot infers an integer from the zero. -
var carried_mark := ""Use an empty string to represent empty hands. A one-letter mark replaces it when Sol takes a parcel. -
var delivered: Array[String] = []Start with a typed list of delivered parcel marks. This becomes a history of completed jobs for the shift. -
var shift_finished := falseOpen the shift in the unfinished state so the movement guard lets the player move. -
var history: Array[Dictionary] = []Make an initially empty stack of snapshots. Each accepted move will add one dictionary of pre-move state. -
var status_label: LabelName the on-screen label that will display the latest action feedback after _ready creates it. -
var ledger_label: LabelName the label that will display the current move count, carried parcel, deliveries and rating. -
func _ready() -> void:Godot calls this scene setup method after adding the Control node. Build labels and buttons here once. -
status_label = Label.new()Stores the new value in status_label. The expression creates a new Label object. -
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. -
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. -
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. -
status_label.add_theme_color_override("font_color", Color("#ffea9f"))Calls status_label.add_theme_color_override with the values in its parentheses. -
status_label.add_theme_font_size_override("font_size", 17)Calls status_label.add_theme_font_size_override with the values in its parentheses. -
add_child(status_label)Add the feedback label to the running scene so Godot can show it on screen. -
ledger_label = Label.new()Stores the new value in ledger_label. The expression creates a new Label object. -
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. -
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. -
ledger_label.add_theme_color_override("font_color", Color("#e3f5f5"))Calls ledger_label.add_theme_color_override with the values in its parentheses. -
ledger_label.add_theme_font_size_override("font_size", 16)Calls ledger_label.add_theme_font_size_override with the values in its parentheses. -
add_child(ledger_label)Add the ledger to the Control scene so players can read the latest course state. -
_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. -
_connect_direction("Left", Vector2(583, 430), Vector2i.LEFT)Create a Left button that sends one tile west to the shared move function. -
_connect_direction("Down", Vector2(675, 430), Vector2i.DOWN)Create a Down button that sends one tile south to the shared move function. -
_connect_direction("Right", Vector2(767, 430), Vector2i.RIGHT)Create a Right button that sends one tile east to the shared move function. -
var undo_button := _make_button("Undo", Vector2(535, 130), Vector2(94, 44))Creates a variable named undo_button. The expression calls _make_button with the values in its parentheses. Godot infers the type from the first value. -
undo_button.pressed.connect(_undo)Connect the button's pressed event directly to _undo because that function does not need a direction. -
var restart_button := _make_button("Restart", Vector2(643, 130), Vector2(100, 44))Creates a variable named restart_button. The expression calls _make_button with the values in its parentheses. Godot infers the type from the first value. -
restart_button.pressed.connect(_restart)Connect Restart directly to the function that resets this deck's gameplay state. -
_refresh()Calls _refresh with the values in its parentheses. -
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. -
var button := Button.new()Creates a variable named button. The expression creates a new Button object. Godot infers the type from the first value. -
button.text = captionUpdates button.text, which controls the words a player sees. The expression reads caption. -
button.position = pixelUpdates button.position, which controls the node's local x and y location. The expression reads pixel. -
button.size = dimensionsUpdates button.size, which controls the control's width and height. The expression reads dimensions. -
button.add_theme_font_size_override("font_size", 16)Calls button.add_theme_font_size_override with the values in its parentheses. -
add_child(button)Adds the new node to the scene tree so that Godot can run and draw it. -
return buttonFinishes the function and hands its result back to the caller. The expression reads button. -
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. -
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. -
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. -
func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state. -
draw_rect(Rect2(Vector2.ZERO, size), Color("#081f31"))Paints a rectangle at the given position and size. -
draw_rect(Rect2(24, 96, 469, 373), Color("#183b4d"))Paints a rectangle at the given position and size. -
draw_rect(Rect2(513, 96, 421, 405), Color("#14374d"))Paints a rectangle at the given position and size. -
var font := ThemeDB.fallback_fontCreates a variable named font. The expression reads ThemeDB.fallback_font. Godot infers the type from the first value. -
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. -
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. -
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. -
for y in range(DECK_ROWS.size()):Draw one row for each index from 0 to the row count minus one. -
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. -
var cell := Vector2i(x, y)Bundle the current column and row into a game square. -
var pixel := BOARD_ORIGIN + Vector2(cell) * CELL_SIZEMultiply the tile address by the spacing, then add the screen offset to get its drawing location. -
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. -
var colour := Color("#22424a") if blocked else Color("#4a6c61")Pick one paint colour for a bulkhead and another for a hallway after reading blocked. -
draw_rect(Rect2(pixel, Vector2(59, 59)), colour)Paints a rectangle at the given position and size. -
if blocked:Checks blocked. The indented instructions below run only if this test passes. -
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. -
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. -
for raw_mark in STATIONS.keys():Repeats the indented instructions for each value in STATIONS.keys(). -
var mark := str(raw_mark)Creates a variable named mark. The expression turns a value into text for a player message. Godot infers the type from the first value. -
var station: Vector2i = STATIONS[mark]Look up the current dock's square by the shared station mark before drawing its outlined marker. -
var dock_pixel := BOARD_ORIGIN + Vector2(station) * CELL_SIZECreates a variable named dock_pixel. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value. -
_draw_marker(font, dock_pixel, mark, true)Calls _draw_marker with the values in its parentheses. -
for raw_mark in PICKUPS.keys():Repeats the indented instructions for each value in PICKUPS.keys(). -
var mark := str(raw_mark)Creates a variable named mark. The expression turns a value into text for a player message. Godot infers the type from the first value. -
if mark == carried_mark:Skip drawing the pickup circle if Sol already has this parcel in hand. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
if mark in delivered:Check the completed list for this letter. The next instruction prevents the finished parcel appearing as an available pickup. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
var parcel_cell: Vector2i = PICKUPS[mark]Read this parcel's original square. It can be drawn at this location whenever it is unclaimed. -
var parcel_pixel := BOARD_ORIGIN + Vector2(parcel_cell) * CELL_SIZECreates a variable named parcel_pixel. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value. -
_draw_marker(font, parcel_pixel, mark, false)Calls _draw_marker with the values in its parentheses. -
var courier_pixel := BOARD_ORIGIN + Vector2(courier) * CELL_SIZEMove the courier's drawn symbol to the pixel origin of its current game square. -
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. -
draw_circle(courier_center, 20.0, Color("#122734"))Paints a filled circle or outline in this node's local coordinates. -
draw_circle(courier_center, 16.0, Color("#fff0b5"))Paints a filled circle or outline in this node's local coordinates. -
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. -
func _draw_marker(font: Font, pixel: Vector2, mark: String, is_station: bool) -> void:Defines draw marker, 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. -
var centre := pixel + Vector2(29, 29)Creates a variable named centre. The expression calculates a new value from the expressions on either side of the operator. Godot infers the type from the first value. -
var colour := Color("#8be2d1") if mark == "S" else Color("#f2ad98")Creates a variable named colour. The expression builds a colour from these values. Godot infers the type from the first value. -
if is_station:Draw an outlined square for a station. The else branch paints a solid circle for a pickup, so shape identifies the marker's job. -
draw_rect(Rect2(pixel + Vector2(7, 7), Vector2(44, 44)), colour, false, 3.0)Paints a rectangle at the given position and size. -
else:Runs the indented fallback instructions if none of the earlier tests passed. -
draw_circle(centre, 19.0, colour)Paints a filled circle or outline in this node's local coordinates. -
var ink := colour if is_station else Color("#10242f")Creates a variable named ink. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value. -
draw_string(font, pixel + Vector2(23, 35), mark, HORIZONTAL_ALIGNMENT_LEFT, -1, 18, ink)Paints a piece of text with a font at a position measured from the node's origin. -
func _inside(cell: Vector2i) -> bool:Return true only for a tile address that exists in the floor plan. -
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. -
return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false. -
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. -
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. -
return DECK_ROWS[cell.y][cell.x]Use the row first and the column second to retrieve one tile character. -
func _try_move(delta: Vector2i) -> void:Use one movement rule for both input methods. delta is the proposed step. -
if shift_finished:Stop a completed shift before it can change its location, turns or cargo. -
status = "The shift is complete."Stores the new value in status. The expression uses the text inside the quotes. -
_refresh()Calls _refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var candidate := courier + deltaCalculate the possible next square. Hold it in a temporary variable until both movement guards approve. -
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. -
status = "That is outside the deck."Stores the new value in status. The expression uses the text inside the quotes. -
_refresh()Calls _refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if _tile_at(candidate) == "#":Once you know the address exists, read its character. A # is a bulkhead and blocks this step. -
status = "A bulkhead blocks that square."Stores the new value in status. The expression uses the text inside the quotes. -
_refresh()Calls _refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
history.append(_snapshot())Push the current state onto Undo history after validating movement and before any legal move can change state. -
courier = candidateCommit the checked move by replacing Sol's current square with the candidate. -
turns += 1Add one and store it back in turns. Only legal moves reach this line. -
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. -
_resolve_landing()Now that Sol has entered the square, check whether a parcel can be delivered or picked up. -
_refresh()Calls _refresh with the values in its parentheses. -
func _resolve_landing() -> void:Apply parcel rules using the current square and hand state. The movement guards have already approved this landing. -
if carried_mark != "":Check for a parcel in hand. The next branch determines whether the game should deliver it or block another pickup. -
var intended_dock: Vector2i = STATIONS[carried_mark]Use the parcel mark in Sol's hands to find its one matching receiving square. -
if courier == intended_dock:Deliver only when Sol's current tile equals the correct recipient tile for the carried parcel. -
var delivered_mark := carried_markMake a local copy of the mark before changing Sol's hands. The copy can still be used to record and name the delivery. -
delivered.append(delivered_mark)Add the delivered parcel's mark to the finished list so the same parcel cannot be taken again. -
carried_mark = ""Empty Sol's hands. The next parcel pickup can now succeed. -
status = "%s parcel delivered." % STATION_NAMES[delivered_mark]Stores the new value in status. The expression uses the text inside the quotes. -
if delivered.size() == PICKUPS.size():Ask whether the count of finished marks equals the number of parcel definitions on this deck. -
shift_finished = trueSet the finished flag after the last parcel arrives. The next move attempt will return at the top of the rule. -
status = "Shift complete."Stores the new value in status. The expression uses the text inside the quotes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if courier in STATIONS.values():If Sol is at a station after missing the intended-square test, it must be a different receiver. Keep the parcel and show the destination name. -
status = "Wrong station. Keep this parcel for %s." % STATION_NAMES[carried_mark]Stores the new value in status. The expression uses the text inside the quotes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
for raw_mark in PICKUPS.keys():Repeats the indented instructions for each value in PICKUPS.keys(). -
var mark := str(raw_mark)Creates a variable named mark. The expression turns a value into text for a player message. Godot infers the type from the first value. -
if courier != PICKUPS[mark]:Skip this job when its pickup square is different from Sol's current square. The loop will check other marks. -
continueSkips the rest of this turn through the loop and moves on to the next item. -
if mark in delivered:Check the completed list for this letter. The next instruction prevents the finished parcel appearing as an available pickup. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if carried_mark != "":Check for a parcel in hand. The next branch determines whether the game should deliver it or block another pickup. -
status = "Hands full. Deliver %s first." % carried_markStores the new value in status. The expression uses the text inside the quotes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
carried_mark = markPick up the matching parcel. The drawing loop will hide its circle while Sol holds it. -
status = "Picked up %s for %s." % [mark, STATION_NAMES[mark]]Stores the new value in status. The expression uses the text inside the quotes. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
func _snapshot() -> Dictionary:Package the values needed to undo a turn under separate dictionary keys. -
return {Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key. -
"courier": courier,Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"turns": turns,Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"carried": carried_mark,Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
"delivered": delivered.duplicate(),Copy the delivered list so changes to the live list cannot alter this earlier snapshot. -
"finished": shift_finished,Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
}Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next. -
func _undo() -> void:Defines undo, 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. -
if history.is_empty():Avoid popping from an empty stack. With no accepted moves there is no earlier gameplay state to restore. -
status = "No move to undo yet."Stores the new value in status. The expression uses the text inside the quotes. -
_refresh()Calls _refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var previous: Dictionary = history.pop_back()Remove the most recently saved state and give it to the local variable previous. -
courier = previous["courier"]Move Sol back to the prior square recorded in the snapshot. -
turns = previous["turns"]Restore the move count from before the undone action. -
carried_mark = previous["carried"]Restore the old parcel mark, which can be empty or a cargo letter. -
delivered.assign(previous["delivered"])Copy the saved list's contents into the live typed list of delivered marks. -
shift_finished = previous["finished"]Restore the finish flag. Undoing the last delivery reopens the shift. -
status = "Last legal move reversed."Stores the new value in status. The expression uses the text inside the quotes. -
_refresh()Calls _refresh with the values in its parentheses. -
func _restart() -> void:Reset every changing field inside the current scene. The buttons and floor plan are reused. -
courier = STARTReturn Sol to the named opening tile. -
turns = 0Start the route count again from zero. -
carried_mark = ""Empty Sol's hands. The next parcel pickup can now succeed. -
delivered.clear()Remove all finished marks so each pickup can show at its original position. -
shift_finished = falseStores the new value in shift_finished. The expression uses the yes-or-no value false. -
history.clear()Discard snapshots from the old shift so Undo cannot cross a restart. -
status = "New shift. Parcels are ready at their original spots."Stores the new value in status. The expression uses the text inside the quotes. -
_refresh()Calls _refresh with the values in its parentheses. -
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. -
status_label.text = statusCopy the latest feedback text into the visible label. -
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. -
var hands := "empty" if carried_mark == "" else carried_markTranslate the empty-string data into a readable word; otherwise show the parcel letter. -
report += "\nCarried parcel: %s" % handsReads report, adds to its old value, then stores the result back in the same place. -
report += "\nDelivered: %d / %d" % [delivered.size(), PICKUPS.size()]Reads report, adds to its old value, then stores the result back in the same place. -
ledger_label.text = reportPresent the current dispatch report in the visible ledger label. -
queue_redraw()Ask Godot to run _draw again using the new game state. -
func _input(event: InputEvent) -> void:Receive input events from Godot and translate recognised keyboard actions into the same rules the touch buttons call. -
if not event is InputEventKey:Pass on non-keyboard input. On-screen Button nodes handle touch presses through their own pressed signals. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var key := event as InputEventKeyTreat the checked event as a keyboard event so its pressed, echo and keycode data are available. -
if not key.pressed or key.echo:Ignore key releases and automatic repeats. A distinct press therefore asks for one move. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
match key.keycode:Compare the key code against the branches below and run the matching command. -
KEY_UP:Starts the instructions for this branch. The indented lines belong together. -
_try_move(Vector2i.UP)Calls _try_move with the values in its parentheses. -
KEY_LEFT:Starts the instructions for this branch. The indented lines belong together. -
_try_move(Vector2i.LEFT)Calls _try_move with the values in its parentheses. -
KEY_DOWN:Starts the instructions for this branch. The indented lines belong together. -
_try_move(Vector2i.DOWN)Calls _try_move with the values in its parentheses. -
KEY_RIGHT:Starts the instructions for this branch. The indented lines belong together. -
_try_move(Vector2i.RIGHT)Calls _try_move with the values in its parentheses. -
_:Handles every match value that the branches above did not handle. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
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 Undo brings back a delivery after you restart, add history.clear() to _restart beside the other reset instructions and test Undo before the first new move.
Try a change
Ages 10–12: test Restart while carrying a parcel and after a delivery. Ages 13–16: make a table of initial settings and reset values and verify that every mutable field in the table agrees.