harvest/game/tests/test_save.gd
Forrest 62324ff4b1 Task #10: per-instance Turret/Tar Patch leveling (L1-L3)
Adds a per-placed-structure "level" (1-3) to automated_defense and
slowing_trap, upgraded independently (not account-wide) by holding
interact at that specific structure, by day, once it's undamaged
(repair still takes priority while it isn't), for a config-tunable
per-level cost.

Turret L2 fires turret_level_fire_mult (3x, matching the live Rapid
Fire multiplier) as often; L3 keeps that rate and fires
turret_l3_projectiles shots at once in a fan. A tar patch's trigger
footprint and visual grow by trap_level_size_mult per level (L2
double, L3 triple its L1 size); a bigger footprint that would overlap
a neighbor or the world refuses the upgrade with a reason.

FarmState.VERSION bumps 5->6 (STRUCTURE_KEYS gains "level"; migrate()
backfills level 1 on older saves, following the v2->v3 precedent for
night_log). Co-op: an upgrade is driven the same way repair already
is -- entirely host-side, off the partner's held interact button, no
new "req" case -- so the only wire change is forwarding the upgrade
channel's target/progress in the avatar snapshot, same as repair's.

New test_structures.gd coverage: fire interval and projectile count
per turret level, tar patch footprint per level, each proven
independently for two separately-placed structures of the same type,
plus the upgrade rules (repair-first, room, afford) and that level
survives a save/retry round trip.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 15:48:19 -04:00

253 lines
12 KiB
GDScript

extends RefCounted
## Saving and settings without the farm scene: a save written and read back reproduces the farm
## state field for field; missing, damaged, newer, and too-old saves are refused with a reason
## and version 2 saves are upgraded; the campaign autosaves every morning, a retry restores that
## morning, and finishing the vacation deletes the save; settings persist, fall back on bad
## values, and apply to the audio buses, the dead zones, and the config; and the final
## assessment's score and tiers.
const P := CampaignController.Phase
const SAVE := "user://test_savegame.json"
const SETTINGS := "user://test_settings.cfg"
func run(r: GameTestRunner) -> void:
_clean()
_round_trip(r)
_bad_saves(r)
_migration(r)
_autosave(r)
_settings(r)
_assessment(r)
_clean()
func _clean() -> void:
for p in [SAVE, SAVE + ".tmp", SETTINGS]:
if FileAccess.file_exists(p):
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
## A morning with something in every field.
static func busy_state(cfg: GameConfig) -> FarmState:
var s := FarmState.create(cfg)
s.night = 3
s.nights_survived = 2
s.phase = P.MORNING
s.scarecrow_max_hp = 12
s.scarecrow_hp = 7
s.lose_crop(4)
s.lose_crop(17)
s.lose_animal(2)
s.resources.shed = {"wood": 13, "scrap": 2, "straw": 21}
s.resources.pouch = {"wood": 0, "scrap": 3, "straw": 1}
s.gather_charges = {"DeadTree": 1, "Haystack": 0}
s.upgrades = {"rapid_fire": 1, "sticky_tar": 1}
s.structures.append({"id": s.next_structure_id, "type": "fence", "x": 30.5, "z": -18.5, "rot": 3, "hp": 11, "level": 1})
s.next_structure_id += 1
s.structures.append({"id": s.next_structure_id, "type": "slowing_trap", "x": 12.0, "z": -7.25, "rot": 0, "hp": 2, "level": 2})
s.next_structure_id += 1
for n in [1, 2]:
var e := {"night": n, "crops_lost": n, "animals_lost": n - 1}
for k in FarmState.EVENTS:
e[k] = n * 3 + FarmState.EVENTS.find(k)
s.night_log.append(e)
return s
func _round_trip(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var s := busy_state(cfg)
var before := s.to_dict()
var err := SaveGame.write(before, SAVE)
r.check(err == OK and FileAccess.file_exists(SAVE) and not FileAccess.file_exists(SAVE + ".tmp"),
"the save is written (through a temporary file that's renamed into place)")
var loaded := SaveGame.read(SAVE)
r.check(loaded.status == SaveGame.Status.OK and loaded.state != null and loaded.message == "" and loaded.saved_at != "",
"and reads back (saved at %s)" % loaded.saved_at)
if loaded.state == null:
return
var after := loaded.state.to_dict()
var differ: Array[String] = []
for key in before:
if JSON.stringify(before[key], "", true, true) != JSON.stringify(after.get(key), "", true, true):
differ.append(key)
r.check(differ.is_empty() and before.size() == after.size(), "saving then loading reproduces the farm state field for field (differ: %s)" % [differ])
r.check(loaded.state.crops == s.crops and loaded.state.animals == s.animals and loaded.state.supplies == s.supplies
and loaded.state.structures[-2]["x"] == 30.5 and loaded.state.structures[-1]["z"] == -7.25
and loaded.state.night_log[1]["killed_crow"] == s.night_log[1]["killed_crow"],
"derived counts, positions, and the nightly records survive")
func _bad_saves(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
_clean()
var missing := SaveGame.read(SAVE)
r.check(missing.status == SaveGame.Status.MISSING and missing.state == null and missing.message == "No saved vacation",
"no save: MISSING")
_write_text("{ this is not json")
var garbage := SaveGame.read(SAVE)
r.check(garbage.status == SaveGame.Status.CORRUPT and garbage.state == null and garbage.message.contains("damaged"),
"unreadable JSON: CORRUPT ('%s')" % garbage.message)
_write_text(JSON.stringify({"game": "another-game", "state": {}}))
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "another game's file: CORRUPT")
var d := busy_state(cfg).to_dict()
d["scarecrow_hp"] = 99 # more than its maximum
SaveGame.write(d, SAVE)
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a state that breaks the rules: CORRUPT")
d = busy_state(cfg).to_dict()
d["phase"] = int(P.NIGHT)
SaveGame.write(d, SAVE)
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a save that isn't a morning: CORRUPT")
d = busy_state(cfg).to_dict()
d.erase("night_log")
SaveGame.write(d, SAVE)
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a missing field: CORRUPT")
d = busy_state(cfg).to_dict()
d["version"] = FarmState.VERSION + 1
SaveGame.write(d, SAVE)
var newer := SaveGame.read(SAVE)
r.check(newer.status == SaveGame.Status.NEWER and newer.state == null and newer.version == FarmState.VERSION + 1
and newer.message.contains("newer"), "a save from a newer version: NEWER, not loaded")
d["version"] = 1
SaveGame.write(d, SAVE)
var old := SaveGame.read(SAVE)
r.check(old.status == SaveGame.Status.OLD and old.state == null and old.message.contains("older"),
"a save from version 1 (no way forward): OLD, not loaded")
func _migration(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var s := busy_state(cfg)
var d := s.to_dict()
d["version"] = 2
var v2_keys := ["night", "crops_lost", "animals_lost", "supplies_lost", "crops_stolen", "crops_recovered",
"animals_stolen", "animals_strayed", "animals_recovered", "supplies_stolen", "supplies_recovered"]
for e: Dictionary in d["night_log"]:
for k in e.keys():
if not v2_keys.has(k):
e.erase(k)
SaveGame.write(d, SAVE)
var loaded := SaveGame.read(SAVE)
r.check(loaded.status == SaveGame.Status.OK and loaded.version == 2, "a version 2 save is upgraded and loads")
if loaded.state == null:
return
var e: Dictionary = loaded.state.night_log[1]
r.check(e["crops_stolen"] == s.night_log[1]["crops_stolen"] and e["killed_crow"] == 0 and e["gathered_wood"] == 0
and loaded.state.scarecrow_hp == 7 and loaded.state.structures.size() == s.structures.size(),
"keeping what it had and counting the new nightly records from zero")
func _autosave(r: GameTestRunner) -> void:
_clean()
var c := r.make_campaign()
c.save_path = SAVE
c.new_campaign()
var first := SaveGame.read(SAVE)
r.check(first.status == SaveGame.Status.OK and first.state.night == 1 and c.last_save_error == OK,
"a new vacation is saved at once (the morning of night 1)")
GameTestRunner.run_until(c, P.DAY)
c.state.resources.shed["wood"] = 99
GameTestRunner.run_until(c, P.NIGHT)
GameTestRunner.run_until(c, P.MORNING)
var second := SaveGame.read(SAVE)
r.check(second.status == SaveGame.Status.OK and second.state.night == 2 and second.state.resources.shed["wood"] == 99
and second.state.night_log.size() == 1, "every morning is autosaved (now the morning of night 2)")
var morning := c.state.to_dict()
GameTestRunner.run_until(c, P.NIGHT)
c.state.scarecrow_hp = 1
GameTestRunner.lose_crops(c.state, 5)
r.check(c.retry_night() and JSON.stringify(c.state.to_dict(), "", true, true) == JSON.stringify(morning, "", true, true)
and JSON.stringify(SaveGame.read(SAVE).state.to_dict(), "", true, true) == JSON.stringify(morning, "", true, true),
"retry restores the morning state, which is also what's saved")
var guard := 0
while not c.is_over() and guard < 100:
GameTestRunner.run_until(c, P.MORNING if c.state.phase != P.MORNING else P.DAY)
guard += 1
r.check(c.outcome == CampaignController.Outcome.VACATION_COMPLETE and not SaveGame.exists(SAVE),
"finishing the vacation deletes the save (nothing left to continue)")
c.queue_free()
var quiet := r.make_campaign()
r.check(quiet.save_path == "" and not SaveGame.exists(SAVE), "without a save path nothing is written")
quiet.queue_free()
func _settings(r: GameTestRunner) -> void:
_clean()
var fresh := GameSettings.load_from(SETTINGS)
r.check(fresh.volume == GameSettings.DEFAULT_VOLUME and fresh.show_tips and fresh.vsync and not fresh.fullscreen
and fresh.resolution_scale == 1.0, "no settings file: the defaults")
var g := GameSettings.new()
g.volume = {"Master": 0.5, "Music": 0.25, "SFX": 0.0, "Ambience": 1.0, "Voice": 0.6}
g.move_dead_zone = 0.35
g.aim_dead_zone = 0.15
g.fullscreen = true
g.vsync = false
g.resolution_scale = 0.75
g.show_tips = false
g.player_name = "Ana"
g.microphone = false
r.check(g.save_to(SETTINGS) == OK, "settings save")
var back := GameSettings.load_from(SETTINGS)
r.check(back.volume == g.volume and back.move_dead_zone == 0.35 and back.aim_dead_zone == 0.15 and back.fullscreen
and not back.vsync and back.resolution_scale == 0.75 and not back.show_tips and back.player_name == "Ana"
and not back.microphone, "and load back unchanged (co-op name and microphone too)")
var f := ConfigFile.new()
f.set_value("audio", "master", 7.0)
f.set_value("audio", "music", "loud")
f.set_value("display", "fullscreen", "yes")
f.set_value("display", "resolution_scale", 0.1)
f.save(SETTINGS)
var odd := GameSettings.load_from(SETTINGS)
r.check(odd.volume["Master"] == 1.0 and odd.volume["Music"] == GameSettings.DEFAULT_VOLUME["Music"] and not odd.fullscreen
and odd.resolution_scale == 0.5, "out-of-range and wrong-typed values are clamped or fall back")
var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
g.apply(null, cfg)
var music := AudioServer.get_bus_index("Music")
var sfx := AudioServer.get_bus_index("SFX")
r.check(music >= 0 and sfx >= 0 and AudioServer.get_bus_index("Ambience") >= 0, "the audio buses exist (Master, Music, SFX, Ambience)")
r.check(is_equal_approx(AudioServer.get_bus_volume_db(music), linear_to_db(0.25)) and AudioServer.is_bus_mute(sfx)
and not AudioServer.is_bus_mute(music), "volumes apply to the buses (and zero mutes)")
r.check(is_equal_approx(InputMap.action_get_deadzone("move_left"), 0.35) and is_equal_approx(cfg.aim_dead_zone, 0.15),
"dead zones apply to the move actions and the aim")
GameSettings.new().apply(null, cfg) # back to the defaults for the other suites
func _assessment(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var s := FarmState.create(cfg)
GameTestRunner.lose_crops(s, 3)
s.lose_animal(1)
s.lose_animal(2)
var e := {"night": 1, "crops_lost": 3, "animals_lost": 2}
for k in FarmState.EVENTS:
e[k] = 0
e["gathered_wood"] = 50
e["gathered_straw"] = 40
e["supplies_lost"] = 4
s.night_log.append(e)
var a := Assessment.of(s, cfg)
var handled := s.supplies_total + 90
var want := roundi(100.0 * (0.5 * 27.0 / 30.0 + 0.3 * 6.0 / 8.0 + 0.2 * (1.0 - 4.0 / handled)))
r.check(a["score"] == want and a["tier"] == "Bumper crop" and a["supplies_handled"] == handled and a["supplies_lost"] == 4,
"the score weighs each category kept (%d points, %s)" % [a["score"], a["tier"]])
var perfect := Assessment.of(FarmState.create(cfg), cfg)
r.check(perfect["score"] == 100 and perfect["tier"] == "Blue-ribbon harvest" and perfect["text"] != "", "nothing lost: 100, the top tier")
s.lose_all_crops()
s.lose_all_animals()
r.check(Assessment.of(s, cfg)["tier"] == "Hanging by a thread", "little left: the bottom tier")
var no_animals := FarmState.create(cfg)
no_animals.animals_total = 0
GameTestRunner.lose_crops(no_animals, 15)
var b := Assessment.of(no_animals, cfg)
r.check(not (b["parts"] as Dictionary).has("animals") and b["score"] == roundi(100.0 * (0.5 * 0.5 + 0.2) / 0.7),
"categories not in play are left out and the weights renormalized")
r.check(Assessment.enemies_line({"killed_crow": 3, "killed_thief": 1, "killed_breaker": 0}) == "3 crows and 1 alien"
and Assessment.materials_line({"spent_wood": 4, "spent_straw": 2}, "spent_") == "4 wood, 2 straw"
and Assessment.materials_line({}, "gathered_") == "nothing", "the totals read as words")
func _write_text(text: String) -> void:
var f := FileAccess.open(SAVE, FileAccess.WRITE)
f.store_string(text)
f.close()