Tiny Shelf Studio · Lesson 38 of 50 · Intermediate to advanced · About 35 min
Someone may leave the game midway through a display. Save a compact state and rebuild the buttons when the studio is active again.

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/37 when the lesson builds on prior work, or copy the checkpoints/38 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 _notification, NOTIFICATION_APPLICATION_PAUSED, ConfigFile, Array[String], is, DirAccess.
-
Open the design bench
Import this checkpoint's project.godot into Godot 4.7.2. Open main.gd from FileSystem. Press F5 for the starting view and F8 to stop it. Keep a copy to undo experiments.
Why it works The checkpoint scene attaches main.gd to a Control. Each test starts from that known version, so compare one change with the original.
-
Place an item and save a draft
Click Clear draft, then click slot 2. Follow the value written to positions and check the status says it was saved.
positions[slot] = ALL_IDS[slot % ALL_IDS.size()]Why it works Saving after a real action keeps the most recent state even if the app closes before a lifecycle notification.
-
Save the model in one record
Inspect write_draft. Find the board section and tiles key. Confirm the function returns the save result.
saved.set_value("board", "tiles", positions)Why it works The four IDs hold the state. New labels can be redrawn from those IDs when loading succeeds.
-
Try the simulated pause
Press Pause practice. Try an empty tile. Press Resume practice and see which tile is still filled.
if paused:Why it works The guard returns before placement while paused. The demo buttons exercise the same callbacks used for a real pause.
-
Validate a loaded array
Temporarily replace validated's argument in resume_board with ["unknown", "", "", ""]. Pause and resume again, then restore the original argument.
if not value is String or (value != "" and value not in ALL_IDS):Why it works The type, size and ID tests refuse the whole bad record. Keeping current tiles avoids a half-restored display.
-
Connect system events to the callbacks
Read the last notification branches. Run the game on a device when available, switch away and return, then inspect the draft.
if what == NOTIFICATION_APPLICATION_PAUSED:Why it works Godot supplies a message for system pause and resume. The status guard prevents calling UI functions before the scene is ready.
Watch the values change
-
Tap empty slot 2 positions[1] becomes comet_crisps.
What you see. The button reads Comet Crisps and the draft is written. -
Pause and try slot 3 paused is true, so the early return runs.
What you see. The button keeps Empty slot 3. -
Resume The validated array has four recognised entries or blanks.
What you see. The saved crisps are restored.
Predict before you run Does tapping a slot while paused change the draft?
Reveal the answer
No. The early return runs before any array change or write.
Complete checkpoint
A restorable draft with four sample slots, a visible paused state and validation for the item IDs.
main.gd
extends Control
const DRAFT := "user://tiny_studio_unit_38.cfg"
const BLANK := ["", "", "", ""]
const ALL_IDS := ["moon_milk", "comet_crisps", "pocket_paints"]
const TITLES := ["Moon Milk", "Comet Crisps", "Pocket Paints"]
var positions: Array = BLANK.duplicate()
var paused := false
var cards: Array[Button] = []
var status: Label
func _ready() -> void:
title_page("APP LIFECYCLE", "Resume an in-progress shelf", "Use a single-row practice shelf to make the restored state easy to check.")
status = label("", Vector2(53, 291), 20, SEA)
for i in range(BLANK.size()):
cards.append(place_button("", Vector2(52 + 215 * i, 198), put_sample.bind(i), 200))
place_button("Pause practice", Vector2(53, 395), pause_board)
place_button("Resume practice", Vector2(237, 395), resume_board, 184)
place_button("Clear draft", Vector2(435, 395), clear_board)
resume_board()
func put_sample(slot: int) -> void:
if paused:
refresh("Resume the shelf before placing a package.")
return
positions[slot] = ALL_IDS[slot % ALL_IDS.size()]
var result := write_draft()
refresh("Placed and saved." if result == OK else "Placed, but draft could not be saved.")
func write_draft() -> Error:
var saved := ConfigFile.new()
saved.set_value("board", "tiles", positions)
return saved.save(DRAFT)
func validated(source: Variant) -> Array:
if not source is Array or source.size() != BLANK.size():
return []
var clean: Array[String] = []
for value in source:
if not value is String or (value != "" and value not in ALL_IDS):
return []
clean.append(value)
return clean
func pause_board() -> void:
paused = true
var result := write_draft()
refresh("Paused · draft saved." if result == OK else "Paused · check the draft path.")
func resume_board() -> void:
paused = false
var loader := ConfigFile.new()
var result := loader.load(DRAFT)
if result == ERR_FILE_NOT_FOUND:
refresh("Place a package to start a draft.")
return
if result != OK:
refresh("Draft could not be read. Current tiles kept.")
return
var clean := validated(loader.get_value("board", "tiles", []))
if clean.is_empty():
refresh("Draft could not be restored. Current tiles kept.")
return
positions = clean
refresh("Resumed · draft restored.")
func clear_board() -> void:
if FileAccess.file_exists(DRAFT):
DirAccess.remove_absolute(DRAFT)
positions = BLANK.duplicate()
paused = false
refresh("Empty shelf · practice draft cleared.")
func _notification(what: int) -> void:
if not is_instance_valid(status):
return
if what == NOTIFICATION_APPLICATION_PAUSED:
pause_board()
elif what == NOTIFICATION_APPLICATION_RESUMED:
resume_board()
func refresh(note: String) -> void:
status.text = note
for i in range(cards.size()):
var item_index := ALL_IDS.find(positions[i])
cards[i].text = TITLES[item_index] if item_index >= 0 else "Empty slot %d" % (i + 1)
func _draw() -> void:
backdrop()
panel(Rect2(42, 177, 875, 177), Color("#244457"), EDGE)
const PAPER := Color("#fff4de")
const GOLD := Color("#f5bd79")
const SEA := Color("#9ddcd0")
const INK := Color("#172c3c")
const EDGE := Color("#54817f")
func title_page(unit: String, heading: String, subtitle: String) -> void:
label("TINY SHELF STUDIO / " + unit, Vector2(44, 36), 14, GOLD)
label(heading, Vector2(44, 65), 33)
label(subtitle, Vector2(46, 119), 16, SEA)
func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:
var item := Label.new()
item.text = words
item.position = at
item.add_theme_font_size_override("font_size", pixels)
item.add_theme_color_override("font_color", ink)
add_child(item)
return item
func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:
var control := Button.new()
control.text = words
control.position = at
control.custom_minimum_size = Vector2(width, 48)
control.add_theme_font_size_override("font_size", 17)
control.add_theme_color_override("font_color", PAPER)
control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))
control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))
control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))
control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))
control.pressed.connect(action)
add_child(control)
return control
func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:
var block := StyleBoxFlat.new()
block.bg_color = fill
block.border_color = edge
block.set_border_width_all(line)
block.set_corner_radius_all(8)
return block
func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:
draw_style_box(style(fill, edge), rect)
func backdrop() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))
panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))
func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:
draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)
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 ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules. -
const DRAFT := "user://tiny_studio_unit_38.cfg"Use a dedicated name so working progress is separate from the permanent scrapbook stamps. -
const BLANK := ["", "", "", ""]Creates a constant named BLANK. The expression makes a list whose items keep their order. Godot infers the type from the first value. -
const ALL_IDS := ["moon_milk", "comet_crisps", "pocket_paints"]Creates a constant named ALL_IDS. The expression makes a list whose items keep their order. Godot infers the type from the first value. -
const TITLES := ["Moon Milk", "Comet Crisps", "Pocket Paints"]Creates a constant named TITLES. The expression makes a list whose items keep their order. Godot infers the type from the first value. -
var positions: Array = BLANK.duplicate()Start from a copy of the blank shelf. The template remains available for reset. -
var paused := falseCreates a variable named paused. The expression uses the yes-or-no value false. Godot infers the type from the first value. -
var cards: Array[Button] = []Creates a variable named cards. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold. -
var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here. -
func _ready() -> void:Godot calls this once after the scene and its children are ready. Use it to set up the room and connect controls. -
title_page("APP LIFECYCLE", "Resume an in-progress shelf", "Use a single-row practice shelf to make the restored state easy to check.")Calls title_page with the values in its parentheses. -
status = label("", Vector2(53, 291), 20, SEA)Stores the new value in status. The expression calls label with the values in its parentheses. -
for i in range(BLANK.size()):Repeats the indented instructions for each value in range(BLANK.size()). -
cards.append(place_button("", Vector2(52 + 215 * i, 198), put_sample.bind(i), 200))Adds an item to the end of a list. -
place_button("Pause practice", Vector2(53, 395), pause_board)Calls place_button with the values in its parentheses. -
place_button("Resume practice", Vector2(237, 395), resume_board, 184)Calls place_button with the values in its parentheses. -
place_button("Clear draft", Vector2(435, 395), clear_board)Calls place_button with the values in its parentheses. -
resume_board()Calls resume_board with the values in its parentheses. -
func put_sample(slot: int) -> void:Defines put sample, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
if paused:Checks paused. The indented instructions below run only if this test passes. -
refresh("Resume the shelf before placing a package.")Calls refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
positions[slot] = ALL_IDS[slot % ALL_IDS.size()]Store the package ID in the chosen slot. The remainder lets four slots share the three practice products. -
var result := write_draft()Creates a variable named result. The expression calls write_draft with the values in its parentheses. Godot infers the type from the first value. -
refresh("Placed and saved." if result == OK else "Placed, but draft could not be saved.")Calls refresh with the values in its parentheses. -
func write_draft() -> Error:Defines write draft, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
var saved := ConfigFile.new()Creates a variable named saved. The expression creates a new ConfigFile object. Godot infers the type from the first value. -
saved.set_value("board", "tiles", positions)Save only the four ID values needed to rebuild the stage. -
return saved.save(DRAFT)Finishes the function and hands its result back to the caller. The expression calls saved.save with the values in its parentheses. -
func validated(source: Variant) -> Array:Defines validated, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
if not source is Array or source.size() != BLANK.size():Refuse a missing or incompatible layout before looping through its entries. -
return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order. -
var clean: Array[String] = []Creates a variable named clean. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold. -
for value in source:Repeats the indented instructions for each value in source. -
if not value is String or (value != "" and value not in ALL_IDS):Accept an empty slot or a known product name. Refuse the entire record if one entry fails. -
return []Finishes the function and hands its result back to the caller. The expression makes a list whose items keep their order. -
clean.append(value)Adds an item to the end of a list. -
return cleanFinishes the function and hands its result back to the caller. The expression reads clean. -
func pause_board() -> void:Defines pause board, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
paused = trueFreeze edits before taking the save snapshot. -
var result := write_draft()Creates a variable named result. The expression calls write_draft with the values in its parentheses. Godot infers the type from the first value. -
refresh("Paused · draft saved." if result == OK else "Paused · check the draft path.")Calls refresh with the values in its parentheses. -
func resume_board() -> void:Defines resume board, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
paused = falseUpdates paused, which controls whether the scene tree is paused. The expression uses the yes-or-no value false. -
var loader := ConfigFile.new()Creates a variable named loader. The expression creates a new ConfigFile object. Godot infers the type from the first value. -
var result := loader.load(DRAFT)Creates a variable named result. The expression reads a resource from the project when this instruction runs. Godot infers the type from the first value. -
if result == ERR_FILE_NOT_FOUND:Show ordinary instructions instead of treating an unused app as broken. -
refresh("Place a package to start a draft.")Calls refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if result != OK:Checks result != OK. The indented instructions below run only if this test passes. -
refresh("Draft could not be read. Current tiles kept.")Calls refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var clean := validated(loader.get_value("board", "tiles", []))Validate independently of the real shelf. A broken input can leave the current view intact. -
if clean.is_empty():Checks clean.is_empty(). The indented instructions below run only if this test passes. -
refresh("Draft could not be restored. Current tiles kept.")Calls refresh with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
positions = cleanOnly replace the board after receiving a whole verified draft. -
refresh("Resumed · draft restored.")Calls refresh with the values in its parentheses. -
func clear_board() -> void:Defines clear board, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
if FileAccess.file_exists(DRAFT):Checks FileAccess.file_exists(DRAFT). The indented instructions below run only if this test passes. -
DirAccess.remove_absolute(DRAFT)Calls DirAccess.remove_absolute with the values in its parentheses. -
positions = BLANK.duplicate()Stores the new value in positions. The expression copies the collection so a later change can leave the original alone. -
paused = falseUpdates paused, which controls whether the scene tree is paused. The expression uses the yes-or-no value false. -
refresh("Empty shelf · practice draft cleared.")Calls refresh with the values in its parentheses. -
func _notification(what: int) -> void:Godot calls this for engine notices, such as the app going into the background. -
if not is_instance_valid(status):Check that the scene's label has been created before responding to system messages. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if what == NOTIFICATION_APPLICATION_PAUSED:Route app pause through the same function as the practice Pause button. -
pause_board()Calls pause_board with the values in its parentheses. -
elif what == NOTIFICATION_APPLICATION_RESUMED:Use the matching resume path to rebuild the shelf from the saved draft. -
resume_board()Calls resume_board with the values in its parentheses. -
func refresh(note: String) -> void:Defines refresh, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
status.text = noteUpdates status.text, which controls the words a player sees. The expression reads note. -
for i in range(cards.size()):Repeats the indented instructions for each value in range(cards.size()). -
var item_index := ALL_IDS.find(positions[i])Translate a key into its name by using the same index for both lists. -
cards[i].text = TITLES[item_index] if item_index >= 0 else "Empty slot %d" % (i + 1)Updates cards[i].text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle. -
func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state. -
backdrop()Calls backdrop with the values in its parentheses. -
panel(Rect2(42, 177, 875, 177), Color("#244457"), EDGE)Calls panel with the values in its parentheses. -
const PAPER := Color("#fff4de")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value. -
const GOLD := Color("#f5bd79")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value. -
const SEA := Color("#9ddcd0")Creates a constant named SEA. The expression builds a colour from these values. Godot infers the type from the first value. -
const INK := Color("#172c3c")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value. -
const EDGE := Color("#54817f")Creates a constant named EDGE. The expression builds a colour from these values. Godot infers the type from the first value. -
func title_page(unit: String, heading: String, subtitle: String) -> void:Defines title page, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
label("TINY SHELF STUDIO / " + unit, Vector2(44, 36), 14, GOLD)Make a small line above the main heading so you can tell which checkpoint is open. -
label(heading, Vector2(44, 65), 33)Calls label with the values in its parentheses. -
label(subtitle, Vector2(46, 119), 16, SEA)Calls label with the values in its parentheses. -
func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:Defines label, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
var item := Label.new()Creates a variable named item. The expression creates a new Label object. Godot infers the type from the first value. -
item.text = wordsUpdates item.text, which controls the words a player sees. The expression reads words. -
item.position = atUpdates item.position, which controls the node's local x and y location. The expression reads at. -
item.add_theme_font_size_override("font_size", pixels)This Label has its own readable type size. Changing that value leaves the other labels alone. -
item.add_theme_color_override("font_color", ink)This label keeps the chosen text ink even when the default theme changes. -
add_child(item)Adds the new node to the scene tree so that Godot can run and draw it. -
return itemFinishes the function and hands its result back to the caller. The expression reads item. -
func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:Defines place button, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
var control := Button.new()Creates a variable named control. The expression creates a new Button object. Godot infers the type from the first value. -
control.text = wordsUpdates control.text, which controls the words a player sees. The expression reads words. -
control.position = atUpdates control.position, which controls the node's local x and y location. The expression reads at. -
control.custom_minimum_size = Vector2(width, 48)Give the button room for its label and an easy target for taps. Containers and layouts can allocate more space. -
control.add_theme_font_size_override("font_size", 17)Calls control.add_theme_font_size_override with the values in its parentheses. -
control.add_theme_color_override("font_color", PAPER)Calls control.add_theme_color_override with the values in its parentheses. -
control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))Calls control.add_theme_stylebox_override with the values in its parentheses. -
control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses. -
control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses. -
control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))Draw a gold outline around keyboard focus. Other button styles can still indicate hover and press independently. -
control.pressed.connect(action)pressed fires on a successful control activation. Godot calls the function passed in without running it at setup time. -
add_child(control)Adds the new node to the scene tree so that Godot can run and draw it. -
return controlFinishes the function and hands its result back to the caller. The expression reads control. -
func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:Defines style, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
var block := StyleBoxFlat.new()Creates a variable named block. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value. -
block.bg_color = fillStores the new value in block.bg_color. The expression reads fill. -
block.border_color = edgeStores the new value in block.border_color. The expression reads edge. -
block.set_border_width_all(line)Apply one border line width to all four edges of the card. -
block.set_corner_radius_all(8)Round each corner of this reusable style by eight pixels. -
return blockFinishes the function and hands its result back to the caller. The expression reads block. -
func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:Defines panel, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
draw_style_box(style(fill, edge), rect)Calls draw_style_box with the values in its parentheses. -
func backdrop() -> void:Defines backdrop, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))Paints a rectangle at the given position and size. -
panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))Subtract space on both sides of the canvas. As the window changes, the outer frame fits within it. -
func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:Defines paint words, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect. -
draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)Godot draws the words from the baseline at the supplied pixel position using its fallback typeface.
Find and fix a bug
If a load clears good slots before it detects bad data, build and validate a separate array first. Assign positions only once all entries pass.
Try a change
Expand the draft to 12 slots for a full shelf. Change the initial array and visual grid together and test an older four-slot draft.