London Market 10 · Preview a three-slot market basket

Market Day London · Lesson 10 of 50 · Beginner · About 30 min

Nia is ready to try collecting useful things. This practice basket carries three items, including more than one of the same kind.

Watercolour of a dry London market lane lined with bread, produce and flower stalls.
What you’ll make Gather up to three items from the market stalls and make the basket appear on screen.

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

Check the square. Only a stall can supply an item. → Check the basket. Room is needed for another item. → Append and refresh. Add the good and update the label.
Check the square → Check the basket → Append and refresh
Godot checkpoint window for Preview a three-slot market basket
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Array[String], append(), size(), clear(), is_empty(), join(), >= and capacity.

  1. Read the empty basket

    Open Lesson 10. Find basket next to CAPACITY and press F5. Locate the Basket 0/3 line below the controls.

    var basket: Array[String] = []

    Why it works [] creates an empty list. Array[String] says that all entries will be item names. CAPACITY keeps the maximum in one place.

  2. Test a collection off the stalls

    At (3,3), tap Collect here. Inspect the first guard in _collect.

    if not STALLS.has(nia):

    Why it works The game checks that the current square names a stall before looking up or adding an item.

  3. Collect from a stall

    Go Up twice to Flowers and press Collect here once. In _collect, follow the item name from the stall record to the basket.

    basket.append(item)

    Why it works Append adds one item to the end of the list. _refresh_basket reads the updated list and its new size.

  4. Fill and test the limit

    Collect twice more at Flowers. Try a fourth time and show the branch that stops the action.

    if basket.size() >= CAPACITY:

    Why it works The check size() >= CAPACITY is true at 3. The early return protects the three stored items.

  5. Read the caption

    Inspect _refresh_basket, then compare its full-basket caption with the start-of-game caption.

    var contents := ", ".join(basket) if not basket.is_empty() else "empty"

    Why it works Join inserts a comma between entries. The separate empty case explains that no item names should appear.

  6. Empty and try another route

    Press Empty basket. Walk to Produce (1,1), then Bakery (5,1), collecting once at both. Compare the displayed order.

    basket.clear()

    Why it works Clear empties the same list. Later items appear in the order you append them. The next unit will use these item names to test orders.

Watch the values change

  1. Press Collect at Flowers. The item flowers is appended.
    What you see. The basket label reads 1/3 with flowers.
  2. Collect until full and try again. The fourth attempt finds size equal to capacity.
    What you see. The basket stays at 3 and a full message appears.
  3. Press Empty basket. clear removes all entries.
    What you see. The label returns to Basket 0/3.

Predict before you run What happens if a full basket tries to collect bread at Bakery instead of flowers?

Reveal the answer

The capacity guard rejects it. Changing the type or stall does not change the fact that all three spaces are in use.

Complete checkpoint

Nia can navigate, inspect and gather apple, flowers or bread at their stalls. The basket shows up to three items and can be emptied for another attempt.

main.gd

extends Control


const NIGHT := Color("#0d2335")
const PANEL := Color("#17374b")
const CREAM := Color("#fff4da")
const MINT := Color("#9ce4ce")
const GOLD := Color("#ffd789")
var board: Label

const ORIGIN := Vector2(47, 134)
const TILE := 57.0
const COLUMNS := 7
const ROWS := 5
var nia := Vector2i(3, 3)

const STALLS := {
	Vector2i(1, 1): {"name": "Produce", "sign": "P", "item": "apple", "ink": Color("#f5c986")},
	Vector2i(3, 1): {"name": "Flowers", "sign": "F", "item": "flowers", "ink": Color("#c5b4f0")},
	Vector2i(5, 1): {"name": "Bakery", "sign": "B", "item": "bread", "ink": Color("#f1a995")}
}
const COUNTER := Vector2i(6, 3)

const CAPACITY := 3
var basket: Array[String] = []
var basket_label: Label


func _ready() -> void:
	var title := Label.new()
	title.text = "Market Day London"
	title.position = Vector2(42, 34)
	title.add_theme_font_size_override("font_size", 34)
	title.modulate = CREAM
	add_child(title)
	board = Label.new()
	board.position = Vector2(45, 88)
	board.add_theme_font_size_override("font_size", 22)
	board.modulate = MINT
	add_child(board)
	_refresh()
	_add_button("Up", Vector2(635, 163), _move.bind(Vector2i.UP))
	_add_button("Left", Vector2(517, 221), _move.bind(Vector2i.LEFT))
	_add_button("Down", Vector2(635, 221), _move.bind(Vector2i.DOWN))
	_add_button("Right", Vector2(753, 221), _move.bind(Vector2i.RIGHT))
	_add_button("Inspect stall", Vector2(635, 285), _inspect)
	_add_button("Collect here", Vector2(753, 285), _collect)
	_add_button("Empty basket", Vector2(517, 285), _empty)
	basket_label = Label.new()
	basket_label.position = Vector2(520, 360)
	basket_label.modulate = CREAM
	basket_label.add_theme_font_size_override("font_size", 18)
	add_child(basket_label)
	_refresh_basket()


func _draw() -> void:
	draw_rect(Rect2(Vector2.ZERO, get_viewport_rect().size), NIGHT)
	draw_rect(Rect2(32, 120, 431, 316), PANEL)
	draw_rect(Rect2(487, 120, 437, 316), PANEL)
	for row in range(ROWS):
		for column in range(COLUMNS):
			var point := cell_centre(Vector2i(column, row))
			var tile := Rect2(point - Vector2.ONE * 27.0, Vector2.ONE * 54.0)
			var tint := Color("#31596b") if (row + column) % 2 == 0 else Color("#284d61")
			draw_rect(tile, tint)
	for location: Vector2i in STALLS:
		var stall: Dictionary = STALLS[location]
		var point := cell_centre(location)
		draw_rect(Rect2(point - Vector2.ONE * 24.0, Vector2.ONE * 48.0), stall["ink"])
		draw_string(ThemeDB.fallback_font, point + Vector2(-5, 6), stall["sign"], HORIZONTAL_ALIGNMENT_LEFT, -1, 20, NIGHT)
	var counter_point := cell_centre(COUNTER)
	draw_rect(Rect2(counter_point - Vector2.ONE * 24.0, Vector2.ONE * 48.0), GOLD, false, 3.0)
	draw_string(ThemeDB.fallback_font, counter_point + Vector2(-16, 5), "Pick up", HORIZONTAL_ALIGNMENT_LEFT, -1, 10, CREAM)
	var marker := cell_centre(nia)
	draw_circle(marker, 18.0, MINT)
	draw_string(ThemeDB.fallback_font, marker + Vector2(-10, 5), "Nia", HORIZONTAL_ALIGNMENT_LEFT, -1, 14, NIGHT)
	draw_string(ThemeDB.fallback_font, Vector2(46, 468), "BRIAR LANE  •  TRAINING MAP", HORIZONTAL_ALIGNMENT_LEFT, -1, 16, GOLD)


func _refresh() -> void:
	board.text = "Briar Lane • Nia is at column %d, row %d" % [nia.x, nia.y]


func cell_centre(cell: Vector2i) -> Vector2:
	return ORIGIN + Vector2(cell) * TILE + Vector2.ONE * (TILE / 2.0)


func _add_button(caption: String, point: Vector2, action: Callable) -> void:
	var button := Button.new()
	button.text = caption
	button.position = point
	button.custom_minimum_size = Vector2(108, 50)
	button.pressed.connect(action)
	add_child(button)


func _move(step: Vector2i) -> void:
	var next := nia + step
	if not Rect2i(0, 0, COLUMNS, ROWS).has_point(next):
		board.text = "End of the lane • Nia stays put."
		return
	nia = next
	_refresh()
	queue_redraw()


func _input(event: InputEvent) -> void:
	if not event is InputEventKey or not event.pressed or event.echo:
		return
	match event.keycode:
		KEY_UP:
			_move(Vector2i.UP)
		KEY_LEFT:
			_move(Vector2i.LEFT)
		KEY_DOWN:
			_move(Vector2i.DOWN)
		KEY_RIGHT:
			_move(Vector2i.RIGHT)
		_:
			return
	get_viewport().set_input_as_handled()


func _inspect() -> void:
	if nia == COUNTER:
		board.text = "Collection counter • Orders will be handed over here."
		return
	if not STALLS.has(nia):
		board.text = "Walk onto a P, F or B square to inspect a stall."
		return
	var stall: Dictionary = STALLS[nia]
	board.text = "%s sells %s" % [stall["name"], stall["item"]]


func _collect() -> void:
	if not STALLS.has(nia):
		board.text = "Choose a stall before collecting."
		return
	if basket.size() >= CAPACITY:
		board.text = "Basket full • Use Empty basket to practise again."
		return
	var stall: Dictionary = STALLS[nia]
	var item := str(stall["item"])
	basket.append(item)
	board.text = "Added %s from %s." % [item, stall["name"]]
	_refresh_basket()

func _empty() -> void:
	basket.clear()
	board.text = "Basket empty • Ready to practise."
	_refresh_basket()

func _refresh_basket() -> void:
	var contents := ", ".join(basket) if not basket.is_empty() else "empty"
	basket_label.text = "Basket %d/%d • %s" % [basket.size(), CAPACITY, contents]

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
  1. extends ControlAttach these screen-building instructions to a Godot Control. That gives the script positions, children and input events.
  2. const NIGHT := Color("#0d2335")Use this dark ink colour behind the market. The fixed colour is also used for lettering on the mint marker and brighter signs.
  3. const PANEL := Color("#17374b")Use one lighter shade to group the map and controls against the dark background.
  4. const CREAM := Color("#fff4da")Keep the title and labels light enough to read against dark panels.
  5. const MINT := Color("#9ce4ce")Use this accent to highlight the status label and Nia’s marker.
  6. const GOLD := Color("#ffd789")Mark utility labels and the collection point with a pale yellow that stands apart from the paving.
  7. var board: LabelSave the opening label so later methods can change it without needing to create a new one.
  8. const ORIGIN := Vector2(47, 134)Set the pixel position of the upper-left corner used to lay out the market grid.
  9. const TILE := 57.0Keep neighbouring tile centres 57 pixels apart.
  10. const COLUMNS := 7Give the training lane seven columns with indices from 0 to 6.
  11. const ROWS := 5Give the training lane five rows with indices from 0 to 4.
  12. var nia := Vector2i(3, 3)Start Nia at column 3 and row 3. Store grid values instead of pixel coordinates.
  13. const STALLS := {Pair each stall position with its teaching name, sign, sold item and colour.
  14. Vector2i(1, 1): {"name": "Produce", "sign": "P", "item": "apple", "ink": Color("#f5c986")},Store the Produce stall at the upper-left marked position. Its P sign stands for produce and it supplies apple.
  15. Vector2i(3, 1): {"name": "Flowers", "sign": "F", "item": "flowers", "ink": Color("#c5b4f0")},Store the Flowers stall in the middle of the upper marked row. Its F sign identifies flowers.
  16. Vector2i(5, 1): {"name": "Bakery", "sign": "B", "item": "bread", "ink": Color("#f1a995")}Store the Bakery at the upper-right marked position. Its B sign identifies the bread stop.
  17. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  18. const COUNTER := Vector2i(6, 3)Place the collection counter at column 6, row 3. No goods can be collected directly from this practice location.
  19. const CAPACITY := 3Keep the bag limit at three items, whatever type those items are.
  20. var basket: Array[String] = []Start an empty list of item names. Repeated names can take more than one of the three available spaces.
  21. var basket_label: LabelSave the basket’s label so _refresh_basket can repaint it after any supported change.
  22. func _ready() -> void:Godot calls this once when the Market scene is ready to create the title, notice and controls.
  23. var title := Label.new()Create an unattached Label for the permanent title. It becomes visible when it is added to the scene.
  24. title.text = "Market Day London"Put the game name into the title label. The title stays fixed while smaller words underneath change.
  25. title.position = Vector2(42, 34)Leave a margin of 42 pixels from the left and 34 from the top.
  26. title.add_theme_font_size_override("font_size", 34)Set this title to a larger local font size. The rest of the labels can keep different sizes.
  27. title.modulate = CREAMSet the title’s drawing colour to the pale cream chosen above.
  28. add_child(title)Add the title to the running scene so Godot draws and maintains it.
  29. board = Label.new()Create the changing notice label and store it in the field used by other methods.
  30. board.position = Vector2(45, 88)Position the variable status words underneath the game name.
  31. board.add_theme_font_size_override("font_size", 22)Set a smaller font for status messages, which can be longer than the title.
  32. board.modulate = MINTTint the notice mint so it stands out as the changing information.
  33. add_child(board)Attach the notice beneath the title so the player sees the current message.
  34. _refresh()Write the latest cell location into the notice without creating another label.
  35. _add_button("Up", Vector2(635, 163), _move.bind(Vector2i.UP))Place the Up button above the centre of the direction button cluster. It later supplies a step of (0,-1).
  36. _add_button("Left", Vector2(517, 221), _move.bind(Vector2i.LEFT))Place the Left button to the left of Down. It supplies a step of (-1,0).
  37. _add_button("Down", Vector2(635, 221), _move.bind(Vector2i.DOWN))Place the Down button below Up. It supplies a step of (0,1).
  38. _add_button("Right", Vector2(753, 221), _move.bind(Vector2i.RIGHT))Place the Right button beside Down. It supplies a step of (1,0).
  39. _add_button("Inspect stall", Vector2(635, 285), _inspect)Give the player one button whose meaning depends on Nia’s current tile.
  40. _add_button("Collect here", Vector2(753, 285), _collect)Allow a player to ask for the good supplied by the stall they are standing on.
  41. _add_button("Empty basket", Vector2(517, 285), _empty)Create a practice reset control for the basket. It does not reset Nia’s location.
  42. basket_label = Label.new()Create a second information line with its own job and retain it between functions.
  43. basket_label.position = Vector2(520, 360)Place the basket line below all control buttons.
  44. basket_label.modulate = CREAMUse cream text so the contents are readable against blue.
  45. basket_label.add_theme_font_size_override("font_size", 18)Choose a font size that can hold a three-item basket line.
  46. add_child(basket_label)Attach the basket label before writing its first status.
  47. _refresh_basket()Update the visible contents from the list, including after startup, collection and emptying.
  48. func _draw() -> void:Paint this section when Godot refreshes the Control. Draw the background first and the frontmost details last.
  49. draw_rect(Rect2(Vector2.ZERO, get_viewport_rect().size), NIGHT)Fill the visible window so there is a consistent dark background behind the game panels.
  50. draw_rect(Rect2(32, 120, 431, 316), PANEL)Draw the dark rectangle under the tile map.
  51. draw_rect(Rect2(487, 120, 437, 316), PANEL)Draw an adjacent rectangle behind the controls and basket information.
  52. for row in range(ROWS):Visit each row index from 0 through 4.
  53. for column in range(COLUMNS):For each row, visit column indices from 0 through 6.
  54. var point := cell_centre(Vector2i(column, row))Convert this loop pair into the pixel centre for one paving square.
  55. var tile := Rect2(point - Vector2.ONE * 27.0, Vector2.ONE * 54.0)Give the tile a 54-pixel square shape. The 57-pixel spacing leaves a small border between squares.
  56. var tint := Color("#31596b") if (row + column) % 2 == 0 else Color("#284d61")Use the remainder to alternate the paving colour. Equal parities use the same ink.
  57. draw_rect(tile, tint)Place the current square using the pixel rectangle and the chosen tint.
  58. for location: Vector2i in STALLS:Look at each position key in the stall map so every stand can be drawn.
  59. var stall: Dictionary = STALLS[location]Read the nested sign data attached to this particular coordinate.
  60. var point := cell_centre(location)Fit the sign into the same square the player must visit to inspect or collect.
  61. draw_rect(Rect2(point - Vector2.ONE * 24.0, Vector2.ONE * 48.0), stall["ink"])Fill the stall’s marked square with its own brighter colour.
  62. draw_string(ThemeDB.fallback_font, point + Vector2(-5, 6), stall["sign"], HORIZONTAL_ALIGNMENT_LEFT, -1, 20, NIGHT)Draw the stall letter on its square so people can tell the stalls apart without using colour alone.
  63. var counter_point := cell_centre(COUNTER)Convert the separate collection counter coordinate into a drawn point.
  64. draw_rect(Rect2(counter_point - Vector2.ONE * 24.0, Vector2.ONE * 48.0), GOLD, false, 3.0)Draw an outline around the future collection square, distinct from the filled stall squares.
  65. draw_string(ThemeDB.fallback_font, counter_point + Vector2(-16, 5), "Pick up", HORIZONTAL_ALIGNMENT_LEFT, -1, 10, CREAM)Add the compact Pick up sign inside the counter marker.
  66. var marker := cell_centre(nia)Convert the saved grid cell to the exact point where Nia’s visual marker belongs.
  67. draw_circle(marker, 18.0, MINT)Paint the small mint circle over the map paving or stall square.
  68. draw_string(ThemeDB.fallback_font, marker + Vector2(-10, 5), "Nia", HORIZONTAL_ALIGNMENT_LEFT, -1, 14, NIGHT)Put Nia’s name inside the circle so the marker does not rely on its colour alone.
  69. draw_string(ThemeDB.fallback_font, Vector2(46, 468), "BRIAR LANE • TRAINING MAP", HORIZONTAL_ALIGNMENT_LEFT, -1, 16, GOLD)Label the map with a quiet footer set apart from the playable square area.
  70. func _refresh() -> void:Update the status line from Nia’s currently stored map cell.
  71. board.text = "Briar Lane • Nia is at column %d, row %d" % [nia.x, nia.y]Read x as the column and y as the row, then show both values.
  72. func cell_centre(cell: Vector2i) -> Vector2:Convert a whole-number tile position into a pixel point for drawing.
  73. return ORIGIN + Vector2(cell) * TILE + Vector2.ONE * (TILE / 2.0)Multiply the tile coordinate by the 57-pixel spacing, start at ORIGIN and move another half tile to reach its centre.
  74. func _add_button(caption: String, point: Vector2, action: Callable) -> void:Receive a caption, screen position and callable to reuse the same control construction for different actions.
  75. var button := Button.new()Create a Godot button that the player will be able to activate after it is attached.
  76. button.text = captionUse the words provided by the caller to explain what this button does.
  77. button.position = pointPlace the button using the point sent by _ready.
  78. button.custom_minimum_size = Vector2(108, 50)Reserve a large area for the button so its label and touch target are easier to distinguish.
  79. button.pressed.connect(action)Tell Godot which stored action should run when the button emits its pressed signal.
  80. add_child(button)Put the button into the active scene so it can display and receive input.
  81. func _move(step: Vector2i) -> void:Receive one direction as a whole-number change to Nia’s column and row.
  82. var next := nia + stepCalculate the proposed grid cell. Nia is still at the saved cell while the game checks the proposal.
  83. if not Rect2i(0, 0, COLUMNS, ROWS).has_point(next):Ask whether the proposal is outside this zero-based rectangle. Points on the far right or bottom border are outside.
  84. board.text = "End of the lane • Nia stays put."Explain the rejected press while leaving the saved grid position alone.
  85. returnFinishes the function right here. Any later instructions in this function are skipped.
  86. nia = nextAccept the new position only after the bounds branch has been passed.
  87. _refresh()Write the latest cell location into the notice without creating another label.
  88. queue_redraw()Request a repaint so Nia’s marker now appears at the new cell.
  89. func _input(event: InputEvent) -> void:Receive a Godot input event. Keyboard events and button signals meet at the same move method.
  90. if not event is InputEventKey or not event.pressed or event.echo:Ignore non-key events, key releases and automatic repeats. Only a fresh key press goes further.
  91. returnFinishes the function right here. Any later instructions in this function are skipped.
  92. match event.keycode:Compare the key that arrived with the four arrow values.
  93. KEY_UP:Match the actual Up arrow, then ask for a one-tile move toward the top of the screen.
  94. _move(Vector2i.UP)Calls _move with the values in its parentheses.
  95. KEY_LEFT:Match the actual Left arrow, then ask for a one-column move to the left.
  96. _move(Vector2i.LEFT)Calls _move with the values in its parentheses.
  97. KEY_DOWN:Match the actual Down arrow, then ask for a one-tile move toward the bottom of the screen.
  98. _move(Vector2i.DOWN)Calls _move with the values in its parentheses.
  99. KEY_RIGHT:Match the actual Right arrow, then ask for a one-column move to the right.
  100. _move(Vector2i.RIGHT)Calls _move with the values in its parentheses.
  101. _:Recognise every other key as unrelated to market movement.
  102. returnFinishes the function right here. Any later instructions in this function are skipped.
  103. get_viewport().set_input_as_handled()Tell Godot this arrow was used for movement so another handler can avoid acting on it.
  104. func _inspect() -> void:Read the current market tile and produce a matching message without changing Nia’s stored location.
  105. if nia == COUNTER:Recognise a visit to the separate collection counter before the stall lookup.
  106. board.text = "Collection counter • Orders will be handed over here."Explain where orders will be handed over in the next unit.
  107. returnFinishes the function right here. Any later instructions in this function are skipped.
  108. if not STALLS.has(nia):Ask whether the current cell lacks a stall entry before trying to read that entry.
  109. board.text = "Walk onto a P, F or B square to inspect a stall."Guide Nia to the three labelled stall tiles. The marker stays where it was.
  110. returnFinishes the function right here. Any later instructions in this function are skipped.
  111. var stall: Dictionary = STALLS[nia]Load the record at Nia’s current position. The earlier membership check means there is a matching key.
  112. board.text = "%s sells %s" % [stall["name"], stall["item"]]Show the stall name and its item by reading the two matching fields from the current record.
  113. func _collect() -> void:Check the visited tile and remaining capacity, then update the stored basket when collection is legal.
  114. if not STALLS.has(nia):Ask whether the current cell lacks a stall entry before trying to read that entry.
  115. board.text = "Choose a stall before collecting."Tell the player why collection from an ordinary tile or the collection counter cannot happen.
  116. returnFinishes the function right here. Any later instructions in this function are skipped.
  117. if basket.size() >= CAPACITY:Compare the number of collected entries with the limit. At exactly three, the next request is already blocked.
  118. board.text = "Basket full • Use Empty basket to practise again."Display feedback when collection is blocked at full capacity. The contents remain intact.
  119. returnFinishes the function right here. Any later instructions in this function are skipped.
  120. var stall: Dictionary = STALLS[nia]Load the record at Nia’s current position. The earlier membership check means there is a matching key.
  121. var item := str(stall["item"])Read the item field as text so the typed basket can accept it.
  122. basket.append(item)Add one item name as a new list entry. It appears after the items that were already carried.
  123. board.text = "Added %s from %s." % [item, stall["name"]]Identify the item and stall in the notice so the player sees the outcome of the current press.
  124. _refresh_basket()Update the visible contents from the list, including after startup, collection and emptying.
  125. func _empty() -> void:Clear the basket and show feedback while leaving Nia in the same tile.
  126. basket.clear()Remove all entries from the practice list. The separate capacity constant is still three.
  127. board.text = "Basket empty • Ready to practise."Tell the player another collection test can start.
  128. _refresh_basket()Update the visible contents from the list, including after startup, collection and emptying.
  129. func _refresh_basket() -> void:Turn the current list and limit into a short readable status line.
  130. var contents := ", ".join(basket) if not basket.is_empty() else "empty"Separate the item names with commas when the list contains entries. Otherwise show the single word empty.
  131. basket_label.text = "Basket %d/%d • %s" % [basket.size(), CAPACITY, contents]Display the actual item count, the carrying limit, and the joined contents.

Find and fix a bug

If the fourth item fits, check the guard uses >= and appears before append. If the numbers are right but the text is stale, look for _refresh_basket after a change.

Try a change

Ages 10–12 can try one basket with three different goods. Ages 13–16 can build a short manual test for three full-item checks, repeated items and an empty reset.