harvest/game/scripts/save_game.gd
2026-10-04 12:07:36 -04:00

108 lines
4.2 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
_:
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