Museum of Lost Lights · Lesson 36 of 50 · Advanced · About 41 min
A museum renovation renamed level to room. An older visitor's ticket should still work, and a damaged ticket should leave the lantern's current visit alone.

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/35 when the lesson builds on prior work, or copy the checkpoints/36 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 JSON, int, clampi, Dictionary.get, Variant, match, type check, early return.
-
Try the old ticket
Import and run the lesson. Press Write version 1 example, then Try loading the example. Read the message and the room number.
Why it works The injected examples are practice save files. This lab can recreate an old release's file without changing the actual museum game.
-
Read the version marker
Open main.gd and find record.get("version"). Compare the first two Write buttons. Look for the different key that follows version.
var version: Variant = record.get("version")Why it works The version tells the loader how to read the rest. Dictionary.get returns the value associated with the key, or null if there is no value and no supplied default.
-
Choose how to read the room
Read match version. Trace the old file to level and the new file to room. Notice that the numeric version patterns use floats, which is how Godot reads these JSON numbers.
candidate = record.get("level")Why it works match chooses a branch. The underscore branch covers other values and ends the load while keeping the current visit.
-
Reject a damaged or unsuitable ticket
Press Write damaged example and Try loading. Inspect the dictionary check before match and the whole-number test after it.
if not (candidate is float or candidate is int):Why it works JSON.new makes a parser. parse reports OK for valid text or an error code. Later checks protect the game from an accepted version with an unusable room, such as a string or a fractional number.
-
Set the live room at the end
Look for room = number and mark that line. Find which earlier lines can return before the assignment.
room = numberWhy it works Only validated data gets permission to change progress. Storing an uncertain value in candidate allows all the checks to happen first.
-
Check the failure and recovery sequence
Load version 2, then load a damaged example, then load version 1. Write down the three displayed room numbers.
Why it works A good recovery test proves a bad save leaves the last good result intact, and the player can recover by loading a usable file later.
Watch the values change
-
Load version 1 Match reads level = 5.
What you see. Current room becomes 5. -
Load damaged example Parsing yields no dictionary. Early return preserves room.
What you see. Room 5 remains and the damaged-file message appears. -
Load version 2 Match reads room = 7. Validation passes.
What you see. Current room becomes 7.
Predict before you run What happens if an example has version 2 and room 13?
Reveal the answer
The numeric data can be read, but the range check catches Room 13. The current room stays exactly as it was and the status explains the allowed range.
Complete checkpoint
Both known formats load. Broken text, unsupported versions and invalid room numbers leave the live room unchanged.
main.gd
extends Control
const SAVE_PATH := "user://museum_lesson_36.json"
const CURRENT_VERSION := 2
var room := 3
var readout: Label
func _ready() -> void:
var panel := make_panel("36 · Recover from a damaged save")
readout = make_label(panel, "")
make_button(panel, "Write version 1 example", func(): write_example('{"version":1,"level":5}'))
make_button(panel, "Write version 2 example", func(): write_example('{"version":2,"room":7}'))
make_button(panel, "Write damaged example", func(): write_example('{"version":2'))
make_button(panel, "Try loading the example", load_snapshot)
show_room("Ready to test.")
func write_example(contents: String) -> void:
var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
if file == null:
show_room("Could not open the test file.")
return
var written := file.store_string(contents)
file.close()
show_room("Example written." if written else "Could not write the test file.")
func load_snapshot() -> void:
if not FileAccess.file_exists(SAVE_PATH):
show_room("Write an example first.")
return
var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
if file == null:
show_room("The test file could not be read.")
return
var parser := JSON.new()
var result := parser.parse(file.get_as_text())
file.close()
if result != OK or not (parser.data is Dictionary):
show_room("Save was damaged. Current progress kept.")
return
var record: Dictionary = parser.data
var version: Variant = record.get("version")
var candidate: Variant
match version:
1.0:
candidate = record.get("level")
float(CURRENT_VERSION):
candidate = record.get("room")
_:
show_room("Unknown version. Current progress kept.")
return
if not (candidate is float or candidate is int):
show_room("Save did not contain a room number. Progress kept.")
return
var number := int(candidate)
if float(candidate) != float(number) or number < 1 or number > 12:
show_room("Room must be a whole number from 1 to 12.")
return
room = number
show_room("Room loaded from version %d." % int(version))
func show_room(message: String) -> void:
readout.text = "Current room %d — %s" % [room, message]
func make_panel(heading: String, width: float = 580.0) -> VBoxContainer:
var margin := MarginContainer.new()
margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 24)
add_child(margin)
var centring := CenterContainer.new()
margin.add_child(centring)
var panel := VBoxContainer.new()
panel.custom_minimum_size.x = width
panel.add_theme_constant_override("separation", 12)
centring.add_child(panel)
make_label(panel, heading, 28)
return panel
func make_label(parent: Control, message: String, size: int = 18) -> Label:
var label := Label.new()
label.text = message
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
label.add_theme_font_size_override("font_size", size)
parent.add_child(label)
return label
func make_button(parent: Control, caption: String, handle_press: Callable) -> Button:
var button := Button.new()
button.text = caption
button.custom_minimum_size.y = 52
button.pressed.connect(handle_press)
parent.add_child(button)
return button
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 ControlGive this script the layout and input abilities of Godot's Control node. The code below turns the root Control into a particular museum practice scene. -
const SAVE_PATH := "user://museum_lesson_36.json"Name a save file just for Lesson 36. user:// asks for the project’s writable data folder instead of the original project folder. -
const CURRENT_VERSION := 2Creates a constant named CURRENT_VERSION. The expression uses the whole number 2. Godot infers the type from the first value. -
var room := 3Creates a variable named room. The expression uses the whole number 3. Godot infers the type from the first value. -
var readout: LabelDeclares readout for later use. A colon followed by a type says which kind of value belongs here. -
func _ready() -> void:Godot calls this function once when the node is ready. The indented setup creates the interface and gives its controls their starting values. -
var panel := make_panel("36 · Recover from a damaged save")Creates a variable named panel. The expression calls make_panel with the values in its parentheses. Godot infers the type from the first value. -
readout = make_label(panel, "")Stores the new value in readout. The expression calls make_label with the values in its parentheses. -
make_button(panel, "Write version 1 example", func(): write_example('{"version":1,"level":5}'))Calls make_button with the values in its parentheses. -
make_button(panel, "Write version 2 example", func(): write_example('{"version":2,"room":7}'))Calls make_button with the values in its parentheses. -
make_button(panel, "Write damaged example", func(): write_example('{"version":2'))Calls make_button with the values in its parentheses. -
make_button(panel, "Try loading the example", load_snapshot)Calls make_button with the values in its parentheses. -
show_room("Ready to test.")Calls show_room with the values in its parentheses. -
func write_example(contents: String) -> void:Defines write example, 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 file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)Try to open the lesson's on-device save for writing. A successful write opening replaces the file's prior contents. -
if file == null:Check whether opening failed before reading from or writing to a file handle that does not exist. -
show_room("Could not open the test file.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var written := file.store_string(contents)Creates a variable named written. The expression writes text into the open file. Godot infers the type from the first value. -
file.close()Close the file after the read or write is done, freeing the open handle before returning to the game. -
show_room("Example written." if written else "Could not write the test file.")Calls show_room with the values in its parentheses. -
func load_snapshot() -> void:Defines load snapshot, 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 FileAccess.file_exists(SAVE_PATH):Check for a missing save path first. Give a friendly message rather than trying to read a nonexistent file. -
show_room("Write an example first.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var file := FileAccess.open(SAVE_PATH, FileAccess.READ)Try to open the lesson's on-device save for reading text. -
if file == null:Check whether opening failed before reading from or writing to a file handle that does not exist. -
show_room("The test file could not be read.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var parser := JSON.new()Create a JSON parser object that can report whether it understood the text. -
var result := parser.parse(file.get_as_text())Read all the saved text and store the parser's status code for the check below. -
file.close()Close the file after the read or write is done, freeing the open handle before returning to the game. -
if result != OK or not (parser.data is Dictionary):Stop if the parser reported an error or produced something other than a dictionary. Neither situation can safely supply a visit. -
show_room("Save was damaged. Current progress kept.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var record: Dictionary = parser.dataUse a named dictionary after the earlier checks have confirmed what the parsed value contains. -
var version: Variant = record.get("version")Read the version marker. It may be absent or use an unknown type, so check it before trusting the rest of the save. -
var candidate: VariantDeclares candidate for later use. A colon followed by a type says which kind of value belongs here. -
match version:Choose a path for a supported file version. The fallback branch keeps the current game state. -
1.0:Select the old file format. JSON numbers are parsed as floats, so this case uses 1.0. -
candidate = record.get("level")Get the proposed room from the older level key, without changing the current room yet. -
float(CURRENT_VERSION):Select the current file format by comparing to its numeric marker. -
candidate = record.get("room")Get the proposed room from the current room key, while leaving the game unchanged. -
_:Handles every match value that the branches above did not handle. -
show_room("Unknown version. Current progress kept.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
if not (candidate is float or candidate is int):Reject a missing or nonnumeric room. A valid candidate must be a number before conversion and range checks. -
show_room("Save did not contain a room number. Progress kept.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
var number := int(candidate)Get the integer candidate. The following line rejects the value if dropping a fractional part changed it. -
if float(candidate) != float(number) or number < 1 or number > 12:Reject fractional numbers and any whole number outside the twelve numbered rooms. -
show_room("Room must be a whole number from 1 to 12.")Calls show_room with the values in its parentheses. -
returnFinishes the function right here. Any later instructions in this function are skipped. -
room = numberChange the actual room now that all earlier checks agree the saved data is safe to use. -
show_room("Room loaded from version %d." % int(version))Calls show_room with the values in its parentheses. -
func show_room(message: String) -> void:Defines show room, 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. -
readout.text = "Current room %d — %s" % [room, message]Updates readout.text, which controls the words a player sees. The expression uses the text inside the quotes. -
func make_panel(heading: String, width: float = 580.0) -> VBoxContainer:Make a helper that takes the heading text and the panel's minimum width. If the caller omits the width, use 580 game pixels. Return the laid-out panel so the caller can add more controls. -
var margin := MarginContainer.new()Create a container that can reserve clear space between the game controls and the window edges. -
margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Choose the preset that aligns the margin's edges with all four edges of the parent Control. -
for side in ["left", "right", "top", "bottom"]:Visit the four names in order so the following indented line can set one margin on each trip through the loop. -
margin.add_theme_constant_override("margin_" + side, 24)Join margin_ to the current side's name. Set that edge to 24 game pixels, and repeat for the other sides. -
add_child(margin)Connect the completed margin container to the lesson's scene root so it can lay out its children. -
var centring := CenterContainer.new()Make a container that will centre the controls within the available space. -
margin.add_child(centring)Give the centring container the space inside the extra border, then let it place the panel within that space. -
var panel := VBoxContainer.new()Create a container that arranges its child controls in one vertical column. -
panel.custom_minimum_size.x = widthAsk the layout for at least the selected width, where x is the horizontal part of the size. -
panel.add_theme_constant_override("separation", 12)Leave 12 game pixels of space between each pair of controls in the vertical panel. -
centring.add_child(panel)Attach the vertical column to the centring container. Godot can now place the whole column together. -
make_label(panel, heading, 28)Put the supplied heading at the top of the column and ask for a larger 28-pixel font. -
return panelHand the panel reference back to the caller so it can add labels or buttons under the heading. -
func make_label(parent: Control, message: String, size: int = 18) -> Label:Accept the parent control, text to show and optional font size. Return the new Label so the caller can update it later. -
var label := Label.new()Make a new empty Label, which is Godot's text display node. -
label.text = messageCopy the incoming message into the label's visible words. -
label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTLet the label wrap lines at sensible places so a long message can fit when the layout is narrow. -
label.add_theme_font_size_override("font_size", size)Set the chosen size on this one label so other text can keep different sizes. -
parent.add_child(label)Add the label to the supplied parent. It becomes part of that panel's layout and can appear on screen. -
return labelReturn the exact label you created so the caller can change its text without building a second label. -
func make_button(parent: Control, caption: String, handle_press: Callable) -> Button:Build and return one Button. The arguments identify its parent, the words on it and the action to run after pressing it. -
var button := Button.new()Create a Godot Button that supports pointer, touch and keyboard activation. -
button.text = captionPut the supplied caption on the visible control. -
button.custom_minimum_size.y = 52Reserve at least 52 game pixels vertically so the control remains a comfortable target. -
button.pressed.connect(handle_press)Connect the pressed signal to the supplied callable. Godot waits for activation before running the action. -
parent.add_child(button)Attach the Button to its parent and let that container position it. -
return buttonGive the finished Button to the caller, which can keep a reference to set focus or change the caption later.
Find and fix a bug
If a damaged save resets the player, check that you assign room only after the entire validation path. Do not give invalid candidate data to the live state.
Try a change
Ages 10–12 can edit the version 2 example to Room 10 and predict the status. Ages 13–16 can add a version 3 dictionary with a settings sub-dictionary and maintain both older formats.