Market Day London · Lesson 12 of 50 · Beginner to intermediate · About 19 min
The market is busy. Nia should never walk through a stall, and a refused step should not put a mark on the shift clock.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/11 when the lesson builds on prior work, or copy the checkpoints/12 folder to try this lesson on its own. Read the file names in the steps before editing.


Build it step by step
Language and tools in this lesson Guard clauses, Rect2i.has_point(), Dictionary values, in, return, +=.
-
Open the practice scene
Import checkpoints/12/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.
-
Reserve a counter
Find the turns variable under the state declarations and check it starts at zero.
var turns := 0Why it works The counter represents accepted actions in this training shift.
-
Test the outside edges
Open _move. It calculates a candidate, checks it against a rectangle and stops before assigning it if the candidate is outside.
if not Rect2i(Vector2i.ZERO, MAP_SIZE).has_point(candidate):Why it works The proposed position is a preview. An illegal coordinate never becomes the live coordinate.
-
Keep walkway and stalls separate
Check whether the coordinate is a stall or the collection point. Use STALLS.values() to get positions instead of names.
if candidate in STALLS.values() or candidate == COUNTER:Why it works A table is reached from its side, so using it and walking into it are separate actions.
-
Spend the turn last
Find the movement assignment and the increment after the guards. Press North twice from the start.
turns += 1Why it works Each early return skips the increment. Nia can try the next open move safely.
-
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
-
Press North at (3, 3) Candidate (3, 2) is open.
What you see. Nia moves and turns becomes 1. -
Press North again Candidate (3, 1) is a stall.
What you see. Nia stays at (3, 2). Turns stays 1. -
Walk three South presses Two legal steps reach (3, 4), third is beyond the map.
What you see. Only the two legal steps count.
Predict before you run What is the turn count after pressing North twice at the starting square?
Reveal the answer
One. The first step is legal and the second meets the Flowers stall.
Complete checkpoint
Legal steps update the live turn count. An edge or stall refusal leaves both position and turn total unchanged.
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
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
_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 _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 = "Collection at (6, 3)"
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. -
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. -
_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 _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 = "Collection at (6, 3)"Show where Collection is while this checkpoint is teaching the map. -
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 touching a stall adds a turn, move the counter update below both early returns.
Try a change
Start a clean run. Touch the lower edge, try to move past it, then compare the coordinate and turn count before and after the refused press.