Video Game Design and Coding

PLECK lesson 157 · suggested week 32, day 2

Finish ordinary richer-system behavior

Objective. Connect a complete useful feature to play.

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.

Validated data, state behavior, integration and restart consistency

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-L156.

Make the richer system fully useful within the game’s scope. For saves, demonstrate a meaningful stop/relaunch restoration without duplication. For AI, show patrol, detection, chase, escape and return with readable cues. For generation, rebuild a playable room from a named seed with matching walls and a guaranteed route. Test a normal full sequence, not just one function. Keep limitations explicit: direct steering is not maze pathfinding, and one guaranteed route is not full-map connectivity.

Worked example

A richer-system table can pair valid values with safe fallback behavior. Unknown checkpoint IDs map to a known start marker rather than a path loaded from input. Scaffold C-STATE-SAVE — Validated inventory and checkpoint data Setup: Attach to a Node named SaveData. This is a separate file from C-SAVE and only reads fixed known scalar fields. get_checkpoint_data returns plain data, not live node references. When applying a loaded checkpoint, the assignment maps checkpoint ID to a teacher-approved safe Marker2D, never to a filename supplied by the save. ```gdscript extends Node const PATH: String = "user://seed_station_v1.json" func defaults() -> Dictionary: return {"version": 1, "seed": 0, "water": 0, "checkpoint": "start"} func _bounded_count(value: Variant) -> int: if value is int or value is float: return clampi(int(value), 0, 99) return 0 func validate(raw: Variant) -> Dictionary: var clean := defaults() if not raw is Dictionary: return clean var data: Dictionary = raw if data.get("version", 0) != 1: return clean clean["seed"] = _bounded_count(data.get("seed", 0)) clean["water"] = _bounded_count(data.get("water", 0)) var checkpoint: Variant = data.get("checkpoint", "start") if checkpoint is String and checkpoint in ["start", "greenhouse"]: clean["checkpoint"] = checkpoint return clean 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-GUARD-AI — A readable patrol/chase/return state machine Setup: Create CharacterBody2D Guard with visible circle or polygon and matching collider. Layer 4 mask 2 for walls. Attach script and assign target to your Player instance in Inspector. Level is one open rectangle; this is steering, not navigation around walls. Damage remains a separate sensor/manager event. Draw detection radii on a design diagram before tuning values. ```gdscript extends CharacterBody2D enum Mode { PATROL, CHASE, RETURN } @export var target: Node2D @export var speed: float = 70.0 var mode: Mode = Mode.PATROL var home: Vector2 var patrol_target: Vector2 func _ready() -> void: home = global_position patrol_target = home + Vector2(80, 0) func _physics_process(delta: float) -> void: if not is_instance_valid(target): velocity = Vector2.ZERO return var distance: float = global_position.distance_to(target.global_position) if mode != Mode.CHASE and distance < 120.0: mode = Mode.CHASE elif mode == Mode.CHASE and distance > 180.0: mode = Mode.RETURN var destination: Vector2 if mode == Mode.CHASE: destination = target.global_position elif mode == Mode.RETURN: destination = home if global_position.distance_to(home) <= maxf(3.0, speed * delta): mode = Mode.PATROL else: destination = patrol_target if global_position.distance_to(patrol_target) <= maxf(3.0, speed * delta): patrol_target = home if patrol_target != home else home + Vector2(80, 0) var offset := destination - global_position velocity = offset.normalized() * minf(speed, offset.length() / maxf(delta, 0.001)) move_and_slide() ``` Scaffold C-GRID — A deterministic grid with a guaranteed clear route Setup: Attach to Node2D GridLab. This example draws, not physics, so the assignment adds matching wall collision only after validation. Grid is 8 columns by 6 rows at 40 pixels per cell. Row 0 and column 7 are a guaranteed clear route from (0,0) to (7,5). RNG seed is a nonpersonal integer. ```gdscript extends Node2D const COLS: int = 8 const ROWS: int = 6 const CELL: int = 40 var cells: Array = [] func _ready() -> void: var rng := RandomNumberGenerator.new() rng.seed = 2468 for y in range(ROWS): var row: Array[int] = [] for x in range(COLS): var blocked: bool = y != 0 and x != COLS - 1 and rng.randf() < 0.25 row.append(1 if blocked else 0) cells.append(row) queue_redraw() func _draw() -> void: for y in range(cells.size()): for x in range(cells[y].size()): var color := Color.DIM_GRAY if cells[y][x] == 1 else Color.BEIGE draw_rect(Rect2(x * CELL, y * CELL, CELL - 2, CELL - 2), color) ```

Validated inventory and checkpoint data

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

Scene and node setup

Attach to a Node named SaveData. This is a separate file from C-SAVE and only reads fixed known scalar fields. get_checkpoint_data returns plain data, not live node references. When applying a loaded checkpoint, the assignment maps checkpoint ID to a teacher-approved safe Marker2D, never to a filename supplied by the save.

extends Node
const PATH: String = "user://seed_station_v1.json"
func defaults() -> Dictionary:
    return {"version": 1, "seed": 0, "water": 0, "checkpoint": "start"}
func _bounded_count(value: Variant) -> int:
    if value is int or value is float:
        return clampi(int(value), 0, 99)
    return 0
func validate(raw: Variant) -> Dictionary:
    var clean := defaults()
    if not raw is Dictionary:
        return clean
    var data: Dictionary = raw
    if data.get("version", 0) != 1:
        return clean
    clean["seed"] = _bounded_count(data.get("seed", 0))
    clean["water"] = _bounded_count(data.get("water", 0))
    var checkpoint: Variant = data.get("checkpoint", "start")
    if checkpoint is String and checkpoint in ["start", "greenhouse"]:
        clean["checkpoint"] = checkpoint
    return clean
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

  • Missing file returns defaults.
  • Negative count becomes zero; count 1000 becomes 99.
  • Unknown checkpoint becomes start.
  • Malformed JSON, arrays and unsupported versions return safe defaults.

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 readable patrol/chase/return state machine

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

Scene and node setup

Create CharacterBody2D Guard with visible circle or polygon and matching collider. Layer 4 mask 2 for walls. Attach script and assign target to your Player instance in Inspector. Level is one open rectangle; this is steering, not navigation around walls. Damage remains a separate sensor/manager event. Draw detection radii on a design diagram before tuning values.

extends CharacterBody2D
enum Mode { PATROL, CHASE, RETURN }
@export var target: Node2D
@export var speed: float = 70.0
var mode: Mode = Mode.PATROL
var home: Vector2
var patrol_target: Vector2
func _ready() -> void:
    home = global_position
    patrol_target = home + Vector2(80, 0)
func _physics_process(delta: float) -> void:
    if not is_instance_valid(target):
        velocity = Vector2.ZERO
        return
    var distance: float = global_position.distance_to(target.global_position)
    if mode != Mode.CHASE and distance < 120.0:
        mode = Mode.CHASE
    elif mode == Mode.CHASE and distance > 180.0:
        mode = Mode.RETURN
    var destination: Vector2
    if mode == Mode.CHASE:
        destination = target.global_position
    elif mode == Mode.RETURN:
        destination = home
        if global_position.distance_to(home) <= maxf(3.0, speed * delta):
            mode = Mode.PATROL
    else:
        destination = patrol_target
        if global_position.distance_to(patrol_target) <= maxf(3.0, speed * delta):
            patrol_target = home if patrol_target != home else home + Vector2(80, 0)
    var offset := destination - global_position
    velocity = offset.normalized() * minf(speed, offset.length() / maxf(delta, 0.001))
    move_and_slide()

Checks to run in the editor

  • Far player: guard patrols 80 pixels from home.
  • Within 120 pixels: chase.
  • Beyond 180 pixels: return, then patrol.
  • Missing target stops safely rather than throwing an invalid-instance error.

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 deterministic grid with a guaranteed clear route

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

Scene and node setup

Attach to Node2D GridLab. This example draws, not physics, so the assignment adds matching wall collision only after validation. Grid is 8 columns by 6 rows at 40 pixels per cell. Row 0 and column 7 are a guaranteed clear route from (0,0) to (7,5). RNG seed is a nonpersonal integer.

extends Node2D
const COLS: int = 8
const ROWS: int = 6
const CELL: int = 40
var cells: Array = []
func _ready() -> void:
    var rng := RandomNumberGenerator.new()
    rng.seed = 2468
    for y in range(ROWS):
        var row: Array[int] = []
        for x in range(COLS):
            var blocked: bool = y != 0 and x != COLS - 1 and rng.randf() < 0.25
            row.append(1 if blocked else 0)
        cells.append(row)
    queue_redraw()
func _draw() -> void:
    for y in range(cells.size()):
        for x in range(cells[y].size()):
            var color := Color.DIM_GRAY if cells[y][x] == 1 else Color.BEIGE
            draw_rect(Rect2(x * CELL, y * CELL, CELL - 2, CELL - 2), color)

Checks to run in the editor

  • Same seed and version produce same grid.
  • All cells on top row and rightmost column are empty.

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.

Finish ordinary richer-system behavior — evidence task

  1. 1. Complete and test one full ordinary sequence for the chosen system.
  2. 2. Write the exact reproduction steps.

Deliverable. Richer-system ordinary-path source and reproduction log.

Acceptance checks

  • VGC-L157-T1. The sequence works through the main game, not only a lab.
  • VGC-L157-T2. The feature’s claimed scope matches evidence.

Understanding question. Why must the system be tested through the main game?

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 focused test scene from week 30 to compare isolated behavior with the main game. Keep one explicit state owner. Start with the first assigned task and re-run its acceptance test before adding the remaining feature.

Optional extra. Add one validated field, AI cue or generation constraint only after existing tests pass. Document one changed parameter, your prediction, and the observed effect; optional, not required for completion.

Turn in typed notes and a JPEG, PNG, or WebP screenshot. One https address is stored as text and is not opened, extracted, or run. An MP3, WAV, M4A, MP4, or WebM file up to 4 MB can show a demo. The demo does not replace editable source. Zip and code files are refused. If there is no private link, keep the project on the family computer and review the code in person.

  • Your first 2D game

    Free public tutorial; no account; external asset download is optional, not used by this course.

    · Opening this link does not submit the lesson.

This is a preview. A parent assigns the lesson and chooses the due date after the student is enrolled. The answer key is not on this page.

Print this lesson