Market Day London · Lesson 19 of 50 · Beginner to intermediate · About 26 min
A student wants to compare two routes without restarting the entire market shift. Undo lets them revisit the most recent accepted state.

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/18 when the lesson builds on prior work, or copy the checkpoints/19 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 Snapshots, Dictionary fields, Array.duplicate(), pop_back(), assign(), Undo history.
-
Open the practice scene
Import checkpoints/19/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.
-
Keep one snapshot per accepted action
Find _remember. Call it after the guards and before each move, collect or successful delivery changes state.
history.append({Why it works The snapshot belongs to the state just before the action.
-
Preserve the basket by copying
Find basket.duplicate() within _remember. Move beside a stall, collect twice and then Undo once.
"cell": position_cell, "turns": turns, "basket": basket.duplicate(),Why it works A copy protects the saved inventory from later live edits.
-
Pop the latest record
Read the empty-history guard and pop_back in _undo. A fresh checkpoint has nothing to restore.
var earlier: Dictionary = history.pop_back()Why it works pop_back takes the newest action first and removes its record.
-
Restore the whole state
Find the lines that put back the position, accepted turns, basket, order progress and finish flag. Undo a delivery, then deliver again.
basket.assign(earlier["basket"])Why it works The restored previous basket and current order stay consistent with the turn count.
-
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
-
Move north from start History stores the (3, 3) position and turn 0.
What you see. Nia appears at (3, 2) with turn 1. -
Collect a flower, then Undo History replays the state before loading.
What you see. Nia stays beside Flowers. Basket is empty and turns is 1. -
Undo again The earlier move is the newest record.
What you see. Nia returns to the starting square and turn 0.
Predict before you run What should happen to the order and basket if you undo the final delivery?
Reveal the answer
The order should reopen and the old basket should return. The completed flag and accepted turn count also go back.
Complete checkpoint
Undo reverses one accepted move, collection or delivery, including a finish. A refused action never adds a history entry.
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"]]
var order_index := 0
var finished := false
var history: Array[Dictionary] = []
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("Deliver", Vector2(678, 330), 106, _deliver)
_button("Undo", Vector2(794, 330), 106, _undo)
_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:
if finished:
_say("Shift complete. Your result is ready.")
return
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
_remember()
position_cell = candidate
turns += 1
_say("Nia stepped to %s." % str(position_cell))
func _collect() -> void:
if finished:
_say("Shift complete. Your result is ready.")
return
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
_remember()
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 _deliver() -> void:
if finished:
_say("The completed orders are recorded.")
return
if not _adjacent(position_cell, COUNTER):
_say("Stand one square beside Collection.")
return
if not _matches(ORDERS[order_index]):
_say("The basket does not exactly match the current order.")
return
_remember()
basket.clear()
order_index += 1
turns += 1
if order_index == ORDERS.size():
finished = true
_say("Shift complete! Both customers collected their bundles.")
else:
_say("First bundle delivered. Check the next order.")
func _remember() -> void:
history.append({
"cell": position_cell, "turns": turns, "basket": basket.duplicate(),
"order_index": order_index, "finished": finished
})
func _undo() -> void:
if history.is_empty():
_say("There is no accepted action to undo.")
return
var earlier: Dictionary = history.pop_back()
position_cell = earlier["cell"]
turns = earlier["turns"]
basket.assign(earlier["basket"])
order_index = earlier["order_index"]
finished = earlier["finished"]
_say("The last accepted action was undone.")
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 = "Orders served: %d / %d" % [order_index, ORDERS.size()]
if not finished:
display_order.text = "Order %d: %s" % [order_index + 1, " + ".join(ORDERS[order_index])]
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. -
var order_index := 0Start the active ticket at index zero. The ticket label displays one because customers count from one. -
var finished := falseA new shift is still open. Turning this flag on freezes movement and other ordinary actions. -
var history: Array[Dictionary] = []Keep one dictionary per accepted action so Undo can restore a complete earlier state. -
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("Deliver", Vector2(678, 330), 106, _deliver)Call the handover rule so it can check the counter and basket. -
_button("Undo", Vector2(794, 330), 106, _undo)Connect Undo directly to the function that restores the last saved state. -
_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. -
if finished:A completed shift is guarded before this ordinary action can change the result. -
_say("Shift complete. Your result is ready.")Show the finished shift status in the feedback label. -
returnLeave the function here so the later action does not run. -
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. -
_remember()Save a snapshot while Nia is still on the previous square and before the turn is counted. -
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. -
if finished:A completed shift is guarded before this ordinary action can change the result. -
_say("Shift complete. Your result is ready.")Show the finished shift status in the feedback label. -
returnLeave the function here so the later action does not run. -
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. -
_remember()Save a snapshot while the basket is still unchanged. -
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 _deliver() -> void:Record a successful handover only after every guard has passed. -
if finished:A completed shift is guarded before this ordinary action can change the result. -
_say("The completed orders are recorded.")Show the finished shift status in the feedback label. -
returnLeave the function here so the later action does not run. -
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[order_index]):Verify the request at the current zero-based ticket index. -
_say("The basket does not exactly match the current order.")Show that the bundle contents do not fulfill the request. The guard below skips the change. -
returnLeave the function here so the later action does not run. -
_remember()Save a snapshot before the full bundle is removed and the order advances. -
basket.clear()Remove every item after the basket has passed the exact order check. -
order_index += 1Record one served order and point to the next ticket. -
turns += 1Spend one turn for the completed handover. -
if order_index == ORDERS.size():Check whether the served count has reached the number of tickets. -
finished = trueMark the last handover as complete so the result can be displayed safely. -
_say("Shift complete! Both customers collected their bundles.")Show the finished shift status in the feedback label. -
else:Run this branch if the earlier check was false. -
_say("First bundle delivered. Check the next order.")Show the outcome in the feedback label and redraw using the live state. -
func _remember() -> void:Save the exact live state immediately before an accepted action changes it. -
history.append({Make a dictionary snapshot and push it onto the end of the history stack. -
"cell": position_cell, "turns": turns, "basket": basket.duplicate(),Save the player cell, turn total and a copy of the basket. Copying means later pickups cannot alter this record. -
"order_index": order_index, "finished": finishedSave the order counter and finished flag together with the rest of the round. -
})Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above. -
func _undo() -> void:Restore the most recent accepted state. A refused move never creates a snapshot. -
if history.is_empty():Skip pop_back when there is no earlier turn to restore. -
_say("There is no accepted action to undo.")Show the result of the Undo action. -
returnLeave the function here so the later action does not run. -
var earlier: Dictionary = history.pop_back()Take the newest snapshot off the list and keep it in a local variable for restoration. -
position_cell = earlier["cell"]Put Nia back on the earlier square. -
turns = earlier["turns"]Restore the exact earlier move count. -
basket.assign(earlier["basket"])Replace the contents of the existing typed basket with items from the saved array. -
order_index = earlier["order_index"]Bring back the correct ticket, including a request that had just been served. -
finished = earlier["finished"]Recover the former open-or-complete state. Undoing the final handover reopens the shift. -
_say("The last accepted action was undone.")Show the result of the Undo action. -
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 = "Orders served: %d / %d" % [order_index, ORDERS.size()]Build a safe default using the served count and total number of tickets. -
if not finished:Read the active ticket only when its index can still point inside the array. -
display_order.text = "Order %d: %s" % [order_index + 1, " + ".join(ORDERS[order_index])]Show the human-readable ticket number and join the requested item names with plus marks. -
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 Undo restores Nia but loses the flowers, check the snapshot uses duplicate(). Saving the live basket directly lets later append or clear affect the old entry.
Try a change
Take a wrong route with two extra moves, then Undo exactly twice. Compare the result with a player who never took those moves.