Video Game Design and Coding · PLECK lesson

PLECK lesson 114 · suggested week 23, day 4

Restore a safe checkpoint and inventory

Objective. Map validated data to known scene objects.

Godot Engine Standard desktop editor 4.7.2-stable, GDScript (Godot 4), Compatibility renderer. Headless Godot 4.7.2.stable.official.ed1daf0bf passed 106 assertions on the supplied scaffolds, including malformed JSON saves. Audio used the Dummy driver and a synthetic WAV, not a speaker. The visual editor, browser export, and signed-in submission were not tested. The desk still does not run a student's own upload.

About 55 minutes. The due date is chosen by a parent.

JSON, user://, schema validation and safe failure

Suggested pace: Recall and predict 5 min; Read instruction and scaffold 12 min; Build or design the assigned artifact 25 min; Run acceptance tests 8 min; Explain and checkpoint 5 min.

Materials: Godot Standard 4.7.2 desktop editor (GDScript, Compatibility renderer), Local course folder and prior checkpoint, No paid assets or public account required.

Comes after VGC-L113.

Use C-WORLD-DATA as the integrated extension after the scalar-save lab. Give pickups fixed IDs s1,s2,s3,w1,w2 and beds b1,b2. The manager records collected and planted IDs; the validator derives remaining inventory from those IDs. On load, hide collected pickups, mark planted beds and map checkpoint to known Marker2D nodes. Clear player velocity. This avoids restoring quantities while respawning the same resources. Version-two world saves use their own course filename; report a fresh-state fallback for unsupported data instead of loading paths from it.

Worked example

A validated save contains known scalar fields and a version. An array instead of a dictionary is syntactically valid JSON but should still be rejected by the schema. Scaffold C-WORLD-DATA — Consistent pickup/bed persistence with derived inventory Setup: Attach to a separate Node named WorldData. This is the default integrated Seed Station model after the scalar-save lab. Fixed pickup IDs are s1,s2,s3,w1,w2; fixed bed IDs are b1,b2. Manager records picked IDs only after a successful pickup and planted IDs only after validating both resource costs. Inventory is derived from these IDs, so reloading cannot keep quantities while respawning already-picked rewards. On load, hide/free picked objects, mark planted beds, set the known start/greenhouse marker, then refresh HUD. Version 1 scalar labs are intentionally not migrated: report a new-game fallback. ```gdscript extends Node const PATH: String = "user://seed_station_world_v2.json" func defaults() -> Dictionary: return {"version": 2, "picked": [], "planted": [], "seed": 0, "water": 0, "checkpoint": "start"} func _ids(raw: Variant, allowed: Array) -> Array[String]: var clean: Array[String] = [] if raw is Array: for value in raw: if value is String and value in allowed and value not in clean: clean.append(value) return clean func validate(raw: Variant) -> Dictionary: var result := defaults() if not raw is Dictionary: return result var data: Dictionary = raw if data.get("version", 0) != 2: return result var picked := _ids(data.get("picked", []), ["s1", "s2", "s3", "w1", "w2"]) var planted := _ids(data.get("planted", []), ["b1", "b2"]) var seed_total: int = 0 var water_total: int = 0 for id in picked: if id.begins_with("s"): seed_total += 1 else: water_total += 1 while planted.size() > mini(seed_total, water_total): planted.pop_back() result["picked"] = picked result["planted"] = planted result["seed"] = seed_total - planted.size() result["water"] = water_total - planted.size() result["checkpoint"] = "greenhouse" if "b1" in planted else "start" return result func save_data(raw: Dictionary) -> bool: var file := FileAccess.open(PATH, FileAccess.WRITE) if file == null: return false file.store_string(JSON.stringify(validate(raw))) file.close() return true func load_data() -> Dictionary: if not FileAccess.file_exists(PATH): return defaults() var file := FileAccess.open(PATH, FileAccess.READ) if file == null: return defaults() var text: String = file.get_as_text() file.close() var parser := JSON.new() if parser.parse(text) != OK: return defaults() return validate(parser.data) ``` Scaffold C-CHECKPOINT — A safe checkpoint respawn Setup: Add this pattern to a separate Node2D level root with child Player using C-PLATFORM. Call set_checkpoint with a safe global position when a player reaches a checkpoint Area2D; call respawn when entering a fall zone. This code does not connect Area2D automatically; select the area body_entered signal in editor and call these methods from its handler after checking the player group. Respawn is deferred because a physics callback may be active. ```gdscript extends Node2D @onready var player: CharacterBody2D = $Player var checkpoint: Vector2 func _ready() -> void: checkpoint = player.global_position func set_checkpoint(safe_position: Vector2) -> void: checkpoint = safe_position func respawn() -> void: _apply_respawn.call_deferred() func _apply_respawn() -> void: player.global_position = checkpoint player.velocity = Vector2.ZERO ``` Scaffold C-INVENTORY — Dictionary inventory with guarded spending Setup: Attach to Node InventoryLab for standalone testing. In a real level put the same functions on its inventory node and update UI after successful calls. Item IDs are short fixed strings, never a player’s name. A key represents one item type and its integer value is the quantity. ```gdscript extends Node var items: Dictionary = {"seed": 0, "water": 0} func add_item(id: String, amount: int = 1) -> bool: if not items.has(id) or amount <= 0: return false items[id] = int(items[id]) + amount return true func spend(id: String, amount: int = 1) -> bool: if not items.has(id) or amount <= 0 or int(items[id]) < amount: return false items[id] = int(items[id]) - amount return true func _ready() -> void: assert(add_item("seed", 2)) assert(spend("seed", 1)) assert(not spend("seed", 2)) assert(items["seed"] == 1) ```

Consistent pickup/bed persistence with derived inventory

GDScript (Godot 4, not Scratch, Python, JavaScript or C#). Scaffold C-WORLD-DATA. Copy starts from this text. The desk does not run it.

Scene and node setup

Attach to a separate Node named WorldData. This is the default integrated Seed Station model after the scalar-save lab. Fixed pickup IDs are s1,s2,s3,w1,w2; fixed bed IDs are b1,b2. Manager records picked IDs only after a successful pickup and planted IDs only after validating both resource costs. Inventory is derived from these IDs, so reloading cannot keep quantities while respawning already-picked rewards. On load, hide/free picked objects, mark planted beds, set the known start/greenhouse marker, then refresh HUD. Version 1 scalar labs are intentionally not migrated: report a new-game fallback.

extends Node
const PATH: String = "user://seed_station_world_v2.json"
func defaults() -> Dictionary:
    return {"version": 2, "picked": [], "planted": [], "seed": 0, "water": 0, "checkpoint": "start"}
func _ids(raw: Variant, allowed: Array) -> Array[String]:
    var clean: Array[String] = []
    if raw is Array:
        for value in raw:
            if value is String and value in allowed and value not in clean:
                clean.append(value)
    return clean
func validate(raw: Variant) -> Dictionary:
    var result := defaults()
    if not raw is Dictionary:
        return result
    var data: Dictionary = raw
    if data.get("version", 0) != 2:
        return result
    var picked := _ids(data.get("picked", []), ["s1", "s2", "s3", "w1", "w2"])
    var planted := _ids(data.get("planted", []), ["b1", "b2"])
    var seed_total: int = 0
    var water_total: int = 0
    for id in picked:
        if id.begins_with("s"):
            seed_total += 1
        else:
            water_total += 1
    while planted.size() > mini(seed_total, water_total):
        planted.pop_back()
    result["picked"] = picked
    result["planted"] = planted
    result["seed"] = seed_total - planted.size()
    result["water"] = water_total - planted.size()
    result["checkpoint"] = "greenhouse" if "b1" in planted else "start"
    return result
func save_data(raw: Dictionary) -> bool:
    var file := FileAccess.open(PATH, FileAccess.WRITE)
    if file == null:
        return false
    file.store_string(JSON.stringify(validate(raw)))
    file.close()
    return true
func load_data() -> Dictionary:
    if not FileAccess.file_exists(PATH):
        return defaults()
    var file := FileAccess.open(PATH, FileAccess.READ)
    if file == null:
        return defaults()
    var text: String = file.get_as_text()
    file.close()
    var parser := JSON.new()
    if parser.parse(text) != OK:
        return defaults()
    return validate(parser.data)

Checks to run in the editor

Native Godot 4.7.2.stable.official.ed1daf0bf headless compile and representative node-tree/runtime tests passed; see native-qa-results.json. Visual UI, audible output, exports and website submission still need separate checks.

A safe checkpoint respawn

GDScript (Godot 4, not Scratch, Python, JavaScript or C#). Scaffold C-CHECKPOINT. Copy starts from this text. The desk does not run it.

Scene and node setup

Add this pattern to a separate Node2D level root with child Player using C-PLATFORM. Call set_checkpoint with a safe global position when a player reaches a checkpoint Area2D; call respawn when entering a fall zone. This code does not connect Area2D automatically; select the area body_entered signal in editor and call these methods from its handler after checking the player group. Respawn is deferred because a physics callback may be active.

extends Node2D
@onready var player: CharacterBody2D = $Player
var checkpoint: Vector2
func _ready() -> void:
    checkpoint = player.global_position
func set_checkpoint(safe_position: Vector2) -> void:
    checkpoint = safe_position
func respawn() -> void:
    _apply_respawn.call_deferred()
func _apply_respawn() -> void:
    player.global_position = checkpoint
    player.velocity = Vector2.ZERO

Checks to run in the editor

Native Godot 4.7.2.stable.official.ed1daf0bf headless compile and representative node-tree/runtime tests passed; see native-qa-results.json. Visual UI, audible output, exports and website submission still need separate checks.

Dictionary inventory with guarded spending

GDScript (Godot 4, not Scratch, Python, JavaScript or C#). Scaffold C-INVENTORY. Copy starts from this text. The desk does not run it.

Scene and node setup

Attach to Node InventoryLab for standalone testing. In a real level put the same functions on its inventory node and update UI after successful calls. Item IDs are short fixed strings, never a player’s name. A key represents one item type and its integer value is the quantity.

extends Node
var items: Dictionary = {"seed": 0, "water": 0}
func add_item(id: String, amount: int = 1) -> bool:
    if not items.has(id) or amount <= 0:
        return false
    items[id] = int(items[id]) + amount
    return true
func spend(id: String, amount: int = 1) -> bool:
    if not items.has(id) or amount <= 0 or int(items[id]) < amount:
        return false
    items[id] = int(items[id]) - amount
    return true
func _ready() -> void:
    assert(add_item("seed", 2))
    assert(spend("seed", 1))
    assert(not spend("seed", 2))
    assert(items["seed"] == 1)

Checks to run in the editor

Native Godot 4.7.2.stable.official.ed1daf0bf headless compile and representative node-tree/runtime tests passed; see native-qa-results.json. Visual UI, audible output, exports and website submission still need separate checks.

Restore a safe checkpoint and inventory — evidence task

  1. 1. Integrate C-WORLD-DATA and restore collected pickup IDs, planted bed IDs, derived inventory and the approved checkpoint marker.
  2. 2. Collect s1,s2,w1, plant b1, save, stop and relaunch. Verify seed1/water0, b1 planted, and the three collected pickups absent.

Deliverable. Integrated save checkpoint, schema amendment if needed, and relaunch test.

Acceptance checks

Understanding question. Why can restoring inventory alone duplicate resources?

Include a downloadable project ZIP with project.godot, .tscn, .gd and original asset files when code changes. A private, teacher-accessible download link to that ZIP is equivalent. Screenshots or a playthrough do not replace editable source.

If this is still shaky. Use the course-specific save filenames in C-SAVE and C-STATE-SAVE. Never edit unrelated game saves or load scripts from save data. Start with the first assigned task and re-run its acceptance test before adding the remaining feature.

Optional extra. Add a new fixed scalar field with a safe default and explicit validation. Document one changed parameter, your prediction, and the observed effect; optional, not required for completion.

Name ____________________ Date ____________________