class_name FarmState extends RefCounted ## The single source of truth for everything that persists through the vacation: farm assets, ## scarecrow health, campaign progress, and the nightly records. Scene nodes only display it. ## to_dict() / from_dict() round-trip every field, also through JSON (the morning retry ## snapshot and the save game, SaveGame). Crops and animals are per-unit records (lost ids, 1..total); ## supplies are the supply shed's stock of construction materials (the shed and each scarecrow's ## pouch live in resources). Gather points below full, bought upgrades, and the built structures ## are kept too. ## 7: a pouch per scarecrow (resources.partner_pouch, #16). const VERSION := 7 const KEYS: Array[String] = [ "night", "nights_survived", "phase", "phase_time_left", "scarecrow_max_hp", "scarecrow_hp", "crops_total", "lost_crops", "animals_total", "lost_animals", "penned_animals", "supplies_total", "shed_raided", "resources", "gather_charges", "upgrades", "structures", "next_structure_id", "night_events", "night_log", "coop", "partner_max_hp", "partner_hp", ] const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp", "level"] ## Events counted from the morning to the end of the dawn grace, copied into the night's log ## entry when it closes. Theft: supply events count material units, the others crop units or ## animals. Then enemies killed by type and those that escaped with loot; the scarecrow's damage ## taken (HP) and patches; structures built, damaged (HP lost), destroyed, and repaired; ## upgrades bought; and materials gathered (into the pouch) and spent, per material. const EVENTS: Array[String] = [ "crops_stolen", "crops_recovered", "animals_stolen", "animals_strayed", "animals_recovered", "supplies_stolen", "supplies_recovered", "supplies_lost", "killed_crow", "killed_thief", "killed_breaker", "killed_ufo", "escaped", "scarecrow_damage", "patches", "structures_built", "structures_damaged", "structures_destroyed", "repairs", "upgrades_bought", "gathered_wood", "gathered_scrap", "gathered_straw", "gathered_alien_goop", "spent_wood", "spent_scrap", "spent_straw", "spent_alien_goop", ] ## The keys of a night_log entry: the night, crops and animals lost, then every EVENTS key. const LOG_KEYS: Array[String] = [ "night", "crops_lost", "animals_lost", "crops_stolen", "crops_recovered", "animals_stolen", "animals_strayed", "animals_recovered", "supplies_stolen", "supplies_recovered", "supplies_lost", "killed_crow", "killed_thief", "killed_breaker", "killed_ufo", "escaped", "scarecrow_damage", "patches", "structures_built", "structures_damaged", "structures_destroyed", "repairs", "upgrades_bought", "gathered_wood", "gathered_scrap", "gathered_straw", "gathered_alien_goop", "spent_wood", "spent_scrap", "spent_straw", "spent_alien_goop", ] ## Current night (1-based). The morning, day, dusk, night, and dawn of a cycle all belong to it. var night: int = 1 var nights_survived: int = 0 var phase: CampaignController.Phase = CampaignController.Phase.MORNING ## Game seconds left in a timed phase (0 in the untimed morning and terminal phases). var phase_time_left: float = 0.0 var scarecrow_max_hp: int = 10 var scarecrow_hp: int = 10 ## Co-op (a second scarecrow, player 2, is on the farm) and that scarecrow's health. Upgrades to ## max health apply to both. In co-op a scarecrow at 0 HP is out until the morning, and only both ## down at once is a Game Over. var coop := false var partner_max_hp: int = 10 var partner_hp: int = 10 ## Per category: the starting count (0 = not in play) and what remains on the farm. var crops_total: int = 0 ## Ids of the crop units that are gone for good (carried off the farm), sorted. var lost_crops := PackedInt32Array() var animals_total: int = 0 ## Ids of the animals that are gone for good (carried or wandered off the farm), sorted. var lost_animals := PackedInt32Array() ## Ids of the animals currently penned (#12): led into a built pen (or auto-returned there after ## being dropped), so sync_from_state() keeps them LootSystem.Status.HOME each morning; an id not ## here (and not lost) is loose, grazing outside the pen until led in. Never overlaps lost_animals. var penned_animals := PackedInt32Array() ## The shed's stock when the vacation started (0 = supplies not in play). var supplies_total: int = 0 ## The shed was last emptied by thieves (not by spending). Only then do empty supplies count ## toward a stripped farm (D2); storing anything clears it (settle_supplies). var shed_raided := false ## Material units carried off by thieves or lying dropped, still on the farm. Not saved: the dawn ## grace ends with none (LootSystem keeps it). var supplies_in_transit: int = 0 ## Crop units still on the farm (home, targeted, carried, or dropped). Derived from lost_crops; ## change it through lose_crop(). var crops: int: get: return crops_total - lost_crops.size() set(_value): push_error("FarmState.crops is derived from lost_crops; use lose_crop()") ## Animals still on the farm (in the pen, loose, following, or carried). Derived from lost_animals. var animals: int: get: return animals_total - lost_animals.size() set(_value): push_error("FarmState.animals is derived from lost_animals; use lose_animal()") ## Supplies still on the farm: the shed's stock plus what thieves carry or dropped. var supplies: int: get: return resources.shed_total() + supplies_in_transit set(_value): push_error("FarmState.supplies is derived from the shed's stock") ## The materials in the supply shed and in each scarecrow's pouch (by avatar slot). var resources := ResourceStore.new() ## Charges of the gather points that are below full (GatherNode name -> charges left); a point ## missing here is full. var gather_charges: Dictionary = {} ## Bought upgrades (id -> level). var upgrades: Dictionary = {} ## Built structures: {"id", "type", "x", "z" (world position, on the 0.5 m build grid), "rot" ## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow), "level" ## (1-3; account-wide upgrades are tracked separately, above -- this is per placed instance, #10)}. var structures: Array[Dictionary] = [] var next_structure_id: int = 1 ## Event counts of the day and night in progress (EVENTS keys), since this morning. var night_events: Dictionary = {} ## One entry per completed night, closed when its dawn ends (LOG_KEYS). var night_log: Array[Dictionary] = [] static func create(cfg: GameConfig) -> FarmState: var s := FarmState.new() s.scarecrow_max_hp = cfg.scarecrow_max_hp s.scarecrow_hp = cfg.scarecrow_max_hp s.partner_max_hp = cfg.scarecrow_max_hp s.partner_hp = cfg.scarecrow_max_hp s.crops_total = cfg.start_crops s.animals_total = cfg.start_animals s.resources.pouch_capacity = cfg.pouch_capacity s.resources.shed = {"wood": cfg.start_wood, "scrap": cfg.start_scrap, "straw": cfg.start_straw, "alien_goop": cfg.start_alien_goop} s.supplies_total = s.resources.shed_total() for e in cfg.start_structures: var t := String(e["type"]) s.structures.append({"id": s.next_structure_id, "type": t, "x": float(e["x"]), "z": float(e["z"]), "rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t), "level": 1}) s.next_structure_id += 1 return s func is_crop_lost(unit_id: int) -> bool: return lost_crops.has(unit_id) ## Marks a crop unit as gone for good. Returns false for unknown or already-lost units. func lose_crop(unit_id: int) -> bool: if unit_id < 1 or unit_id > crops_total or lost_crops.has(unit_id): return false lost_crops.append(unit_id) lost_crops.sort() return true func lose_all_crops() -> void: for id in range(1, crops_total + 1): lose_crop(id) func is_animal_lost(id: int) -> bool: return lost_animals.has(id) ## Marks an animal as gone for good. Returns false for unknown or already-lost animals. func lose_animal(id: int) -> bool: if id < 1 or id > animals_total or lost_animals.has(id): return false lost_animals.append(id) lost_animals.sort() unpen_animal(id) return true func lose_all_animals() -> void: for id in range(1, animals_total + 1): lose_animal(id) func is_animal_penned(id: int) -> bool: return penned_animals.has(id) ## Marks an animal as penned (led into the pen, or auto-returned there). Returns false for an ## unknown, already-penned, or lost animal. func pen_animal(id: int) -> bool: if id < 1 or id > animals_total or penned_animals.has(id) or lost_animals.has(id): return false penned_animals.append(id) penned_animals.sort() return true ## Marks an animal as loose again. Returns false if it wasn't penned. func unpen_animal(id: int) -> bool: var i := penned_animals.find(id) if i < 0: return false penned_animals.remove_at(i) return true ## Debug and tests: every surviving animal penned at once (the old always-in-the-pen behavior). func pen_all_animals() -> void: for id in range(1, animals_total + 1): pen_animal(id) ## Debug and tests: every asset gone, the shed emptied by thieves. func strip() -> void: lose_all_crops() lose_all_animals() for m in ResourceStore.MATERIALS: resources.shed[m] = 0 supplies_in_transit = 0 shed_raided = true func record_event(key: String, amount: int = 1) -> void: night_events[key] = int(night_events.get(key, 0)) + amount ## Pays a cost from the payer's pouch (its avatar slot; 0 solo) and the shed (ResourceStore.pay) ## and counts what was spent. Every purchase (building, repairs, patching, upgrades) goes through ## here. func pay(cost: Dictionary, slot: int = 0) -> bool: if not resources.pay(cost, slot): return false for m in cost: if int(cost[m]) > 0: record_event("spent_" + String(m), int(cost[m])) return true ## Every night_log entry's EVENTS key added up (plus crops_lost and animals_lost). func totals() -> Dictionary: var out := {} for key in LOG_KEYS: if key != "night": out[key] = 0 for entry in night_log: for key in out: out[key] += int(entry.get(key, 0)) return out ## Called every tick before the outcome check: once the shed holds anything again, it no longer ## counts as raided. func settle_supplies() -> void: if shed_raided and resources.shed_total() > 0: shed_raided = false ## D2: every category in play is gone. Categories not in play are ignored. Supplies only count ## as gone when thieves emptied the shed: spending the last materials doesn't strip the farm. func is_stripped() -> bool: var in_play := false if crops_total > 0: in_play = true if crops > 0: return false if animals_total > 0: in_play = true if animals > 0: return false if supplies_total > 0: in_play = true if supplies > 0 or not shed_raided: return false return in_play func asset_counts() -> PackedInt32Array: return PackedInt32Array([crops, animals, supplies]) ## Records the night that just ended, given the asset counts when it started, and clears the ## night's event counts. Crops and animals lost are what's gone since then; supplies lost are the ## units carried off (the shed's stock also changes by storing and spending). func log_night(start: PackedInt32Array) -> void: var now := asset_counts() if start.size() != now.size(): start = now var entry := { "night": night, "crops_lost": maxi(start[0] - now[0], 0), "animals_lost": maxi(start[1] - now[1], 0), } for key in EVENTS: entry[key] = int(night_events.get(key, 0)) night_log.append(entry) night_events.clear() func to_dict() -> Dictionary: var entries: Array = [] for entry in night_log: entries.append(entry.duplicate()) var lost: Array = [] for id in lost_crops: lost.append(id) var lost_a: Array = [] for id in lost_animals: lost_a.append(id) var penned: Array = [] for id in penned_animals: penned.append(id) return { "version": VERSION, "night": night, "nights_survived": nights_survived, "phase": int(phase), "phase_time_left": phase_time_left, "scarecrow_max_hp": scarecrow_max_hp, "scarecrow_hp": scarecrow_hp, "crops_total": crops_total, "lost_crops": lost, "animals_total": animals_total, "lost_animals": lost_a, "penned_animals": penned, "supplies_total": supplies_total, "shed_raided": shed_raided, "resources": resources.to_dict(), "gather_charges": gather_charges.duplicate(), "upgrades": upgrades.duplicate(), "structures": _structures_copy(), "next_structure_id": next_structure_id, "night_events": night_events.duplicate(), "night_log": entries, "coop": coop, "partner_max_hp": partner_max_hp, "partner_hp": partner_hp, } ## Rebuilds a state from to_dict() output (numbers may arrive as floats after JSON). Returns ## null for another version, missing keys, or values that break the state's invariants. static func from_dict(d: Dictionary) -> FarmState: if int(d.get("version", -1)) != VERSION: return null for key in KEYS: if not d.has(key): return null var phase_value := int(d["phase"]) if not CampaignController.Phase.values().has(phase_value): return null if not (d["night_log"] is Array and d["lost_crops"] is Array and d["lost_animals"] is Array and d["penned_animals"] is Array and d["night_events"] is Dictionary and d["gather_charges"] is Dictionary and d["upgrades"] is Dictionary and d["structures"] is Array): return null var store := ResourceStore.from_dict(d["resources"]) if store == null: return null var s := FarmState.new() s.night = int(d["night"]) s.nights_survived = int(d["nights_survived"]) s.phase = phase_value as CampaignController.Phase s.phase_time_left = float(d["phase_time_left"]) s.scarecrow_max_hp = int(d["scarecrow_max_hp"]) s.scarecrow_hp = int(d["scarecrow_hp"]) s.coop = bool(d["coop"]) s.partner_max_hp = int(d["partner_max_hp"]) s.partner_hp = int(d["partner_hp"]) s.crops_total = int(d["crops_total"]) for id in d["lost_crops"]: if not s.lose_crop(int(id)): return null # unknown or duplicate unit id s.animals_total = int(d["animals_total"]) for id in d["lost_animals"]: if not s.lose_animal(int(id)): return null for id in d["penned_animals"]: if not s.pen_animal(int(id)): return null # unknown, duplicate, or already-lost animal id s.supplies_total = int(d["supplies_total"]) s.shed_raided = bool(d["shed_raided"]) s.resources = store for key in d["gather_charges"]: if int(d["gather_charges"][key]) < 0: return null s.gather_charges[String(key)] = int(d["gather_charges"][key]) for key in d["upgrades"]: if int(d["upgrades"][key]) < 0: return null s.upgrades[String(key)] = int(d["upgrades"][key]) s.next_structure_id = int(d["next_structure_id"]) var ids := {} for raw in d["structures"]: if not raw is Dictionary: return null var e := {} for key in STRUCTURE_KEYS: if not (raw as Dictionary).has(key): return null e["id"] = int(raw["id"]) e["type"] = String(raw["type"]) e["x"] = float(raw["x"]) e["z"] = float(raw["z"]) e["rot"] = int(raw["rot"]) e["hp"] = int(raw["hp"]) e["level"] = int(raw["level"]) if e["id"] < 1 or e["id"] >= s.next_structure_id or ids.has(e["id"]) or e["type"] == "" \ or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0 or e["level"] < 1 or e["level"] > 3: return null ids[e["id"]] = true s.structures.append(e) for key in d["night_events"]: if not EVENTS.has(String(key)): return null s.night_events[String(key)] = int(d["night_events"][key]) for raw in d["night_log"]: if not raw is Dictionary: return null var entry := {} for key in LOG_KEYS: if not (raw as Dictionary).has(key): return null entry[key] = int(raw[key]) s.night_log.append(entry) return s if s.is_valid() else null ## The structure record with this id, or an empty dictionary. func structure(id: int) -> Dictionary: for e in structures: if int(e["id"]) == id: return e return {} func _structures_copy() -> Array: var out: Array = [] for e in structures: out.append(e.duplicate()) return out func is_valid() -> bool: return night >= 1 and nights_survived >= 0 and nights_survived <= night \ and phase_time_left >= 0.0 \ and scarecrow_max_hp >= 1 and scarecrow_hp >= 0 and scarecrow_hp <= scarecrow_max_hp \ and partner_max_hp >= 1 and partner_hp >= 0 and partner_hp <= partner_max_hp \ and crops_total >= 0 and lost_crops.size() <= crops_total \ and animals_total >= 0 and lost_animals.size() <= animals_total \ and penned_animals.size() <= animals_total - lost_animals.size() \ and supplies_total >= 0 and supplies_in_transit >= 0