Tiny Shelf 09 · Draw the first tiny packages

Tiny Shelf Studio · Lesson 09 of 50 · Beginner · About 25 min

Three sample miniatures arrive for the display. Give each one a distinct front label and show every other shelf space empty.

Miniature packaging workshop with coloured paper models, tools and a teal cutting mat.
What you’ll make Attach item IDs to particular slot IDs and draw one small carton for each using a reusable function.

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

Read the slot ID. Look for it in PREVIEW. → Find the style. Use the item ID as the key. → Draw small layers. Show the product and its label.
Read the slot ID → Find the style → Draw small layers
Godot checkpoint window for Draw the first tiny packages
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Dictionary, keys and values, has, nested dictionaries, Color, draw_rect, draw_string.

  1. Map spaces to item IDs

    Add PREVIEW to the constants. Use slot IDs as keys and brief item IDs as their values.

    const PREVIEW := {0: "lemon_fizz", 1: "honey_hoops", 5: "mint_paste"}

    Why it works The slot number is where the package sits. The text ID identifies which kind of package it is.

  2. Describe each tiny carton

    Add PACK_STYLE. Use an ink colour for the carton and an uppercase mark for its front label.

    const PACK_STYLE := {
    	"lemon_fizz": {"ink": Color("#ffd575"), "mark": "LEMON"},
    	"honey_hoops": {"ink": Color("#f58a9d"), "mark": "HONEY"},
    	"mint_paste": {"ink": Color("#b4edce"), "mark": "MINT"},
    }

    Why it works Each ID points to another dictionary describing its appearance. Separate information from the generic drawing instructions.

  3. Find occupied spaces while drawing

    At the bottom of the inner loop in _draw, check PREVIEW.has(index). If an item is present, call draw_pack a little way into the slot.

    			if PREVIEW.has(index):
    				draw_pack(point + Vector2(31, 27), PREVIEW[index])

    Why it works The check prevents looking for a value under a missing slot. The same loop still draws every shelf space.

  4. Read the correct style

    Add draw_pack below the helpers. Fetch the product dictionary and store its ink colour in a typed variable.

    func draw_pack(point: Vector2, item_id: String) -> void:
    	var product: Dictionary = PACK_STYLE[item_id]
    	var ink: Color = product["ink"]

    Why it works One item ID selects the record so the drawing function can use different styles with identical geometry.

  5. Build the package from layers

    Finish draw_pack by drawing a shadow, front, folded seal and light label. Draw the mark last.

    	draw_rect(Rect2(point + Vector2(4, 4), Vector2(49, 53)), NAVY)
    	draw_rect(Rect2(point, Vector2(45, 53)), ink)
    	draw_rect(Rect2(point + Vector2(0, 2), Vector2(45, 5)), ink.lightened(0.35))
    	draw_rect(Rect2(point + Vector2(4, 15), Vector2(37, 20)), PAPER)
    	print_on_shelf(product["mark"], point + Vector2(6, 29), 10, NAVY)

    Why it works Later drawings cover earlier ones where they overlap. Starting with the shadow makes the small carton look raised off the shelf surface.

  6. Find the three placements

    Run and tap slots 00, 01 and 05. Compare the marks. Then select slot 07 and check there is no carton drawn.

    Why it works The selection is independent of the item's presence. A player can examine empty or occupied shelf space.

Watch the values change

  1. Draw slot 00. PREVIEW holds "lemon_fizz".
    What you see. A yellow carton with a LEMON mark appears.
  2. Draw slot 01. PREVIEW holds "honey_hoops".
    What you see. A rose carton with a HONEY mark appears.
  3. Draw slot 07. PREVIEW has no key 7.
    What you see. The space has no carton.

Predict before you run What moves if you replace PREVIEW's key 5 with 8 and keep its value mint_paste?

Reveal the answer

The MINT carton moves from slot 05 to 08. Its shape, colour and mark still come from the same style record.

Complete checkpoint

LEMON, HONEY and MINT appear in slots 00, 01 and 05. The other nine slots have no cartons.

main.gd

extends Control


const NAVY := Color("#18243d")
const PAPER := Color("#fff5e7")
const SHELF := Color("#302e4b")
const CREAM := Color("#fff2d3")
const PINK := Color("#f58a9d")
const MINT := Color("#b4edce")
const GOLD := Color("#ffd575")
const COLUMNS := 4
const ROWS := 3
const ORIGIN := Vector2(68, 171)
const TILE := Vector2(116, 98)
var selected := Vector2i.ZERO
const PREVIEW := {0: "lemon_fizz", 1: "honey_hoops", 5: "mint_paste"}
const PACK_STYLE := {
	"lemon_fizz": {"ink": Color("#ffd575"), "mark": "LEMON"},
	"honey_hoops": {"ink": Color("#f58a9d"), "mark": "HONEY"},
	"mint_paste": {"ink": Color("#b4edce"), "mark": "MINT"},
}
var bulletin: Label


func _ready() -> void:
	make_label("TINY SHELF STUDIO", Vector2(49, 30), 35, NAVY)
	bulletin = make_label("", Vector2(51, 81), 21, NAVY)
	_refresh()
	make_label("Miniatures on display", Vector2(598, 181), 23, NAVY)
	_add_button("Up", Vector2(704, 232), _shift.bind(Vector2i.UP))
	_add_button("Left", Vector2(598, 285), _shift.bind(Vector2i.LEFT))
	_add_button("Down", Vector2(704, 285), _shift.bind(Vector2i.DOWN))
	_add_button("Right", Vector2(810, 285), _shift.bind(Vector2i.RIGHT))


func make_label(text: String, point: Vector2, font_size: int, ink: Color) -> Label:
	var label := Label.new()
	label.text = text
	label.position = point
	label.modulate = ink
	label.add_theme_font_size_override("font_size", font_size)
	add_child(label)
	return label


func _draw() -> void:
	draw_rect(get_viewport_rect(), PAPER)
	draw_rect(Rect2(48, 126, 502, 360), SHELF)
	draw_rect(Rect2(577, 126, 334, 360), Color("#f1ded4"))
	draw_rect(Rect2(48, 126, 8, 360), PINK)
	print_on_shelf("TRAINING DISPLAY", Vector2(67, 153), 14, MINT)
	print_on_shelf("DISPLAY WORKBENCH", Vector2(597, 155), 14, NAVY)
	print_on_shelf("Quesbo Coding  /  Godot practice", Vector2(49, 520), 16, NAVY)
	for row in range(ROWS):
		for column in range(COLUMNS):
			var cell := Vector2i(column, row)
			var point := cell_origin(cell)
			var slot := Rect2(point, TILE - Vector2(9, 9))
			draw_rect(slot, Color("#554a69"))
			var index := cell_to_index(cell)
			print_on_shelf("%02d" % index, point + Vector2(9, 19), 13, CREAM)
			if cell == selected:
				draw_rect(slot, GOLD, false, 3.0)
			if PREVIEW.has(index):
				draw_pack(point + Vector2(31, 27), PREVIEW[index])


func print_on_shelf(text: String, point: Vector2, font_size: int, ink: Color) -> void:
	draw_string(ThemeDB.fallback_font, point, text, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, ink)


func cell_origin(cell: Vector2i) -> Vector2:
	return ORIGIN + Vector2(cell) * TILE


func _refresh() -> void:
	bulletin.text = "Selected column %d, row %d" % [selected.x, selected.y]


func cell_to_index(cell: Vector2i) -> int:
	return cell.y * COLUMNS + cell.x


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(90, 46)
	button.pressed.connect(action)
	add_child(button)


func _select(cell: Vector2i) -> void:
	if not Rect2i(0, 0, COLUMNS, ROWS).has_point(cell):
		bulletin.text = "Shelf edge  ·  Selection stays put."
		return
	selected = cell
	_refresh()
	queue_redraw()


func _shift(direction: Vector2i) -> void:
	_select(selected + direction)


func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		var shelf_rect := Rect2(ORIGIN, Vector2(COLUMNS, ROWS) * TILE)
		if shelf_rect.has_point(event.position):
			var offset: Vector2 = (event.position - ORIGIN) / TILE
			_select(Vector2i(floori(offset.x), floori(offset.y)))
			get_viewport().set_input_as_handled()
		return
	if not event is InputEventKey or not event.pressed or event.echo:
		return
	match event.keycode:
		KEY_UP:
			_shift(Vector2i.UP)
		KEY_LEFT:
			_shift(Vector2i.LEFT)
		KEY_DOWN:
			_shift(Vector2i.DOWN)
		KEY_RIGHT:
			_shift(Vector2i.RIGHT)
		_:
			return
	get_viewport().set_input_as_handled()


func draw_pack(point: Vector2, item_id: String) -> void:
	var product: Dictionary = PACK_STYLE[item_id]
	var ink: Color = product["ink"]
	draw_rect(Rect2(point + Vector2(4, 4), Vector2(49, 53)), NAVY)
	draw_rect(Rect2(point, Vector2(45, 53)), ink)
	draw_rect(Rect2(point + Vector2(0, 2), Vector2(45, 5)), ink.lightened(0.35))
	draw_rect(Rect2(point + Vector2(4, 15), Vector2(37, 20)), PAPER)
	print_on_shelf(product["mark"], point + Vector2(6, 29), 10, NAVY)

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 ControlBase this script on a Godot Control. It can assemble text and buttons, receive input and draw directly into the scene.
  2. const NAVY := Color("#18243d")Give headings and package shadows a shared dark ink. The six-digit colour is read from a hexadecimal string.
  3. const PAPER := Color("#fff5e7")Use this warm, light colour behind the shelf and on front labels.
  4. const SHELF := Color("#302e4b")Set the dark display board colour. A constant lets later drawings refer to it by name.
  5. const CREAM := Color("#fff2d3")Use a light ink for numbers and letters placed against the dark display.
  6. const PINK := Color("#f58a9d")Add a warm edge to the display. This colour does not decide whether a slot is occupied.
  7. const MINT := Color("#b4edce")Use a light green marker in the workbench styling.
  8. const GOLD := Color("#ffd575")Reserve a high-contrast yellow for the frame around the selected slot.
  9. const COLUMNS := 4Set the shelf width to four slots. It also determines the step from the start of one row to the next in slot IDs.
  10. const ROWS := 3Limit the shelf to three rows. The valid row addresses are 0, 1 and 2.
  11. const ORIGIN := Vector2(68, 171)Place slot (0, 0) at x 68 and y 171 in the game window.
  12. const TILE := Vector2(116, 98)Give each grid location 116 pixels of width and 98 of height, including the gap before the next visible slot.
  13. var selected := Vector2i.ZEROStart at the top left. ZERO means the integer pair (0, 0).
  14. const PREVIEW := {0: "lemon_fizz", 1: "honey_hoops", 5: "mint_paste"}Record which slot contains each displayed product. The key is the slot ID. The value is a small product ID.
  15. const PACK_STYLE := {Look up a product's front design by its ID. The little inner braces group the colour and lettering for one item.
  16. "lemon_fizz": {"ink": Color("#ffd575"), "mark": "LEMON"},Use yellow and the short LEMON mark for the first miniature.
  17. "honey_hoops": {"ink": Color("#f58a9d"), "mark": "HONEY"},Use a pink carton and HONEY mark for the second miniature.
  18. "mint_paste": {"ink": Color("#b4edce"), "mark": "MINT"},Use pale green and MINT for the care miniature.
  19. }Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  20. var bulletin: LabelKeep a reference to the text node so other functions can edit its words.
  21. func _ready() -> void:Godot calls this when the Control enters the ready scene. Set up the initial title, labels and buttons here.
  22. make_label("TINY SHELF STUDIO", Vector2(49, 30), 35, NAVY)Put the studio name near the top-left corner. The title uses 35-pixel dark text on the light background.
  23. bulletin = make_label("", Vector2(51, 81), 21, NAVY)Create a second label and keep it in bulletin. You can set its text after placement.
  24. _refresh()Synchronise the main bulletin with the current column and row.
  25. make_label("Miniatures on display", Vector2(598, 181), 23, NAVY)Give the workbench one explanatory caption at the requested pixel position.
  26. _add_button("Up", Vector2(704, 232), _shift.bind(Vector2i.UP))Store the upward step to pass to _shift when the button fires.
  27. _add_button("Left", Vector2(598, 285), _shift.bind(Vector2i.LEFT))Store the left step to pass to _shift when the button fires.
  28. _add_button("Down", Vector2(704, 285), _shift.bind(Vector2i.DOWN))Store the downward step to pass to _shift when the button fires.
  29. _add_button("Right", Vector2(810, 285), _shift.bind(Vector2i.RIGHT))Store the right step to pass to _shift when the button fires.
  30. func make_label(text: String, point: Vector2, font_size: int, ink: Color) -> Label:Accept a string, a point, a font size and an ink colour. This helper returns the new Label so the caller can keep updating it.
  31. var label := Label.new()Create a Label object. It needs to be added to the running scene before it can appear.
  32. label.text = textPut the helper's text argument into the new Label.
  33. label.position = pointPosition the label using the x and y pixel coordinates passed into the helper.
  34. label.modulate = inkTint the label with the colour passed into this call.
  35. label.add_theme_font_size_override("font_size", font_size)Override the theme's size for just this label.
  36. add_child(label)Make Godot manage and draw the new Label as a child of the Control.
  37. return labelGive the caller the Label for later changes.
  38. func _draw() -> void:Godot calls this when the view requires drawing. Draw from the current selection and catalogue without changing the data.
  39. draw_rect(get_viewport_rect(), PAPER)Cover the entire view with the chosen light background.
  40. draw_rect(Rect2(48, 126, 502, 360), SHELF)Place the main dark panel under the shelf. The numbers are x, y, width and height.
  41. draw_rect(Rect2(577, 126, 334, 360), Color("#f1ded4"))Place a separate panel behind the tools and item card.
  42. draw_rect(Rect2(48, 126, 8, 360), PINK)Draw a thin edge along the display board.
  43. print_on_shelf("TRAINING DISPLAY", Vector2(67, 153), 14, MINT)Draw the display's section label using a mint colour on the dark panel.
  44. print_on_shelf("DISPLAY WORKBENCH", Vector2(597, 155), 14, NAVY)Draw a dark section label on the light workbench panel.
  45. print_on_shelf("Quesbo Coding / Godot practice", Vector2(49, 520), 16, NAVY)Add a quiet footer below both panels.
  46. for row in range(ROWS):Run the body for each row from zero up to, but excluding, ROWS.
  47. for column in range(COLUMNS):For every row, repeat the inner drawing code for each column.
  48. var cell := Vector2i(column, row)Join the loop's column and row into one grid address.
  49. var point := cell_origin(cell)Convert this address to its top-left screen point.
  50. var slot := Rect2(point, TILE - Vector2(9, 9))Turn the point and a slightly smaller tile size into a rectangle with room for a visible gap.
  51. draw_rect(slot, Color("#554a69"))Paint the background of the current shelf slot.
  52. var index := cell_to_index(cell)Read a zero-based slot ID for this cell.
  53. print_on_shelf("%02d" % index, point + Vector2(9, 19), 13, CREAM)Format the slot ID with at least two digits and position it above the package space.
  54. if cell == selected:Compare whole addresses, so the outline appears on the one matching column and row.
  55. draw_rect(slot, GOLD, false, 3.0)Paint a gold outline around the selected slot. Leave the middle of the rectangle unchanged.
  56. if PREVIEW.has(index):Only draw a package if the current slot ID is a key in PREVIEW.
  57. draw_pack(point + Vector2(31, 27), PREVIEW[index])Place the miniature 31 pixels right and 27 pixels down from the slot's corner.
  58. func print_on_shelf(text: String, point: Vector2, font_size: int, ink: Color) -> void:Name the text, position, size and colour for a painted line of text.
  59. draw_string(ThemeDB.fallback_font, point, text, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, ink)Use Godot's fallback font. point places the baseline of the text, which is where its letters sit.
  60. func cell_origin(cell: Vector2i) -> Vector2:Accept a slot address and return the top-left screen coordinate of that slot.
  61. return ORIGIN + Vector2(cell) * TILEMultiply the column by the tile width and the row by the tile height. Add the shelf margin to place the result.
  62. func _refresh() -> void:Define the single place that writes a shelf address onto the status bulletin.
  63. bulletin.text = "Selected column %d, row %d" % [selected.x, selected.y]Read selected.x for the column and selected.y for the row, then substitute each number into the status text.
  64. func cell_to_index(cell: Vector2i) -> int:Convert a two-part shelf address into one unique slot ID.
  65. return cell.y * COLUMNS + cell.xSkip the completed rows, four slots at a time, then add the column in this row.
  66. func _add_button(caption: String, point: Vector2, action: Callable) -> void:Build a reusable touch and keyboard control. The action argument points to the function that should run after a press.
  67. var button := Button.new()Create an unplaced Button object.
  68. button.text = captionSet the words the player reads on this button.
  69. button.position = pointUse the requested pixel coordinates for the upper-left corner of the button.
  70. button.custom_minimum_size = Vector2(90, 46)Give every workbench button a minimum width and height for easier viewing and clicking.
  71. button.pressed.connect(action)Listen to the pressed signal. Run the supplied callable when the activation happens.
  72. add_child(button)Put the configured Button on screen so it can handle clicks and keyboard focus.
  73. func _select(cell: Vector2i) -> void:Use one selection function whether the player taps the shelf or uses a button.
  74. if not Rect2i(0, 0, COLUMNS, ROWS).has_point(cell):Test the candidate against the four-by-three rectangle. not flips the result, so this block runs for an out-of-range address.
  75. bulletin.text = "Shelf edge · Selection stays put."Explain the blocked action while keeping the previous selection.
  76. returnLeave the function before touching selected or moving the highlight.
  77. selected = cellStore the requested address then let the label and highlight read it.
  78. _refresh()Synchronise the main bulletin with the current column and row.
  79. queue_redraw()Ask Godot to redraw the shelf so the highlight catches up with selected.
  80. func _shift(direction: Vector2i) -> void:Receive a direction from a button or key and turn it into a candidate address.
  81. _select(selected + direction)Combine the old selection and one step. The selection function will accept or reject that candidate.
  82. func _input(event: InputEvent) -> void:Let Godot send events to this Control so it can read taps or keys.
  83. if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:Check the event is a mouse-style left press. Touch can generate this event when touch-to-mouse emulation is enabled.
  84. var shelf_rect := Rect2(ORIGIN, Vector2(COLUMNS, ROWS) * TILE)Build the full click region from ORIGIN and the total size of all four columns and three rows.
  85. if shelf_rect.has_point(event.position):Only convert clicks inside the shelf. A workbench button can still handle its own press.
  86. var offset: Vector2 = (event.position - ORIGIN) / TILESubtract the shelf's screen margin and divide by one tile size. The remaining decimals describe the place inside a shelf tile.
  87. _select(Vector2i(floori(offset.x), floori(offset.y)))Round both tile coordinates down and pass the resulting integer pair to the shared selection rule.
  88. get_viewport().set_input_as_handled()Tell Godot that the current event has been used by the shelf.
  89. returnLeave this input path. No selection update is needed after the branch has handled or declined the event.
  90. if not event is InputEventKey or not event.pressed or event.echo:Skip events that are not fresh keyboard presses. A key release or an echo should not change the address.
  91. returnLeave this input path. No selection update is needed after the branch has handled or declined the event.
  92. match event.keycode:Run the branch for the selected arrow key. An unrelated key reaches the underscore fallback.
  93. KEY_UP:Recognise the up arrow.
  94. _shift(Vector2i.UP)Propose a move one row upward.
  95. KEY_LEFT:Recognise the left arrow.
  96. _shift(Vector2i.LEFT)Propose a move one column to the left.
  97. KEY_DOWN:Recognise the down arrow.
  98. _shift(Vector2i.DOWN)Propose a move one row downward.
  99. KEY_RIGHT:Recognise the right arrow.
  100. _shift(Vector2i.RIGHT)Propose a move one column to the right.
  101. _:Handles every match value that the branches above did not handle.
  102. returnLeave this input path. No selection update is needed after the branch has handled or declined the event.
  103. get_viewport().set_input_as_handled()Tell Godot that the current event has been used by the shelf.
  104. func draw_pack(point: Vector2, item_id: String) -> void:Paint a small product given its screen point and catalogue ID.
  105. var product: Dictionary = PACK_STYLE[item_id]Read the visual data record for this miniature.
  106. var ink: Color = product["ink"]Take the front colour from the product record.
  107. draw_rect(Rect2(point + Vector2(4, 4), Vector2(49, 53)), NAVY)Place the shadow first, a few pixels to the right and below the carton.
  108. draw_rect(Rect2(point, Vector2(45, 53)), ink)Draw the carton front over part of its shadow.
  109. draw_rect(Rect2(point + Vector2(0, 2), Vector2(45, 5)), ink.lightened(0.35))Draw a narrow pale strip at the top to show the fold of the package.
  110. draw_rect(Rect2(point + Vector2(4, 15), Vector2(37, 20)), PAPER)Lay a light label on the carton so dark text can be read.
  111. print_on_shelf(product["mark"], point + Vector2(6, 29), 10, NAVY)Paint the product's short front mark inside that label.

Find and fix a bug

If all three cartons look the same, check that draw_pack reads PACK_STYLE[item_id] rather than a single fixed ID.

Try a change

Create an original fourth diagram carton. Give it a new ID and distinct mark, then display it on slot 11. Try keeping the mark under seven letters.