harvest/game/scripts/save_game.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

127 lines
5 KiB
GDScript

class_name SaveGame
extends RefCounted
## The vacation's save file: the farm state of the latest morning as JSON (full float precision)
## at user://savegame.json. CampaignController writes it every MORNING when its save_path is set
## (Main sets it; tests and the farm scene on its own don't), so Continue always resumes at that
## morning, and a Game Over leaves the failed night's morning there to retry. Finishing the
## vacation deletes it.
##
## Reading it back never crashes and never loads something broken: a missing file, unreadable
## JSON, a state that FarmState.from_dict rejects or that isn't a morning, and a save from a newer
## version are reported (Loaded.status) and not loaded. A save from an older version is upgraded
## first (migrate) when there's a known way forward, and reported as OLD when there isn't.
enum Status { OK, MISSING, CORRUPT, OLD, NEWER }
const PATH := "user://savegame.json"
const GAME := "harvest-season"
class Loaded:
var status: Status = Status.MISSING
## The saved farm state (status OK only).
var state: FarmState
## For the player: why it can't be continued ("" when it can).
var message := ""
var saved_at := ""
## The version the file was written with (-1 if unknown).
var version: int = -1
## Writes a FarmState.to_dict() atomically: to path.tmp, then renamed over path.
static func write(state: Dictionary, path: String = PATH) -> Error:
var data := {"game": GAME, "version": FarmState.VERSION, "saved_at": Time.get_datetime_string_from_system(false, true),
"state": state}
var tmp := path + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error()
f.store_string(JSON.stringify(data, "\t", true, true))
f.close()
return DirAccess.rename_absolute(ProjectSettings.globalize_path(tmp), ProjectSettings.globalize_path(path))
static func read(path: String = PATH) -> Loaded:
var out := Loaded.new()
if not FileAccess.file_exists(path):
out.message = "No saved vacation"
return out
var json := JSON.new()
var parsed: Variant = json.data if json.parse(FileAccess.get_file_as_string(path)) == OK else null
if not parsed is Dictionary or String((parsed as Dictionary).get("game", "")) != GAME \
or not (parsed as Dictionary).get("state") is Dictionary:
return _fail(out, Status.CORRUPT, "The saved vacation is damaged and can't be continued")
out.saved_at = String(parsed.get("saved_at", ""))
var d: Dictionary = parsed["state"]
out.version = int(d.get("version", -1))
if out.version > FarmState.VERSION:
return _fail(out, Status.NEWER, "The saved vacation is from a newer version of the game")
if out.version < FarmState.VERSION:
d = migrate(d)
if d.is_empty():
return _fail(out, Status.OLD, "The saved vacation is from an older version and can't be continued")
var s := FarmState.from_dict(d)
if s == null or s.phase != CampaignController.Phase.MORNING:
return _fail(out, Status.CORRUPT, "The saved vacation is damaged and can't be continued")
out.status = Status.OK
out.state = s
return out
## Upgrades a FarmState dictionary from an older VERSION, one version at a time. Returns {} when
## there's no way forward (version 1 predates saving to disk).
static func migrate(d: Dictionary) -> Dictionary:
var out := d.duplicate(true)
while int(out.get("version", -1)) < FarmState.VERSION:
match int(out.get("version", -1)):
2:
# Version 3 counts more per night: kills, damage, building, and materials.
for entry: Variant in out.get("night_log", []):
if entry is Dictionary:
for key in FarmState.LOG_KEYS:
if not (entry as Dictionary).has(key):
entry[key] = 0
out["version"] = 3
3:
# Version 4 adds co-op: a second scarecrow's health.
out["coop"] = false
out["partner_max_hp"] = int(out.get("scarecrow_max_hp", 10))
out["partner_hp"] = int(out.get("scarecrow_max_hp", 10))
out["version"] = 4
4:
# Version 5 adds the Animal Pen's loose/penned state (#12). Older saves always kept
# every surviving animal in the pen, so migrate them in as already penned.
var total := int(out.get("animals_total", 0))
var lost := {} # id (int) -> true; Array.has() won't match a float to an int
for raw: Variant in out.get("lost_animals", []):
lost[int(raw)] = true
var penned: Array = []
for id in range(1, total + 1):
if not lost.has(id):
penned.append(id)
out["penned_animals"] = penned
out["version"] = 5
5:
# Version 6 adds per-instance structure leveling (#10): older structures are level 1.
for entry: Variant in out.get("structures", []):
if entry is Dictionary and not (entry as Dictionary).has("level"):
entry["level"] = 1
out["version"] = 6
_:
return {}
return out
static func exists(path: String = PATH) -> bool:
return FileAccess.file_exists(path)
static func delete(path: String = PATH) -> void:
if FileAccess.file_exists(path):
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
static func _fail(out: Loaded, status: Status, message: String) -> Loaded:
out.status = status
out.message = message
return out