London Market 37 · Upgrade a saved market record

Market Day London · Lesson 37 of 50 · Intermediate to advanced · About 35 min

Last year's market only tracked fastest turns. A new update needs both a best score and completion state.

Watercolour of a dry London market lane lined with bread, produce and flower stalls.
What you’ll make Convert old save data into the current layout and handle broken or unfamiliar records.

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

Inspect. Read the save version. → Validate. Check names and turn values. → Convert. Return the current shape. → Recover. Keep unreadable originals.
Inspect → Validate → Convert → Recover
Godot checkpoint window for Upgrade a saved market record
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Variant, is Dictionary, get, match, JSON.stringify.

  1. Import the editable checkpoint

    In the Godot 4.7.2 Project Manager, select Import and open the project.godot in this lesson folder. Open main.gd in the FileSystem dock. Press F5 to run the market and F8 to stop it before editing.

    Why it works This checkpoint already has a Control root with its script attached, so you can compare your edits to a working market scene.

  2. Recognise the old shape

    Run Load v1 example. Find the buttons in _ready and compare the dictionary for v1 with the v2 example.

    var version: Variant = input.get("version", 1)

    Why it works The old record carries best directly. The current one groups records by shift ID inside shifts.

  3. Pick one version branch

    Look at match version in upgrade. Click Load future v3 and find the branch that receives it.

    match version:

    Why it works The underscore branch handles a version the current code does not recognise. It returns an empty result so the preview refuses it.

  4. Build a new v2 record

    Press Load v1 example and read the JSON at the bottom. Find the return that puts the valid old best into setup.

    return {"version": 2, "shifts": {"setup": score}}

    Why it works A one-way conversion copies data into a new dictionary. It does not edit the original sample.

  5. Validate the new values

    Inspect the test inside the v2 loop. Add a test sample whose setup value is the word fast.

    if shift_id is String and score is int and int(score) > 0:

    Why it works Shift names must be text and best turns must be positive integers. A bad entry never becomes a valid personal record.

  6. Keep the original when unsure

    Read inspect and compare the damaged and future version messages. Make sure neither button saves a new file.

    output.text = "Keep the original file intact." if result.is_empty() else JSON.stringify(result)

    Why it works Migration is easier to test as a pure function. Refusal leaves the sample intact, which lets a later build recover it.

Watch the values change

  1. Load v1 The version defaults to 1 and best is 13.
    What you see. Preview shows v2 with setup of 13.
  2. Load a valid v2 The checker accepts the setup value.
    What you see. Preview shows the same score of 11.
  3. Load v3 or damaged The branch cannot safely interpret it.
    What you see. The preview tells the player to keep the original.

Predict before you run Will opening a future v3 example erase the original record?

Reveal the answer

No. This preview refuses unsupported records and does not write to disk.

Complete checkpoint

Valid old and new samples show a v2 result. Damaged and future samples keep the original data intact.

main.gd

extends Control

var status: Label
var output: Label

func _ready() -> void:
	heading("Upgrade a saved market record", "SAVE VERSIONS")
	label("Choose a record to load. The original sample stays unchanged.", Vector2(44, 126), 18, MINT)
	button("Load v1 example", Vector2(44, 209), inspect.bind({"best": 13}), 177)
	button("Load v2 example", Vector2(237, 209), inspect.bind({"version": 2, "shifts": {"setup": 11}}), 177)
	button("Load damaged", Vector2(430, 209), inspect.bind({"best": "fast"}), 177)
	button("Load future v3", Vector2(624, 209), inspect.bind({"version": 3, "entries": {}}), 177)
	status = label("", Vector2(44, 305), 25)
	output = label("", Vector2(44, 370), 18, MINT)
	inspect({"best": 13})

func upgrade(input: Variant) -> Dictionary:
	if not input is Dictionary:
		return {}
	var version: Variant = input.get("version", 1)
	if not version is int:
		return {}
	match version:
		1:
			var score: Variant = input.get("best", -1)
			if not score is int or int(score) < 1:
				return {}
			return {"version": 2, "shifts": {"setup": score}}
		2:
			var shifts: Variant = input.get("shifts", {})
			if not shifts is Dictionary:
				return {}
			var checked := {}
			for shift_id in shifts:
				var score: Variant = shifts[shift_id]
				if shift_id is String and score is int and int(score) > 0:
					checked[shift_id] = score
			return {"version": 2, "shifts": checked}
		_:
			return {}

func inspect(input: Variant) -> void:
	var result := upgrade(input)
	status.text = "Cannot load this sample" if result.is_empty() else "Ready • version 2 record"
	output.text = "Keep the original file intact." if result.is_empty() else JSON.stringify(result)

func _draw() -> void:
	base()

const INK := Color("#173353")
const PAPER := Color("#fff4db")
const MINT := Color("#a8e0c1")
const GOLD := Color("#ffd291")

func heading(caption: String, topic: String) -> void:
	label("MARKET DAY LONDON     /     " + topic, Vector2(44, 36), 15, GOLD)
	label(caption, Vector2(44, 66), 31)

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 button(words: String, at: Vector2, action: Callable, width: float = 164.0) -> Button:
	var control := Button.new()
	control.text = words
	control.position = at
	control.custom_minimum_size = Vector2(width, 43)
	control.pressed.connect(action)
	add_child(control)
	return control

func base(colour: Color = Color("#193652")) -> void:
	draw_rect(Rect2(Vector2.ZERO, size), Color("#11263e"))
	draw_rect(Rect2(Vector2(22, 20), size - Vector2(44, 40)), colour)

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 ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules.
  2. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  3. var output: LabelDeclares output for later use. A colon followed by a type says which kind of value belongs here.
  4. 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.
  5. heading("Upgrade a saved market record", "SAVE VERSIONS")Calls heading with the values in its parentheses.
  6. label("Choose a record to load. The original sample stays unchanged.", Vector2(44, 126), 18, MINT)Calls label with the values in its parentheses.
  7. button("Load v1 example", Vector2(44, 209), inspect.bind({"best": 13}), 177)Bind a small Dictionary to each button so learners can reproduce one save format with a press.
  8. button("Load v2 example", Vector2(237, 209), inspect.bind({"version": 2, "shifts": {"setup": 11}}), 177)Calls button with the values in its parentheses.
  9. button("Load damaged", Vector2(430, 209), inspect.bind({"best": "fast"}), 177)Calls button with the values in its parentheses.
  10. button("Load future v3", Vector2(624, 209), inspect.bind({"version": 3, "entries": {}}), 177)Calls button with the values in its parentheses.
  11. status = label("", Vector2(44, 305), 25)Stores the new value in status. The expression calls label with the values in its parentheses.
  12. output = label("", Vector2(44, 370), 18, MINT)Stores the new value in output. The expression calls label with the values in its parentheses.
  13. inspect({"best": 13})Calls inspect with the values in its parentheses.
  14. func upgrade(input: Variant) -> Dictionary:Receive a Variant so malformed samples can be checked before using Dictionary methods.
  15. if not input is Dictionary:Reject a non-Dictionary straight away. An empty Dictionary represents a record that the lab cannot use.
  16. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  17. var version: Variant = input.get("version", 1)Treat a Dictionary without a version key as the original version-one format.
  18. if not version is int:Checks not version is int. The indented instructions below run only if this test passes.
  19. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  20. match version:match selects one conversion branch for the supplied version number.
  21. 1:Starts the instructions for this branch. The indented lines belong together.
  22. var score: Variant = input.get("best", -1)Read the version-one result from its best key. The fallback -1 will fail the positive score check below.
  23. if not score is int or int(score) < 1:Checks not score is int or int(score) < 1. The indented instructions below run only if this test passes.
  24. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  25. return {"version": 2, "shifts": {"setup": score}}Return a new version-two Dictionary. The old best result becomes the setup shift score.
  26. 2:Starts the instructions for this branch. The indented lines belong together.
  27. var shifts: Variant = input.get("shifts", {})Creates a variable named shifts. The expression looks up a named or indexed value, using a fallback when the call gives one. The type after the colon says what kind of value it can hold.
  28. if not shifts is Dictionary:Checks not shifts is Dictionary. The indented instructions below run only if this test passes.
  29. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  30. var checked := {}Create a fresh Dictionary to collect validated shift records, keeping the input sample intact.
  31. for shift_id in shifts:Repeats the indented instructions for each value in shifts.
  32. var score: Variant = shifts[shift_id]Creates a variable named score. The expression looks up the item or key written between the square brackets. The type after the colon says what kind of value it can hold.
  33. if shift_id is String and score is int and int(score) > 0:Accept string keys and positive whole-number scores before copying them into the new record.
  34. checked[shift_id] = scoreStores the new value in checked[shift_id]. The expression reads score.
  35. return {"version": 2, "shifts": checked}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  36. _:The underscore is match’s catch-all branch. Future versions are rejected by this lab.
  37. return {}Finishes the function and hands its result back to the caller. The expression makes a dictionary that looks up values by key.
  38. func inspect(input: Variant) -> void:Defines inspect, 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.
  39. var result := upgrade(input)Creates a variable named result. The expression calls upgrade with the values in its parentheses. Godot infers the type from the first value.
  40. status.text = "Cannot load this sample" if result.is_empty() else "Ready • version 2 record"Updates status.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  41. output.text = "Keep the original file intact." if result.is_empty() else JSON.stringify(result)JSON.stringify() turns the new Dictionary into text that the learner can inspect on screen.
  42. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  43. base()Calls base with the values in its parentheses.
  44. const INK := Color("#173353")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value.
  45. const PAPER := Color("#fff4db")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  46. const MINT := Color("#a8e0c1")Creates a constant named MINT. The expression builds a colour from these values. Godot infers the type from the first value.
  47. const GOLD := Color("#ffd291")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value.
  48. func heading(caption: String, topic: String) -> void:Defines heading, 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.
  49. label("MARKET DAY LONDON / " + topic, Vector2(44, 36), 15, GOLD)Calls label with the values in its parentheses.
  50. label(caption, Vector2(44, 66), 31)Calls label with the values in its parentheses.
  51. 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.
  52. var item := Label.new()Creates a variable named item. The expression creates a new Label object. Godot infers the type from the first value.
  53. item.text = wordsUpdates item.text, which controls the words a player sees. The expression reads words.
  54. item.position = atUpdates item.position, which controls the node's local x and y location. The expression reads at.
  55. item.add_theme_font_size_override("font_size", pixels)Calls item.add_theme_font_size_override with the values in its parentheses.
  56. item.add_theme_color_override("font_color", ink)Calls item.add_theme_color_override with the values in its parentheses.
  57. add_child(item)Adds the new node to the scene tree so that Godot can run and draw it.
  58. return itemFinishes the function and hands its result back to the caller. The expression reads item.
  59. func button(words: String, at: Vector2, action: Callable, width: float = 164.0) -> Button:Defines 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.
  60. var control := Button.new()Creates a variable named control. The expression creates a new Button object. Godot infers the type from the first value.
  61. control.text = wordsUpdates control.text, which controls the words a player sees. The expression reads words.
  62. control.position = atUpdates control.position, which controls the node's local x and y location. The expression reads at.
  63. control.custom_minimum_size = Vector2(width, 43)Updates control.custom_minimum_size, which controls the smallest space the layout should reserve for this control. The expression packs x and y into one value.
  64. control.pressed.connect(action)Links a signal to the function that should run when the event happens.
  65. add_child(control)Adds the new node to the scene tree so that Godot can run and draw it.
  66. return controlFinishes the function and hands its result back to the caller. The expression reads control.
  67. func base(colour: Color = Color("#193652")) -> void:Defines base, 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.
  68. draw_rect(Rect2(Vector2.ZERO, size), Color("#11263e"))Paints a rectangle at the given position and size.
  69. draw_rect(Rect2(Vector2(22, 20), size - Vector2(44, 40)), colour)Paints a rectangle at the given position and size.

Find and fix a bug

If a missing version is always rejected, check that get supplies version 1 as the fallback for the historical format.

Try a change

Ages 10–12 can try a v1 best of 9. Ages 13–16 can create a v0 record sample, then add a separate migration branch and tests.