Market Day London · Lesson 16 of 50 · Beginner to intermediate · About 23 min
The collection helper checks bags at the purple counter. Checking a bag is quick and does not spend a turn.

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/15 when the lesson builds on prior work, or copy the checkpoints/16 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 Sequential guards, Read-only comparison, Function call, Status feedback, Order indexing.
-
Open the practice scene
Import checkpoints/16/project.godot in the Godot Project Manager. In the Scene dock select the root Control and click its script icon. Open main.gd in the Script workspace.
Why it works The complete checkpoint already contains the work for the lesson. Keep a spare copy before changing the script.
-
Connect Check order
Find Check order in _ready and see what function the button calls.
_button("Check order", Vector2(678, 330), 162, _check_order)Why it works Giving this check a separate action makes it clear no basket operation needs to happen.
-
Check the counter location first
Follow _check_order. Reuse _adjacent with COUNTER and report when Nia is too far.
if not _adjacent(position_cell, COUNTER):Why it works It uses the same single-step rule as every stall, including diagonal refusal.
-
Check the bundle next
Read _matches(ORDERS[0]) in the next guard. Try the counter with an empty basket.
if not _matches(ORDERS[0]):Why it works The ticket is read for validation. Nothing is taken away while we check.
-
Keep it read-only
Try a correctly filled basket at Collection and compare the state before and after clicking Check order.
_say("Bundle ready for Collection. The check used no turns.")Why it works This message tells the player the order is ready and leaves inventory and turns intact.
-
Run it and confirm the trace
Press F5, then replay the three checks below in order. Restart the game window between independent trials if needed. In the bottom panel, inspect Output or Debugger if something looks wrong.
Why it works Use visible position, basket contents and turn totals to test the rule.
Watch the values change
-
Check near Flowers Nia is not beside Collection.
What you see. Get a location instruction and no change in turns. -
Check an incomplete basket beside Collection Item comparison fails.
What you see. Get the exact items required. -
Check apple and bread beside Collection Both guards pass.
What you see. Read Bundle ready. Basket and turns are unchanged.
Predict before you run What should change after tapping Check order with a correct basket?
Reveal the answer
Only the status message. A check neither delivers goods nor spends a turn.
Complete checkpoint
Check order reports the first reason it cannot pass, or says the bundle is ready. No check changes the basket or turn count.
main.gd
extends Control
const MAP_SIZE := Vector2i(7, 5)
const START := Vector2i(3, 3)
const COUNTER := Vector2i(6, 3)
const STALLS := {"apple": Vector2i(1, 1), "flowers": Vector2i(3, 1), "bread": Vector2i(5, 1)}
const NAMES := {"apple": "Apples", "flowers": "Flowers", "bread": "Bread"}
const MARKS := {"apple": "A", "flowers": "F", "bread": "B"}
const INK := Color("#162d35")
const SLATE := Color("#254853")
const PAPER := Color("#fff2d6")
const MINT := Color("#a4e5b7")
const AMBER := Color("#ffd68a")
var position_cell := START
var location: Label
var display_order: Label
var report: Label
var basket_readout: Label
var message := "Move beside a stall to look at its goods."
var turns := 0
var basket: Array[String] = []
const CAPACITY := 3
const ORDERS = [["apple", "bread"], ["flowers", "flowers", "apple"]]
func _ready() -> void:
_label("MARKET DAY LONDON", Vector2(28, 21), Vector2(710, 37), 33)
_label("BRIAR LANE · NIA’S TRAINING SHIFT", Vector2(31, 62), Vector2(680, 24), 16)
_label("STALL MAP", Vector2(49, 112), Vector2(440, 26), 17)
_label("A Apples F Flowers B Bread C Collection", Vector2(49, 458), Vector2(492, 27), 15)
location = _label("", Vector2(562, 115), Vector2(355, 28), 19)
_button("North", Vector2(678, 154), 106, _move.bind(Vector2i.UP))
_button("West", Vector2(562, 201), 106, _move.bind(Vector2i.LEFT))
_button("South", Vector2(678, 201), 106, _move.bind(Vector2i.DOWN))
_button("East", Vector2(794, 201), 106, _move.bind(Vector2i.RIGHT))
display_order = _label("", Vector2(562, 253), Vector2(355, 29), 16)
basket_readout = _label("", Vector2(562, 294), Vector2(355, 29), 16)
report = _label("", Vector2(562, 424), Vector2(353, 74), 17)
report.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_button("Collect", Vector2(562, 330), 106, _collect)
_button("Check order", Vector2(678, 330), 162, _check_order)
_refresh()
func _label(words: String, point: Vector2, extent: Vector2, font_size: int) -> Label:
var label := Label.new()
label.text = words
label.position = point
label.size = extent
label.add_theme_font_size_override("font_size", font_size)
label.modulate = PAPER
add_child(label)
return label
func _button(words: String, point: Vector2, width: int, action: Callable) -> void:
var button := Button.new()
button.text = words
button.position = point
button.custom_minimum_size = Vector2(width, 44)
button.pressed.connect(action)
add_child(button)
func _unhandled_key_input(event: InputEvent) -> void:
if event.is_action_pressed("ui_up"):
_move(Vector2i.UP)
elif event.is_action_pressed("ui_down"):
_move(Vector2i.DOWN)
elif event.is_action_pressed("ui_left"):
_move(Vector2i.LEFT)
elif event.is_action_pressed("ui_right"):
_move(Vector2i.RIGHT)
func _adjacent(a: Vector2i, b: Vector2i) -> bool:
var offset := a - b
return absi(offset.x) + absi(offset.y) == 1
func _nearest_stall() -> String:
for item: String in STALLS:
if _adjacent(position_cell, STALLS[item]):
return item
return ""
func _move(step: Vector2i) -> void:
var candidate := position_cell + step
if not Rect2i(Vector2i.ZERO, MAP_SIZE).has_point(candidate):
_say("Briar Lane ends here.")
return
if candidate in STALLS.values() or candidate == COUNTER:
_say("Stand beside the counter or stall to use it.")
return
position_cell = candidate
turns += 1
_say("Nia stepped to %s." % str(position_cell))
func _collect() -> void:
var item := _nearest_stall()
if item.is_empty():
_say("Move one square beside a stall first.")
return
if basket.size() >= CAPACITY:
_say("The three basket spaces are full.")
return
basket.append(item)
turns += 1
_say("Added %s to your basket." % item)
func _matches(required: Array) -> bool:
var packed: Array[String] = basket.duplicate()
var requested := required.duplicate()
packed.sort()
requested.sort()
return packed == requested
func _check_order() -> void:
if not _adjacent(position_cell, COUNTER):
_say("Stand one square beside Collection.")
return
if not _matches(ORDERS[0]):
_say("This bundle needs exactly an apple and bread.")
return
_say("Bundle ready for Collection. The check used no turns.")
func _say(words: String) -> void:
message = words
_refresh()
func _refresh() -> void:
location.text = "Nia at %s" % str(position_cell) + " · Turns: %d" % turns
display_order.text = "Request: apple + bread"
basket_readout.text = "Basket: empty" if basket.is_empty() else "Basket: " + ", ".join(basket)
basket_readout.text += " %d/%d" % [basket.size(), CAPACITY]
report.text = message
queue_redraw()
func _tile_rect(cell: Vector2i) -> Rect2:
return Rect2(Vector2(52, 149) + Vector2(cell) * Vector2(65, 56), Vector2(59, 50))
func _draw_mark(mark: String, box: Rect2, ink: Color, font_size: int) -> void:
var typeface := ThemeDB.fallback_font
var width := typeface.get_string_size(mark, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x
draw_string(typeface, box.get_center() + Vector2(-width / 2.0, 6.0), mark, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, ink)
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), INK)
draw_rect(Rect2(30, 95, 491, 410), SLATE)
draw_rect(Rect2(545, 95, 385, 410), SLATE)
for y in range(MAP_SIZE.y):
for x in range(MAP_SIZE.x):
draw_rect(_tile_rect(Vector2i(x, y)), Color("#55706d"))
var nearby := _nearest_stall()
for item: String in STALLS:
var box := _tile_rect(STALLS[item])
draw_rect(box, AMBER if item == nearby else Color("#a16655"))
_draw_mark(MARKS[item], box, INK if item == nearby else PAPER, 24)
var counter_box := _tile_rect(COUNTER)
draw_rect(counter_box, AMBER if _adjacent(position_cell, COUNTER) else Color("#725991"))
_draw_mark("C", counter_box, INK if _adjacent(position_cell, COUNTER) else PAPER, 24)
var here := _tile_rect(position_cell)
draw_circle(here.get_center(), 18, MINT)
_draw_mark("N", here, INK, 19)
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 ControlUse a Control at the root so the scene can draw the street and host the interface labels and buttons. -
const MAP_SIZE := Vector2i(7, 5)Set seven columns and five rows. They are numbered 0–6 and 0–4 because the first index is zero. -
const START := Vector2i(3, 3)Nia starts in column 3, row 3 on each new shift. -
const COUNTER := Vector2i(6, 3)Place Collection at the east end. The training rule asks Nia to stand one step from this square. -
const STALLS := {"apple": Vector2i(1, 1), "flowers": Vector2i(3, 1), "bread": Vector2i(5, 1)}The dictionary connects each item ID to a stall position. Keep the IDs consistent across the order and basket. -
const NAMES := {"apple": "Apples", "flowers": "Flowers", "bread": "Bread"}Give the player a familiar stall name for each item ID. -
const MARKS := {"apple": "A", "flowers": "F", "bread": "B"}Give each stall a short map mark. The legend also spells the names out. -
const INK := Color("#162d35")Use a deep blue-green behind the map and for text on light markers. -
const SLATE := Color("#254853")Use a lighter blue-green for the two interface panels. -
const PAPER := Color("#fff2d6")Use cream for interface text and markers on dark squares. -
const MINT := Color("#a4e5b7")Use mint for Nia’s round marker so it stands apart from the market objects. -
const AMBER := Color("#ffd68a")Use amber to signal an object that can be reached from the current square. -
var position_cell := STARTKeep Nia’s live game position as a pair of whole square numbers. -
var location: LabelKeep a reference to the status label so a later refresh can update it. -
var display_order: LabelKeep a reference for the current ticket or nearby-stall description. -
var report: LabelKeep a reference for the last action’s message. -
var basket_readout: LabelKeep a reference for the text showing the basket contents. -
var message := "Move beside a stall to look at its goods."Set a starting message that gives the player an action to try. -
var turns := 0Count only accepted actions. A newly opened shift starts at zero. -
var basket: Array[String] = []The basket starts as an empty array of strings. Each entry represents one individual item. -
const CAPACITY := 3Keep the three-slot design rule in one place so collection and the interface agree. -
const ORDERS = [["apple", "bread"], ["flowers", "flowers", "apple"]]An array holds both tickets. Each inner array lists every unit requested. The second ticket contains two separate flower entries. -
func _ready() -> void:Godot calls this once when the scene is ready. Here it builds the interface and shows the first state. -
_label("MARKET DAY LONDON", Vector2(28, 21), Vector2(710, 37), 33)Place the game title above both panels. -
_label("BRIAR LANE · NIA’S TRAINING SHIFT", Vector2(31, 62), Vector2(680, 24), 16)Give the practice map a place and tell the player whose shift it is. -
_label("STALL MAP", Vector2(49, 112), Vector2(440, 26), 17)Label the left panel above the first row of paving. -
_label("A Apples F Flowers B Bread C Collection", Vector2(49, 458), Vector2(492, 27), 15)Print the full names behind the four one-letter map marks. -
location = _label("", Vector2(562, 115), Vector2(355, 28), 19)Create an initially empty label. The first refresh fills it with Nia’s position. -
_button("North", Vector2(678, 154), 106, _move.bind(Vector2i.UP))Attach the North button to the common movement rule with an upward step attached. -
_button("West", Vector2(562, 201), 106, _move.bind(Vector2i.LEFT))Attach the West button to the common movement rule with a leftward step attached. -
_button("South", Vector2(678, 201), 106, _move.bind(Vector2i.DOWN))Attach the South button to the common movement rule with a downward step attached. -
_button("East", Vector2(794, 201), 106, _move.bind(Vector2i.RIGHT))Attach the East button to the common movement rule with a rightward step attached. -
display_order = _label("", Vector2(562, 253), Vector2(355, 29), 16)Create the label that will hold the active request. -
basket_readout = _label("", Vector2(562, 294), Vector2(355, 29), 16)Give the basket a display area of its own. -
report = _label("", Vector2(562, 424), Vector2(353, 74), 17)Give action messages extra height so feedback can take a second line. -
report.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTBreak feedback at word boundaries when it reaches the end of the panel. -
_button("Collect", Vector2(562, 330), 106, _collect)Give the press signal the same collection function for every stall. -
_button("Check order", Vector2(678, 330), 162, _check_order)Ask the validation function to respond without delivering or spending a turn. -
_refresh()Populate the empty labels and request a map drawing right after setup. -
func _label(words: String, point: Vector2, extent: Vector2, font_size: int) -> Label:Group repeated interface setup in a function that returns the new label to its caller. -
var label := Label.new()Construct a label node. It becomes part of the scene after add_child. -
label.text = wordsDisplay the words supplied by the caller. -
label.position = pointUse the supplied top-left pixel point within the scene. -
label.size = extentSet the width and height of this particular label. -
label.add_theme_font_size_override("font_size", font_size)Set the font size of this label without editing the project-wide theme. -
label.modulate = PAPERTint this label cream for a strong contrast against the panel. -
add_child(label)Attach the new label to the running scene so it can be drawn. -
return labelReturn the same label node for any future changes to its text. -
func _button(words: String, point: Vector2, width: int, action: Callable) -> void:Set up each button using its label, position, width and function to call. -
var button := Button.new()Make a native button so Godot handles focus and input. -
button.text = wordsGive the player a readable action name. -
button.position = pointPlace the button’s top-left corner in the training interface. -
button.custom_minimum_size = Vector2(width, 44)Reserve enough width for the caption and at least 44 drawing pixels for its height. -
button.pressed.connect(action)When this button emits pressed, run the function passed in as action. -
add_child(button)Attach the button to the scene so it can be seen and activated. -
func _unhandled_key_input(event: InputEvent) -> void:Let Godot offer keys to the interface first, then check any remaining key event for movement. -
if event.is_action_pressed("ui_up"):Recognize the keyboard’s Up action. -
_move(Vector2i.UP)Try a step of zero columns and minus one row. -
elif event.is_action_pressed("ui_down"):If Up did not match, test for Down. -
_move(Vector2i.DOWN)Try a step of zero columns and plus one row. -
elif event.is_action_pressed("ui_left"):If neither vertical action matched, test for Left. -
_move(Vector2i.LEFT)Try a step of minus one column and zero rows. -
elif event.is_action_pressed("ui_right"):If none of the earlier directions matched, test for Right. -
_move(Vector2i.RIGHT)Try a step of plus one column and zero rows. -
func _adjacent(a: Vector2i, b: Vector2i) -> bool:Answer a yes-or-no question about whether two cells share one side. -
var offset := a - bFind the horizontal and vertical distance with direction still attached. -
return absi(offset.x) + absi(offset.y) == 1Use absolute values to remove the signs. Return true only for a single sideways or vertical step. -
func _nearest_stall() -> String:Return the item ID of the first side-by-side stall. Return an empty string when no stall is reachable. -
for item: String in STALLS:Try the stall IDs in the declared order. If two are beside Nia, the first one wins. -
if _adjacent(position_cell, STALLS[item]):Fetch the stall position by its item ID, then apply the shared one-step rule. -
return itemFinish the search as soon as one permitted stall is found. -
return ""Use an empty string to signal that the search found no nearby item. -
func _move(step: Vector2i) -> void:Use the same rule for touch and keyboard movement. -
var candidate := position_cell + stepCalculate a proposed cell before changing Nia’s real position. -
if not Rect2i(Vector2i.ZERO, MAP_SIZE).has_point(candidate):Reject coordinates outside the rectangle of legal cells. Its far edges are excluded. -
_say("Briar Lane ends here.")Give the player the reason this action was refused, while leaving the market state unchanged. -
returnLeave the function here so the later action does not run. -
if candidate in STALLS.values() or candidate == COUNTER:Reject a square occupied by a stall or Collection so Nia uses it from the walkway. -
_say("Stand beside the counter or stall to use it.")Show the outcome in the feedback label and redraw using the live state. -
returnLeave the function here so the later action does not run. -
position_cell = candidateCommit the proposed cell only after both guards pass. -
turns += 1Spend one turn after a legal move is committed. -
_say("Nia stepped to %s." % str(position_cell))Show the outcome in the feedback label and redraw using the live state. -
func _collect() -> void:Try to put an item from a reachable stall into an open basket space. -
var item := _nearest_stall()Ask for the reachable stall’s item ID before touching the basket. -
if item.is_empty():Refuse collection when no stall is at a legal distance. -
_say("Move one square beside a stall first.")Give the player the reason this action was refused, while leaving the market state unchanged. -
returnLeave the function here so the later action does not run. -
if basket.size() >= CAPACITY:Refuse a fourth item while preserving all three existing entries. -
_say("The three basket spaces are full.")Give the player the reason this action was refused, while leaving the market state unchanged. -
returnLeave the function here so the later action does not run. -
basket.append(item)Put the selected item at the end of the live basket array. -
turns += 1Spend one turn for the successful pickup only. -
_say("Added %s to your basket." % item)Show the outcome in the feedback label and redraw using the live state. -
func _matches(required: Array) -> bool:Answer whether the basket and ticket have exactly the same items and counts. -
var packed: Array[String] = basket.duplicate()Copy the basket so sorting can leave the live pickup order alone. -
var requested := required.duplicate()Copy the required items so sorting can also preserve the original ticket text. -
packed.sort()Put the copied basket’s strings in a predictable order. -
requested.sort()Apply the same sort to the ticket copy. -
return packed == requestedCompare every entry in the sorted arrays. Missing, extra and wrong items all fail. -
func _check_order() -> void:Give feedback about the location and bundle without recording a handover. -
if not _adjacent(position_cell, COUNTER):Require one side-step of distance from Collection before comparing the order. -
_say("Stand one square beside Collection.")Give the player the reason this action was refused, while leaving the market state unchanged. -
returnLeave the function here so the later action does not run. -
if not _matches(ORDERS[0]):Verify the first request at index zero, apple plus bread. -
_say("This bundle needs exactly an apple and bread.")Show the outcome in the feedback label and redraw using the live state. -
returnLeave the function here so the later action does not run. -
_say("Bundle ready for Collection. The check used no turns.")Show the outcome in the feedback label and redraw using the live state. -
func _say(words: String) -> void:Send all action feedback through one function so the labels and map stay in sync. -
message = wordsOverwrite the stored player message with the current result. -
_refresh()Give feedback, labels and redraw one shared point of update. -
func _refresh() -> void:Turn the current game state into interface text and request a new drawing of the map. -
location.text = "Nia at %s" % str(position_cell) + " · Turns: %d" % turnsConvert the coordinate pair to text and display the live location. -
display_order.text = "Request: apple + bread"Keep both requested items visible during the check exercise. -
basket_readout.text = "Basket: empty" if basket.is_empty() else "Basket: " + ", ".join(basket)Say the basket is empty or join its item names with commas. -
basket_readout.text += " %d/%d" % [basket.size(), CAPACITY]Add the occupied-space count and the three-space limit to the display. -
report.text = messagePut the last result where the player can read it. -
queue_redraw()Request a fresh map so changes to Nia and nearby objects appear in the next frame. -
func _tile_rect(cell: Vector2i) -> Rect2:Convert a square in grid coordinates to the pixel rectangle used for drawing. -
return Rect2(Vector2(52, 149) + Vector2(cell) * Vector2(65, 56), Vector2(59, 50))Add the indexed spacing to the top-left map origin. The slightly smaller tile size leaves gaps. -
func _draw_mark(mark: String, box: Rect2, ink: Color, font_size: int) -> void:Draw one centered letter as a short label inside a square or token. -
var typeface := ThemeDB.fallback_fontUse Godot’s fallback font so the exercise runs without extra files. -
var width := typeface.get_string_size(mark, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).xMeasure the current letter in pixels for centering. -
draw_string(typeface, box.get_center() + Vector2(-width / 2.0, 6.0), mark, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, ink)Start half the measured width left of center and use a small vertical baseline offset. -
func _draw() -> void:Godot calls this to render the board when the scene first shows and after each redraw request. -
draw_rect(Rect2(Vector2.ZERO, size), INK)Paint the scene background across the root Control’s current dimensions. -
draw_rect(Rect2(30, 95, 491, 410), SLATE)Paint a panel behind the map and legend. -
draw_rect(Rect2(545, 95, 385, 410), SLATE)Paint a panel behind the movement buttons and live information. -
for y in range(MAP_SIZE.y):Loop over the five legal rows, starting with row zero. -
for x in range(MAP_SIZE.x):In each row, loop through the seven legal columns. -
draw_rect(_tile_rect(Vector2i(x, y)), Color("#55706d"))Draw a paving square at this column and row. -
var nearby := _nearest_stall()Find the stall that is in reach according to the same rule used by Collect. -
for item: String in STALLS:Draw each of the three stalls in the position assigned to its item ID. -
var box := _tile_rect(STALLS[item])Convert this stall cell to a pixel rectangle before drawing it. -
draw_rect(box, AMBER if item == nearby else Color("#a16655"))Use amber for the available stall. Use muted clay for a stall out of reach. -
_draw_mark(MARKS[item], box, INK if item == nearby else PAPER, 24)Draw the stall’s letter using an ink colour that stays readable on the fill. -
var counter_box := _tile_rect(COUNTER)Find the screen rectangle of the Collection cell. -
draw_rect(counter_box, AMBER if _adjacent(position_cell, COUNTER) else Color("#725991"))Highlight Collection if Nia is beside it. Use purple while it is out of reach. -
_draw_mark("C", counter_box, INK if _adjacent(position_cell, COUNTER) else PAPER, 24)Label Collection with its map letter. -
var here := _tile_rect(position_cell)Find the rectangle that contains Nia’s live cell. -
draw_circle(here.get_center(), 18, MINT)Draw the mint token in the center of the live cell. -
_draw_mark("N", here, INK, 19)Print Nia’s initial in her movement marker.
Find and fix a bug
If Check order advances the clock or empties the basket, remove the stock and turn mutations from this read-only function.
Try a change
Find a diagonal square near Collection, predict refusal, then step to an actual neighbour and retry.