harvest/game/scripts/save_game.gd
Forrest fa7f67fe04 Task #16: per-player pouch in co-op
Each scarecrow carries its own pouch (ResourceStore.pouches by avatar
slot; slot 0 is the solo player / host, `pouch` stays slot 0's), with one
shared pouch_capacity so a Bigger pouch grows both. The shed stays shared.

- Gathering, the shed drop-off, repair, upgrade-in-place, patching,
  building and buying all act on the acting avatar's slot. The host pays
  the partner's "place" and "buy" requests from P2's pouch and the shed.
- The partner's build mode, build hotbar, shop menus and materials HUD
  check affordability against P2's pouch (FarmSim.set_local).
- Alien Goop goes to the killer's pouch: FarmSim sets
  EnemySystem.attacker around each avatar's combat step and shots carry
  their shooter's slot; bomb/turret kills go to the nearest scarecrow.
  The replica no longer rolls goop locally.
- When the partner leaves, their pouch goes into the shed (and is named
  in the toast); a co-op save continued alone banks P2's pouch at morning.
- FarmState.VERSION 7 (resources.partner_pouch) with a v6 migration;
  CoopSession.PROTOCOL 4.
- Tests: per-slot store rules, v6 save migration, and test_coop cases for
  separate gathering, no cross-banking in the shed, own-pouch paying,
  shared capacity, goop credit and leaving. test_coop's crowd case now
  resets the loopback's drop counter so earlier traffic can't change
  which messages it loses.
- Docs: COOP.md and RULES.md no longer say the pouch is shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:06:25 -04:00

137 lines
5.4 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
6:
# Version 7 gives each scarecrow its own pouch (#16): the old shared one becomes player
# 1's (resources.pouch, unchanged), and player 2's starts empty.
var res: Variant = out.get("resources")
if res is Dictionary and not (res as Dictionary).has("partner_pouch"):
var empty := {}
for m in ResourceStore.MATERIALS:
empty[m] = 0
res["partner_pouch"] = empty
out["version"] = 7
_:
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