Mobile Game 35 · Save the player's progress on this device

Museum of Lost Lights · Lesson 35 of 50 · Advanced · About 36 min

The museum may be visited over several days. Give players a way to return to their room and keep their display preference.

A gouache painting of a Fossil Gallery with amber lights, tall prehistoric skeleton displays and a dark stone floor.
What you’ll make Write a saved room and high-contrast setting to an on-device JSON file and load them back.

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

Take snapshot. Make a dictionary from the live variables. → Write JSON. Convert it to text and write to user://. → Load JSON. Read text and restore the two live values. → Render progress. Show the restored room and preference.
Take snapshot → Write JSON → Load JSON → Render progress

Build it step by step

Language and tools in this lesson const, Dictionary, FileAccess.open, FileAccess.WRITE, JSON.stringify, JSON.parse_string, null.

  1. Open and try the session

    Import the lesson folder in Godot and press F5. Enter Room 2, turn high contrast on and press Save this visit. Enter Room 3 and turn contrast off.

    Why it works You now have a saved visit and a changed live visit. Keeping two different values makes your load test easy to see.

  2. Find the save destination

    Open main.gd. Locate SAVE_PATH. Importantly, it starts with user://. In Godot's editor, use Project > Open User Data Folder to find the test file after saving.

    const SAVE_PATH := "user://museum_lesson_35.json"

    Why it works user:// is the project's writable data location. The path is a constant because the reader and writer need the same filename.

  3. Open the file and guard the write

    Follow save_visit. Compare the WRITE argument with the READ argument in load_visit. Keep the null check before touching the file.

    FileAccess.open(SAVE_PATH, FileAccess.WRITE)

    Why it works FileAccess can fail to open a file, returning null. The early return means the function will not try to use that missing file.

  4. Turn game state into text

    Match room and high_contrast in the live interface to the two values in snapshot. In the file, look for the same two keys.

    file.store_string(JSON.stringify(snapshot))

    Why it works JSON.stringify turns the dictionary into ordinary text. store_string writes that text. close releases the open file after the write.

  5. Read the text and restore state

    In load_visit locate parse_string, the Dictionary check and the two assignments below it. Now press Load the saved visit.

    JSON.parse_string(file.get_as_text())

    Why it works Parsing turns suitable text back into data. The check guards the dictionary lookups. int converts the room value to a whole number, and clampi keeps it in the museum's 1–12 range.

  6. Check a restart

    Stop with F8. Press F5 again. Confirm the fresh session starts at Room 1. Press Load and confirm you get Room 2 and high contrast on.

    Why it works This experiment checks the save survived closing the program. The game stores progress and a display preference on this device.

Watch the values change

  1. Save Room 2, contrast on Dictionary has two current values.
    What you see. JSON text is written to the lesson file.
  2. Enter Room 3, contrast off Only the live variables change.
    What you see. The interface shows Room 3 and high contrast off.
  3. Press Load Read and parse the saved dictionary.
    What you see. Room 2 and high contrast on return.

Predict before you run If you go to Room 4 after saving Room 2, then close without saving, which room does Load give you?

Reveal the answer

Room 2. Load reads the values from the last saved snapshot, which still contains Room 2.

Complete checkpoint

Room and display preference return from the saved snapshot, including after stopping and rerunning the project.

main.gd

extends Control

const SAVE_PATH := "user://museum_lesson_35.json"
var room := 1
var high_contrast := false
var readout: Label

func _ready() -> void:
	var panel := make_panel("35 · Save progress on this device")
	readout = make_label(panel, "")
	make_button(panel, "Enter the next room", next_room)
	make_button(panel, "Toggle high contrast", toggle_contrast)
	make_button(panel, "Save this visit", save_visit)
	make_button(panel, "Load the saved visit", load_visit)
	render_visit("New session.")

func next_room() -> void:
	room = mini(room + 1, 12)
	render_visit("Moved to a room.")

func toggle_contrast() -> void:
	high_contrast = not high_contrast
	render_visit("Display preference changed.")

func save_visit() -> void:
	var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
	if file == null:
		render_visit("The save file could not be written.")
		return
	var snapshot := {"room": room, "high_contrast": high_contrast}
	var written := file.store_string(JSON.stringify(snapshot))
	file.close()
	render_visit("Visit saved." if written else "The write failed.")

func load_visit() -> void:
	if not FileAccess.file_exists(SAVE_PATH):
		render_visit("There is no saved visit yet.")
		return
	var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
	if file == null:
		render_visit("The save file could not be read.")
		return
	var snapshot: Variant = JSON.parse_string(file.get_as_text())
	file.close()
	if not (snapshot is Dictionary):
		render_visit("The saved text could not be read as a visit.")
		return
	room = clampi(int(snapshot.get("room", 1)), 1, 12)
	high_contrast = snapshot.get("high_contrast", false) == true
	render_visit("Saved visit loaded.")

func render_visit(message: String) -> void:
	var preference := "on" if high_contrast else "off"
	readout.text = "Room %d · High contrast %s — %s" % [room, preference, 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
  1. 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.
  2. const SAVE_PATH := "user://museum_lesson_35.json"Name a save file just for Lesson 35. user:// asks for the project’s writable data folder instead of the original project folder.
  3. var room := 1Creates a variable named room. The expression uses the whole number 1. Godot infers the type from the first value.
  4. var high_contrast := falseCreates a variable named high_contrast. The expression uses the yes-or-no value false. Godot infers the type from the first value.
  5. var readout: LabelDeclares readout for later use. A colon followed by a type says which kind of value belongs here.
  6. 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.
  7. var panel := make_panel("35 · Save progress on this device")Creates a variable named panel. The expression calls make_panel with the values in its parentheses. Godot infers the type from the first value.
  8. readout = make_label(panel, "")Stores the new value in readout. The expression calls make_label with the values in its parentheses.
  9. make_button(panel, "Enter the next room", next_room)Calls make_button with the values in its parentheses.
  10. make_button(panel, "Toggle high contrast", toggle_contrast)Calls make_button with the values in its parentheses.
  11. make_button(panel, "Save this visit", save_visit)Calls make_button with the values in its parentheses.
  12. make_button(panel, "Load the saved visit", load_visit)Calls make_button with the values in its parentheses.
  13. render_visit("New session.")Calls render_visit with the values in its parentheses.
  14. func next_room() -> void:Defines next 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.
  15. room = mini(room + 1, 12)Increase room by one, but take 12 instead when adding one would go beyond the last room.
  16. render_visit("Moved to a room.")Calls render_visit with the values in its parentheses.
  17. func toggle_contrast() -> void:Defines toggle contrast, 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.
  18. high_contrast = not high_contrastSwitch the display preference between its two states independently of the exhibit.
  19. render_visit("Display preference changed.")Calls render_visit with the values in its parentheses.
  20. func save_visit() -> void:Defines save visit, 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.
  21. 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.
  22. if file == null:Check whether opening failed before reading from or writing to a file handle that does not exist.
  23. render_visit("The save file could not be written.")Calls render_visit with the values in its parentheses.
  24. returnFinishes the function right here. Any later instructions in this function are skipped.
  25. var snapshot := {"room": room, "high_contrast": high_contrast}Collect the current room and accessibility setting under two named keys so they can travel to the file together.
  26. var written := file.store_string(JSON.stringify(snapshot))Turn the snapshot into JSON text, write it to the opened file and remember whether Godot reports that the write worked.
  27. file.close()Close the file after the read or write is done, freeing the open handle before returning to the game.
  28. render_visit("Visit saved." if written else "The write failed.")Calls render_visit with the values in its parentheses.
  29. func load_visit() -> void:Defines load visit, 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.
  30. 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.
  31. render_visit("There is no saved visit yet.")Calls render_visit with the values in its parentheses.
  32. returnFinishes the function right here. Any later instructions in this function are skipped.
  33. var file := FileAccess.open(SAVE_PATH, FileAccess.READ)Try to open the lesson's on-device save for reading text.
  34. if file == null:Check whether opening failed before reading from or writing to a file handle that does not exist.
  35. render_visit("The save file could not be read.")Calls render_visit with the values in its parentheses.
  36. returnFinishes the function right here. Any later instructions in this function are skipped.
  37. var snapshot: Variant = JSON.parse_string(file.get_as_text())Get the saved text then parse it into a value. Keep it in a Variant until the next code confirms its actual type.
  38. file.close()Close the file after the read or write is done, freeing the open handle before returning to the game.
  39. if not (snapshot is Dictionary):Require parsed values to be a dictionary before looking up any key.
  40. render_visit("The saved text could not be read as a visit.")Calls render_visit with the values in its parentheses.
  41. returnFinishes the function right here. Any later instructions in this function are skipped.
  42. room = clampi(int(snapshot.get("room", 1)), 1, 12)Read room with a fallback of 1, convert to a whole number and keep it in the allowed 1–12 range.
  43. high_contrast = snapshot.get("high_contrast", false) == trueRead the saved preference or use false by default. The resulting Boolean determines the next displayed contrast state.
  44. render_visit("Saved visit loaded.")Calls render_visit with the values in its parentheses.
  45. func render_visit(message: String) -> void:Defines render visit, 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.
  46. var preference := "on" if high_contrast else "off"Creates a variable named preference. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  47. readout.text = "Room %d · High contrast %s — %s" % [room, preference, message]Updates readout.text, which controls the words a player sees. The expression uses the text inside the quotes.
  48. 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.
  49. var margin := MarginContainer.new()Create a container that can reserve clear space between the game controls and the window edges.
  50. 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.
  51. 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.
  52. 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.
  53. add_child(margin)Connect the completed margin container to the lesson's scene root so it can lay out its children.
  54. var centring := CenterContainer.new()Make a container that will centre the controls within the available space.
  55. margin.add_child(centring)Give the centring container the space inside the extra border, then let it place the panel within that space.
  56. var panel := VBoxContainer.new()Create a container that arranges its child controls in one vertical column.
  57. panel.custom_minimum_size.x = widthAsk the layout for at least the selected width, where x is the horizontal part of the size.
  58. panel.add_theme_constant_override("separation", 12)Leave 12 game pixels of space between each pair of controls in the vertical panel.
  59. centring.add_child(panel)Attach the vertical column to the centring container. Godot can now place the whole column together.
  60. make_label(panel, heading, 28)Put the supplied heading at the top of the column and ask for a larger 28-pixel font.
  61. return panelHand the panel reference back to the caller so it can add labels or buttons under the heading.
  62. 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.
  63. var label := Label.new()Make a new empty Label, which is Godot's text display node.
  64. label.text = messageCopy the incoming message into the label's visible words.
  65. 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.
  66. label.add_theme_font_size_override("font_size", size)Set the chosen size on this one label so other text can keep different sizes.
  67. parent.add_child(label)Add the label to the supplied parent. It becomes part of that panel's layout and can appear on screen.
  68. return labelReturn the exact label you created so the caller can change its text without building a second label.
  69. 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.
  70. var button := Button.new()Create a Godot Button that supports pointer, touch and keyboard activation.
  71. button.text = captionPut the supplied caption on the visible control.
  72. button.custom_minimum_size.y = 52Reserve at least 52 game pixels vertically so the control remains a comfortable target.
  73. button.pressed.connect(handle_press)Connect the pressed signal to the supplied callable. Godot waits for activation before running the action.
  74. parent.add_child(button)Attach the Button to its parent and let that container position it.
  75. 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 Save appears to work but Load cannot find it, check that both functions use the same SAVE_PATH constant and the file is in the project's user data folder.

Try a change

Ages 10–12 can add a second preference, such as sound, and test whether it returns after restart. Ages 13–16 can add a default for an older save that has no new preference.