Market Day London · Lesson 13 of 50 · Beginner to intermediate · About 20 min
Nia collects items for market visitors. A single Collect button works at every stall.

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/12 when the lesson builds on prior work, or copy the checkpoints/13 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 Typed Array[String], append(), join(), is_empty(), Reusable button callback.
-
Open the practice scene
Import checkpoints/13/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.
-
Prepare the basket
Find the typed empty array in main.gd. Read the element type between the brackets.
var basket: Array[String] = []Why it works Each slot holds an item key. A typed array tells Godot that every item here is text.
-
Connect the one Collect button
In _ready, find the call that creates Collect. Follow _collect down to its function.
_button("Collect", Vector2(562, 330), 106, _collect)Why it works The button requests a collection action. The rule decides which stall Nia can use.
-
Guard the collection
Find the nearest-stall check. Run once and press Collect before moving.
if item.is_empty():Why it works A stall name comes back only when Nia is beside it. An empty string means no item can be collected.
-
Put the item into the basket
Read the append and turn increment, then move north once and collect Flowers. The refresh line joins the keys for the readout.
basket.append(item)Why it works Appending puts an item after any existing items. Joining lets the label show the whole basket.
-
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
-
Collect at the starting square No adjacent stall.
What you see. The basket stays empty and turns stays 0. -
North, then Collect Nia is beside Flowers.
What you see. The basket contains flowers and turns is 2. -
Collect again The same stall remains beside Nia.
What you see. Two separate flowers entries are visible.
Predict before you run If Nia Collects twice next to Flowers, how many flower entries will this checkpoint show?
Reveal the answer
Two. An array can hold the same item string more than once.
Complete checkpoint
Collecting beside a stall adds its item and spends one turn. The Collect button describes an invalid position with no basket change.
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] = []
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)
_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
basket.append(item)
turns += 1
_say("Added %s to your basket." % item)
func _say(words: String) -> void:
message = words
_refresh()
func _refresh() -> void:
location.text = "Nia at %s" % str(position_cell) + " · Turns: %d" % turns
var stall := _nearest_stall()
display_order.text = "Beside " + NAMES[stall] if not stall.is_empty() else "Walk beside a stall"
basket_readout.text = "Basket: empty" if basket.is_empty() else "Basket: " + ", ".join(basket)
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. -
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. -
_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. -
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 _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. -
var stall := _nearest_stall()Reuse the same reach check the collection action uses. -
display_order.text = "Beside " + NAMES[stall] if not stall.is_empty() else "Walk beside a stall"Look up the nearby stall name only when the search found a real item ID. -
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. -
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 Collect at the start adds a blank slot, check that return is indented beneath the empty-item guard.
Try a change
Collect from all three stalls. Write down the order in which their labels appear in the basket.