harvest/game/tests/test_nights.gd
Forrest 91b9e52e96 Task #26: upgrade tiers and timed shed stock
Workbench stat upgrades get 3 levels: level L costs costs[id] x
upgrade_cost_growth (1.8) ^ (L - 1), each material rounded up, and opens on
day upgrade_level_days[L - 1] ([1, 8, 16]). Each owned level's "mult"/"add"
entry stacks. Level 1 keeps the user's values and costs (rapid fire 3.0x).
Shed items arrive on set days ("from_day"): corn shooter 1, shurikens 2,
pumpkin bombs 3, potato cannon 6, radar 8, propane torch 10, alien ray 14.

- Upgrades: level(), max_level(), maxed(), cost(cfg, id, level),
  next_cost(), per_level(), text_at(), name_at() (roman numerals),
  from_day(), level_day(), arrived(). owned() stays "level >= 1". blocker()
  adds "Arrives on day N" and "Level N opens on day D"; buy() takes the next
  level and applies that level's side effect; upgrades_bought counts every
  level. FarmState.upgrades keeps id -> level, so saves don't change shape.
- UpgradePanel: "Rapid fire II" with the next level's text and cost, the
  blocker reason, "Max" at the last level; a shed item before its day shows
  its name greyed with "Arrives on day N" ("?" plus the day if hidden). The
  title counts items at their last level. Every level bought jingles.
- Co-op: the host sends "bought" for any level (no wire change; PROTOCOL
  stays 5).
- soak_night.gd buys the lowest next level first across UPGRADE_ORDER.
- Tests: level costs, day gates, stacking, from_day, save/morning/retry/co-op,
  an old {"rapid_fire": 1} save as level 1. Existing tests set the day where
  they buy stock that now arrives later.
- RULES.md Upgrades: per-level effects and costs, stock schedule.

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

287 lines
15 KiB
GDScript

extends RefCounted
## The five-night progression (Step 10): every night plan and debug scenario is valid (markers
## exist and suit the enemy type, types and targets are known, arrivals fit the night), each night
## tests what the plan says it should, the upgrades apply to the systems they change and persist
## (next morning, JSON, retry), and the five nights play back to back to the farmers' return, each
## with its own plan and morning snapshot, everything carrying over.
const P := CampaignController.Phase
const T := ThiefBehavior.State
const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0)
const SCENARIOS := "res://game/resources/scenarios/"
func run(r: GameTestRunner) -> void:
var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
r.root.add_child(farm)
await r.process_frame
await r.physics_frame
var sim := farm.get_node("FarmSim") as FarmSim
sim.set_physics_process(false)
sim.waves.enabled = false
var player := farm.get_node("Player") as PlayerCharacter
player.global_position = AWAY
_validation(r, sim)
_designs(r, sim)
_upgrades(r, sim, player)
_five_nights(r, farm, sim, player)
farm.queue_free()
await r.process_frame
## Every plan (the five nights and the debug scenarios) checks out against the farm.
func _validation(r: GameTestRunner, sim: FarmSim) -> void:
var plans: Array[NightPlan] = sim.waves.plans.duplicate()
r.check(plans.size() == sim.config.campaign_nights, "a plan for each of the %d nights" % sim.config.campaign_nights)
for f in DirAccess.get_files_at(SCENARIOS):
if f.ends_with(".tres"):
plans.append(load(SCENARIOS + f) as NightPlan)
for plan in plans:
var length := plan.night_length if plan.night_length > 0.0 else sim.config.night_length
var bad := plan.problems(length, plan.count_scale_in(sim.config), plan.spacing_scale_in(sim.config))
r.check(bad.is_empty() and plan.title != "", "'%s' is valid%s" % [plan.title, "" if bad.is_empty() else ": %s" % [bad]])
# The checks catch mistakes.
var broken := NightPlan.new()
broken.groups = [{"type": "crow", "target": "crops", "time": 5.0, "count": 1, "every": 1.0},
{"type": "thief", "target": "crops", "time": 200.0, "count": 2, "every": 1.0},
{"type": "crow", "target": "animals", "time": 5.0, "count": 0, "every": 1.0},
{"type": "dragon", "time": 5.0, "count": 1, "every": 1.0}]
var found := broken.problems(150.0)
r.check(found.size() == 5, "a broken plan is caught: %s" % [found])
for k in sim.waves.plans.size():
r.check(sim.waves.plans[k].dusk_hint.length() > 20, "night %d has a dusk hint" % (k + 1))
## Each night tests what it's meant to.
func _designs(r: GameTestRunner, sim: FarmSim) -> void:
var w := sim.waves
var n := w.plans
var crow := EnemySystem.TYPE_CROW
var thief := EnemySystem.TYPE_THIEF
var breaker := EnemySystem.TYPE_BREAKER
r.check(n[0].type_counts().keys() == [crow], "night 1: crows only, at the crops (%s)" % [n[0].type_counts()])
var targets_2 := {}
for g in n[1].groups:
if g["type"] == "thief":
targets_2[g["target"]] = true
r.check(n[1].type_counts().has(crow) and n[1].type_counts().has(thief) and not n[1].type_counts().has(breaker)
and targets_2.has("supplies") and targets_2.has("animals"), "night 2: crows, plus thieves at the shed and the pen")
r.check(int(n[2].type_counts().get(breaker, 0)) >= 2 and int(n[2].type_counts().get(thief, 0)) >= 3, "night 3: fence breakers, and thieves behind them (%s)" % [n[2].type_counts()])
var crowded := _crowded_moments(n[3])
r.check(crowded >= 3, "night 4: %d moments with two groups arriving at once" % crowded)
var waves_5 := _waves(n[4])
r.check(n[4].type_counts().size() == 4 and waves_5 >= 3 and n[4].night_length > sim.config.night_length,
"night 5: all four types (including UFOs) in %d waves, over a longer %.0f s night" % [waves_5, n[4].night_length])
var totals := []
for p in n:
totals.append(p.total(p.count_scale_in(sim.config)))
r.check(totals[4] == totals.max() and totals[0] == totals.min(), "the first night is the smallest, the last the biggest, as played (%s)" % [totals])
r.check(is_equal_approx(n[0].count_scale_in(sim.config), 1.0) and is_equal_approx(n[0].spacing_scale_in(sim.config), 1.0)
and totals[0] <= 12 and n[1].count_scale == 0.0, "night 1 plays as designed, unscaled (%d crows); the later nights at the config's scale" % totals[0])
## Times when two groups start arriving within 3 s of each other.
func _crowded_moments(plan: NightPlan) -> int:
var moments := {}
for i in plan.groups.size():
for j in range(i + 1, plan.groups.size()):
var a := float(plan.groups[i]["time"])
var b := float(plan.groups[j]["time"])
if absf(a - b) <= 3.0:
moments[roundi(minf(a, b) / 10.0)] = true
return moments.size()
## Clusters of arrivals at least 25 s apart.
func _waves(plan: NightPlan) -> int:
var times: Array[float] = []
for g in plan.groups:
times.append(float(g["time"]))
times.sort()
var waves := 1
for k in range(1, times.size()):
if times[k] - times[k - 1] >= 25.0:
waves += 1
return waves
## The upgrades (level 1 of each) change the systems they're about, can't be bought twice (a
## one-off) or before their day (a next level) or at night, and persist.
func _upgrades(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign
var s := c.state
var cfg := sim.config
var es := sim.enemies
var st := sim.structures
c.begin_day()
s.resources.shed = {"wood": 200, "scrap": 200, "straw": 200, "alien_goop": 200}
s.night_events["gathered_alien_goop"] = cfg.hidden_reveal_goop # so the Alien Ray (#7, hidden) buys below
var fence := st.place("fence", 8.0, -8.0, 0)
_settle(sim)
var before := {
"interval": sim.combat.interval_ticks(), "damage": sim.combat.shot_damage(), "radius": sim.scarecrow.fear_radius(),
"cooldown": sim.scarecrow.fear_cooldown(), "max_hp": s.scarecrow_max_hp, "fence": st.max_hp("fence"),
"gate": st.max_hp("gate"), "range": st.turret_range(), "slow": st.trap_slow_time(),
}
var morning := s.to_dict()
var shed := s.resources.shed_total()
var spent := 0
r.check(not player.can_sprint(), "(no sprint before the Sprint upgrade)")
var day := s.night
s.night = 14 # every shed item is in stock by day 14 (#26's from_day)
for id in Upgrades.ORDER:
spent += _sum(Upgrades.cost(cfg, id))
var text := Upgrades.buy(c, id, st)
r.check(Upgrades.level(s, id) == 1 and text.contains("done:"), "bought %s: '%s'" % [id, text])
s.night = day
r.check(s.resources.shed_total() == shed - spent, "all %d cost %d materials together (level 1 each)" % [Upgrades.ORDER.size(), spent])
r.check(player.can_sprint(), "sprint: the scarecrow can sprint")
r.check(Upgrades.buy(c, "sprint", st).contains("already done") and Upgrades.buy(c, "rapid_fire", st).contains("level 2 opens on day 8")
and Upgrades.level(s, "rapid_fire") == 1, "a one-off can't be bought twice, and an upgrade's level 2 waits for day 8")
r.check(sim.combat.interval_ticks() < int(before["interval"]) and sim.combat.shot_damage() == int(before["damage"]) + 1,
"rapid fire and heavy seeds: a shot every %d ticks (was %d), %d damage" % [sim.combat.interval_ticks(), before["interval"], sim.combat.shot_damage()])
r.check(is_equal_approx(sim.scarecrow.fear_radius(), float(before["radius"]) * 1.3) and is_equal_approx(sim.scarecrow.fear_cooldown(), float(before["cooldown"]) * 0.8),
"wide and quick fear: %.1f m, %.1f s" % [sim.scarecrow.fear_radius(), sim.scarecrow.fear_cooldown()])
r.check(s.scarecrow_max_hp == int(before["max_hp"]) + 2 and s.scarecrow_hp == s.scarecrow_max_hp, "straw stuffing: +2 max health")
r.check(st.max_hp("fence") == roundi(int(before["fence"]) * 1.5) and st.max_hp("gate") == roundi(int(before["gate"]) * 1.5)
and int(s.structure(fence)["hp"]) == st.max_hp("fence"), "reinforced fences: fences %d HP, gates %d; a standing fence keeps its full health" % [st.max_hp("fence"), st.max_hp("gate")])
r.check(is_equal_approx(st.turret_range(), float(before["range"]) * 1.3) and is_equal_approx(st.trap_slow_time(), float(before["slow"]) * 1.5),
"long-range defenses %.1f m, sticky tar %.1f s" % [st.turret_range(), st.trap_slow_time()])
# The effects are real: a shot does 2 damage, a defense reaches a thief beyond its old range,
# a trap holds longer.
var keep := es.behavior
es.behavior = null
var h := es.spawn(EnemySystem.TYPE_THIEF, 10.0, -8.0, Vector2.DOWN)
_step(sim, 1)
sim.projectiles.fire(Vector3(10.0, cfg.combat_height, -2.0), Vector3(10.0, cfg.combat_height, -3.0), Vector3(0, 0, -1), sim.combat.shot_damage())
for i in 20:
sim.projectiles.step(DT)
r.check(es.health[es.resolve_handle(h)] == es.t_hp[EnemySystem.TYPE_THIEF] - 2, "a heavy seed takes 2 health off a thief")
es.apply_hit_handle(h, 99)
st.dismantle(fence)
var turret := st.place("automated_defense", 6.0, -13.0, 0)
var far := es.spawn(EnemySystem.TYPE_THIEF, 6.0 + float(before["range"]) + 1.0, -13.0, Vector2.UP)
_step(sim, 90)
r.check(es.resolve_handle(far) < 0 or es.health[es.resolve_handle(far)] < es.t_hp[EnemySystem.TYPE_THIEF], "a defense hits a thief %.0f m away (its old range: %.0f m)" % [float(before["range"]) + 1.0, before["range"]])
for d in es.active_count:
es.apply_hit(d, 99)
st.dismantle(turret)
var trap := st.place("slowing_trap", 8.0, -12.0, 0)
_settle(sim)
h = es.spawn(EnemySystem.TYPE_THIEF, 8.0, -12.0, Vector2.RIGHT)
_step(sim, 1)
r.check(absf(es.slow_left[es.resolve_handle(h)] - st.trap_slow_time()) < 0.05, "a trap slows for %.1f s" % es.slow_left[es.resolve_handle(h)])
es.apply_hit_handle(h, 99)
st.dismantle(trap)
es.behavior = keep
_step(sim, 1)
# They persist: into the next morning, through JSON, and in a retry from that morning; a retry
# from before they were bought takes them back.
var bought := s.upgrades.duplicate()
while s.phase != P.NIGHT:
c.advance_phase()
r.check(Upgrades.blocker(c, "sprint") == "Done" and Upgrades.buy(c, "radar", st).contains("already done"), "(owned ones stay owned at night)")
s.upgrades.erase("sticky_tar")
r.check(Upgrades.blocker(c, "sticky_tar") == "The work area is for daytime", "nothing can be bought at night")
s.upgrades["sticky_tar"] = 1
while s.phase != P.MORNING:
c.advance_phase()
r.check(s.upgrades == bought, "the upgrades carry into the next morning")
var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(s.to_dict(), "", true, true)))
r.check(back != null and back.upgrades == bought, "and through a save")
c.begin_day()
s.scarecrow_hp = 0
_step(sim, 1)
c.retry_night()
r.check(s != c.state and c.state.upgrades == bought, "a retry from that morning keeps them")
var old := FarmState.from_dict(morning)
r.check(old.upgrades.is_empty() and old.resources.shed_total() == shed, "(the morning before they were bought had none, and the materials)")
c.new_campaign()
_step(sim, 1)
r.check(c.state.upgrades.is_empty() and sim.combat.shot_damage() == 1 and st.max_hp("fence") == cfg.fence_hp and not player.can_sprint(),
"a new vacation starts without them")
player.global_position = AWAY
## All five nights back to back, each with its own plan and morning snapshot, to the farmers'
## return. The farm is defended, and the scarecrow kept out of harm.
func _five_nights(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign
var hud := farm.get_node("Hud/PhaseHud") as PhaseHud
c.new_campaign()
_step(sim, 1)
sim.structures.grant_workbench() # #9: granted once, up front, so the per-night structure
# count below (broken aside) doesn't trip over the night-1 grant itself
c._morning_snapshot = c.state.to_dict() # ...and this morning's snapshot (the loop checks it) agrees
sim.waves.enabled = true
player.global_position = AWAY
var arrivals := {}
sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void:
var t: int = sim.enemies.type[sim.enemies.resolve_handle(h)]
arrivals[t] = int(arrivals.get(t, 0)) + 1)
var broken: Array[int] = []
sim.structures.destroyed.connect(func(id: int, _t: String, _at: Vector3) -> void: broken.append(id))
var all_good := true
var lengths: Array[float] = []
var t0 := Time.get_ticks_msec()
for night in range(1, c.config.campaign_nights + 1):
var s := c.state
all_good = all_good and s.night == night and s.phase == P.MORNING and c._morning_snapshot == s.to_dict()
c.begin_day()
if night == 1:
_defend(sim)
s.resources.shed = {"wood": 99, "scrap": 99, "straw": 99}
while c.state.phase != P.NIGHT:
c.advance_phase()
lengths.append(c.state.phase_time_left)
hud._on_phase_changed(P.NIGHT, P.DUSK)
var title_ok := hud._banner.text == "Night %d: %s" % [night, sim.waves.plan_for(night).title]
arrivals.clear()
var structures_at_night := c.state.structures.size()
broken.clear()
while c.state.phase != P.MORNING and not c.is_over():
sim.scarecrow.invulnerable_left = 1.0
sim.step(DT)
var expect := sim.waves.plan_for(night).type_counts(sim.waves.plan_for(night).count_scale_in(c.config))
r.check(arrivals == expect and title_ok, "night %d, '%s': the plan's %s arrived %s" % [night, sim.waves.plan_for(night).title, expect, arrivals])
var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
r.info("night %d: %d crops, %d animals, %d supplies lost; %d structures broken" % [night, e["crops_lost"], e["animals_lost"], e["supplies_lost"], broken.size()])
if night < c.config.campaign_nights:
all_good = all_good and c.state.structures.size() == structures_at_night - broken.size() and c.state.supplies_in_transit == 0
r.check(all_good, "every morning is its night's snapshot, and the farm carries over night to night")
r.check(c.state.phase == P.FARMERS_RETURN and c.state.nights_survived == 5 and c.state.night_log.size() == 5,
"all five nights played to the farmers' return (%.1f s)" % ((Time.get_ticks_msec() - t0) / 1000.0))
r.check(is_equal_approx(lengths[4], sim.waves.plans[4].night_length) and is_equal_approx(lengths[0], c.config.night_length),
"the last night is longer (%.0f s; the others %.0f s)" % [lengths[4], lengths[0]])
sim.waves.enabled = false
## Automated defenses by the crops, the pen, and the shed.
func _defend(sim: FarmSim) -> void:
var st := sim.structures
sim.campaign.state.resources.shed = {"wood": 99, "scrap": 99, "straw": 99}
for at in [Vector2(13.5, -15.0), Vector2(46.0, -15.0), Vector2(13.5, 9.0), Vector2(46.0, 9.0), Vector2(30.0, -17.5),
Vector2(30.0, 11.5), Vector2(7.0, -3.5), Vector2(9.5, -14.0), Vector2(-3.5, -12.0)]:
if st.validate("automated_defense", at.x, at.y, 0, at) in ["", "The scarecrow is in the way"]:
st.place("automated_defense", at.x, at.y, 0)
_settle(sim)
static func _sum(cost: Dictionary) -> int:
var n := 0
for m in cost:
n += int(cost[m])
return n
func _settle(sim: FarmSim) -> void:
var guard := 0
while sim.rebuilding and guard < 600:
sim.step(DT)
guard += 1
func _step(sim: FarmSim, n: int) -> void:
for i in n:
sim.step(DT)