extends RefCounted ## Construction on the real farm, with FarmSim stepped by hand: placement rules (each reason), ## the player-built Animal Pen boundary (open with nothing built, open with a gap, shut once the ## ring is complete), build mode driven by gamepad input (build, dismantle, leave), paying and ## recording, the sliced flow-field rebuild, gates (the scarecrow passes, enemies can't), a walled-in thief breaking ## out through a fence (barrier routing), slowing traps (speed, triggers), the automated ## defense (range), damage and breaking (breach), repair (cost, any phase), dismantling (refund), ## persistence and retry, an A/B night: the same attack on an open and on a fenced crop field, and ## per-instance leveling (#10): a turret's fire rate and L3 volley, a tar patch's footprint, paid ## independently per placed structure, the rules around it (repair first, room, afford), and that ## the level survives a save/retry round trip; and the Workbench (#9): absent and inaccessible ## (no prompt, no shop, including over a co-op request) before Night 1, granted into state before ## the morning snapshot once it's survived, then damaged by an enemy like any barrier, "broken" ## (not destroyed) at 0 HP with its shop refused, repaired at the normal proportional cost, and ## its presence and HP surviving a save and a retry. const P := CampaignController.Phase const T := ThiefBehavior.State const DT := 1.0 / 60.0 const AWAY := Vector3(-11.0, 0.0, 13.0) 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 var c := sim.campaign c.begin_day() _rich(c) _validation(r, sim) _pen_boundary(r, sim) _place_and_rebuild(r, sim) _build_mode(r, sim, player) await _gate(r, sim, player) await _breakout(r, sim, player) _trap(r, sim) _turret(r, sim) _leveling(r, sim) _repair_and_dismantle(r, sim, player) _persistence(r, sim) _ab_night(r, sim, player) _workbench(r, sim, player) farm.queue_free() await r.process_frame func _rich(c: CampaignController) -> void: c.state.resources.shed = {"wood": 999, "scrap": 999, "straw": 999} func _validation(r: GameTestRunner, sim: FarmSim) -> void: var st := sim.structures var cases := [ ["open ground", "fence", Vector2(8.0, -8.0), 0, ""], ["outside the fence", "fence", Vector2(-14.0, 0.0), 0, "Build inside the farm"], ["in the north fence's gap", "fence", Vector2(12.0, -44.0), 0, "Keep the gap clear"], ["where the west fence was", "fence", Vector2(-11.5, -6.0), 2, ""], ["at the barn doors", "fence", Vector2(1.0, -19.5), 0, "Keep the barn doors clear"], ["on a crop row", "fence", sim.loot.home[1], 2, "Not on the crops"], ["in the house", "automated_defense", Vector2(20.5, -26.0), 0, "Blocked"], ["on the pen's edge (no more fence_024 colliders)", "fence", Vector2(-3.0, -11.0), 0, ""], ] for case in cases: var why := st.validate(case[1], case[2].x, case[2].y, case[3], case[2] + Vector2(2.0, 2.0)) r.check(why == case[4], "%s %s: '%s' (got '%s')" % [StructureSystem.NAMES[case[1]], case[0], case[4], why]) var at := Vector2(8.0, -8.0) r.check(st.validate("fence", at.x, at.y, 0, at) == "The scarecrow is in the way", "not on top of the scarecrow") r.check(st.validate("gate", at.x, at.y, 0, at) == "", "a gate may go where the scarecrow stands (it walks through)") r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(12.0, 0.0)) == "Too far from the scarecrow", "only within reach of the scarecrow") var h := sim.enemies.spawn(EnemySystem.TYPE_THIEF, at.x, at.y, Vector2.LEFT) r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(2.0, 2.0)) == "An enemy is in the way", "not on top of an enemy") sim.enemies.apply_hit_handle(h, 99) _step(sim, 1) var res := sim.campaign.state.resources var keep: Dictionary = res.shed.duplicate() res.shed = {"wood": 1, "scrap": 0, "straw": 0} r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(2.0, 2.0)) == "Not enough: need 1 wood more", "and only if it's affordable") res.shed = keep sim.campaign.advance_phase() sim.campaign.advance_phase() r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(2.0, 2.0)) == "Building is for daytime", "no building at night") _to_day(sim) ## Task #11: the Animal Pen's boundary is no longer a scene prop (fence_024) or a free starting ## gate -- it's built the same way as any other fence/gate, at normal cost, through the normal ## validate/place path. With nothing built the pen is open; closing all but its gate slot still ## leaves that one gap open; filling it with a gate shuts the pen. This also leaves the ring ## standing (gate included) for the rest of the suite, the way the deleted props and the removed ## starting gate used to. func _pen_boundary(r: GameTestRunner, sim: FarmSim) -> void: var st := sim.structures var s := sim.campaign.state r.check(sim.animals.pen_open, "with no fence_024 props and no starting gate, the pen starts open") var slots := PenRing.fence_slots() var wood0 := int(s.resources.shed["wood"]) var refused := [] for slot in slots: var why := st.validate("fence", slot[0], slot[1], slot[2], PenRing.NEAR) if why == "": st.place("fence", slot[0], slot[1], slot[2]) else: refused.append("(%s, %s): %s" % [slot[0], slot[1], why]) r.check(refused.is_empty(), "every fence around the pen rect validates and places (%s)" % [refused]) r.check(int(s.resources.shed["wood"]) == wood0 - slots.size() * 2, "%d fences cost 2 wood each" % slots.size()) _settle(sim) r.check(sim.animals.pen_open, "the ring minus its gate slot still leaves a gap: the pen is open") var why := st.validate("gate", PenRing.EAST_X, PenRing.GATE_Z, PenRing.GATE_ROT, PenRing.NEAR) r.check(why == "", "a gate validates in the last gap (got '%s')" % why) var wood1 := int(s.resources.shed["wood"]) var scrap1 := int(s.resources.shed["scrap"]) var gate_id := st.place("gate", PenRing.EAST_X, PenRing.GATE_Z, PenRing.GATE_ROT) r.check(gate_id >= 1 and int(s.resources.shed["wood"]) == wood1 - 4 and int(s.resources.shed["scrap"]) == scrap1 - 1, "the gate costs 4 wood and 1 scrap") _settle(sim) r.check(not sim.animals.pen_open, "a player-built gate in the last gap shuts the pen") func _place_and_rebuild(r: GameTestRunner, sim: FarmSim) -> void: var st := sim.structures var s := sim.campaign.state var wood := int(s.resources.shed["wood"]) var rebuilds := sim.rebuilds var id := st.place("fence", 8.0, -8.0, 0) var e := s.structure(id) r.check(id >= 1 and e.get("hp") == sim.config.fence_hp and int(s.resources.shed["wood"]) == wood - 2, "a fence costs 2 wood and is recorded with 20 HP") r.check(sim.nav.structure_at[sim.nav.cell_of(8.0, -8.0)] == id and sim.nav.structure_at[sim.nav.cell_of(6.0, -8.0)] < 0, "its cells (inflated) are barrier cells for enemies") r.check(sim.rebuilding, "placing it starts a flow-field rebuild") var ticks := 0 while sim.rebuilding and ticks < 600: sim.step(DT) ticks += 1 r.check(not sim.rebuilding and sim.rebuilds == rebuilds + 1, "the rebuild completes over %d ticks" % sim.last_rebuild_ticks) r.info("flow-field rebuild (escape, pen, 3 shed piles, fence breakers): %.1f ms over %d ticks, largest slice %.2f ms (%d cells per tick)" % [ sim.last_rebuild_usec / 1000.0, sim.last_rebuild_ticks, sim.max_rebuild_slice_usec / 1000.0, sim.config.flow_slice_cells]) r.check(st.validate("fence", 8.0, -8.0, 0, Vector2(10.0, -6.0)) == "Something is built here already", "no stacking structures") r.check(st.validate("fence", 9.0, -7.0, 2, Vector2(11.0, -5.0)) == "", "a fence may touch another at its end (corners)") r.check(st.validate("slowing_trap", 8.0, -8.5, 0, Vector2(10.0, -6.0)) == "Something is built here already", "a trap can't overlap a fence") st.dismantle(id) _settle(sim) ## Gamepad: aim right, open build mode, build a fence ahead, dismantle it, and leave. func _build_mode(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var b := sim.build var st := sim.structures player.global_position = Vector3(6.0, 0.0, -2.0) sim.combat.device = ScarecrowCombat.Device.GAMEPAD Input.action_press("aim_right", 1.0) _tap(sim, "build_mode") r.check(b.active, "build mode opens") _tap(sim, "build_2") r.check(b.type() == "gate", "2 picks the gate") _tap(sim, "build_next") _tap(sim, "build_next") _tap(sim, "build_next") r.check(b.type() == "fence", "build_next cycles back to the fence") _tap(sim, "rotate_right") _tap(sim, "rotate_left") _step(sim, 2) var expect := StructureSystem.snap(Vector2(player.global_position.x, player.global_position.z) + b._stick_dir * BuildMode.GAMEPAD_REACH) r.check(b.cursor == expect and b.reason == "", "the cursor is 3 m along the stick, snapped (%s, '%s')" % [b.cursor, b.reason]) var n := st.count() _tap(sim, "fire") r.check(st.count() == n + 1 and sim.combat.shots_fired == 0, "fire builds (and doesn't shoot) in build mode") _step(sim, 1) r.check(b.hover >= 0, "the cursor is over the new fence") var wood := int(sim.campaign.state.resources.shed["wood"]) _tap(sim, "cancel") r.check(st.count() == n and int(sim.campaign.state.resources.shed["wood"]) == wood + 1 and b.active, "cancel over a structure dismantles it, refunding half (1 wood)") _tap(sim, "cancel") r.check(not b.active, "cancel elsewhere leaves build mode") Input.action_release("aim_right") sim.combat.device = ScarecrowCombat.Device.MOUSE _settle(sim) func _gate(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var st := sim.structures var gate := st.place("gate", 8.0, -4.0, 0) var fence := st.place("fence", 12.0, -4.0, 0) _settle(sim) await r.physics_frame # new bodies join the physics space on the next physics frame player.global_position = Vector3(8.0, 0.2, -5.2) var through := player.move_and_collide(Vector3(0.0, 0.0, 2.4), true) player.global_position = Vector3(12.0, 0.2, -5.2) var blocked := player.move_and_collide(Vector3(0.0, 0.0, 2.4), true) r.check(through == null and blocked != null, "the scarecrow walks through a gate but not a fence") r.check(sim.nav.structure_at[sim.nav.cell_of(8.0, -4.0)] == gate, "enemies can't: the gate is a barrier cell") st.dismantle(gate) st.dismantle(fence) _settle(sim) player.global_position = AWAY ## A thief inside the pen, walled in by its player-built ring, breaks a way out; a replacement ## piece can go back in the breach. ## Task #11: escape_field is a global distance-to-the-farm's-outer-edge field, not a "nearest pen ## exit" one, and every ring piece costs the same to cross -- so (unlike the old fence_024 wall ## with its one gap) the thief isn't guaranteed to break the gate specifically; it breaks whatever ## ring piece sits nearest its route to the edge. This checks the general mechanic (a walled-in ## thief breaks out, the breach opens the pen, patching it shuts the pen again) against whichever ## piece that turns out to be, rather than assuming it's the gate. func _breakout(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var st := sim.structures var es := sim.enemies player.global_position = AWAY r.check(not sim.animals.pen_open, "the player-built ring (_pen_boundary) is shutting the pen") var inside := sim.nav.cell_of(-4.0, -6.0) r.check(sim.escape_field[inside] < FarmNavigation.UNREACHABLE, "the walled-in pen still has a route out (through the barrier)") var broken: Array[int] = [] st.destroyed.connect(func(sid: int, _t: String, _at: Vector3) -> void: broken.append(sid)) var h := es.spawn(EnemySystem.TYPE_THIEF, -2.0, -6.0, Vector2.RIGHT) es.state[es.resolve_handle(h)] = T.RETREAT var reached := _until(sim, func() -> bool: return es.resolve_handle(h) >= 0 and es.state[es.resolve_handle(h)] == T.BREAK, 20.0) var id := es.barrier[es.resolve_handle(h)] if reached < 20.0 else -1 r.check(reached < 20.0 and id >= 1, "the thief walks to the pen's boundary and starts breaking a way out (%.1f s)" % reached) var piece: Dictionary = sim.campaign.state.structure(id) var type: String = piece.get("type", "fence") var at := Vector2(float(piece.get("x", 0.0)), float(piece.get("z", 0.0))) var rot: int = int(piece.get("rot", 0)) var took := _until(sim, func() -> bool: return broken.has(id), 30.0) var expect := ceilf(float(st.max_hp(type)) / es.t_structure_damage[EnemySystem.TYPE_THIEF]) * es.t_hit_interval[EnemySystem.TYPE_THIEF] r.check(took < 30.0 and absf(took - expect) < es.t_hit_interval[EnemySystem.TYPE_THIEF] + 0.5, "it breaks the %s in about %.0f s (took %.1f s)" % [type, expect, took]) r.check(sim.nav.structure_at[sim.nav.cell_of(at.x, at.y)] < 0 and sim.animals.pen_open, "the broken piece is gone from navigation: the pen is open") var out := _until(sim, func() -> bool: return es.resolve_handle(h) == -1, 40.0) r.check(out < 40.0, "then it leaves the farm through the breach (%.1f s)" % out) await r.process_frame # the broken piece's view (fences keep real collision) is queue_free()'d, not freed outright var replace_why := st.validate(type, at.x, at.y, rot, PenRing.NEAR) r.check(replace_why == "", "a replacement %s can go back in the breach (got '%s')" % [type, replace_why]) st.place(type, at.x, at.y, rot) _settle(sim) r.check(not sim.animals.pen_open, "patching the breach shuts the pen again") func _trap(r: GameTestRunner, sim: FarmSim) -> void: var st := sim.structures var es := sim.enemies var id := st.place("slowing_trap", 8.0, -12.0, 0) _settle(sim) var h := es.spawn(EnemySystem.TYPE_THIEF, 8.0, -12.0, Vector2.RIGHT) var keep := es.behavior es.behavior = null # drive it by hand: full pace to the east var d := es.resolve_handle(h) es.desire_x[d] = 1.0 es.pace[d] = 1.0 _step(sim, 1) r.check(es.slow_left[d] > 0.0 and int(sim.campaign.state.structure(id)["hp"]) == sim.config.trap_triggers - 1, "stepping on the trap slows the thief and uses a trigger") _step(sim, 40) var speed := Vector2(es.vel_x[d], es.vel_z[d]).length() r.check(speed <= es.t_speed[EnemySystem.TYPE_THIEF] * sim.config.trap_slow_factor + 0.05 and int(sim.campaign.state.structure(id)["hp"]) == sim.config.trap_triggers - 1, "it moves at half speed (%.2f m/s), one trigger per crossing" % speed) es.pos_x[d] = 8.0 es.pos_z[d] = -12.0 es.slow_left[d] = 0.0 sim.campaign.state.structure(id)["hp"] = 0 _step(sim, 1) r.check(es.slow_left[d] == 0.0, "a used-up trap slows no one") es.behavior = keep es.apply_hit(d, 99) st.dismantle(id) _settle(sim) func _turret(r: GameTestRunner, sim: FarmSim) -> void: var st := sim.structures var es := sim.enemies var id := st.place("automated_defense", 8.0, -6.0, 0) _settle(sim) var far := es.spawn(EnemySystem.TYPE_THIEF, 8.0 + sim.config.turret_range + 2.0, -6.0, Vector2.UP) var fired := sim.projectiles.fired var keep := es.behavior es.behavior = null # keep both thieves where they are _step(sim, 90) r.check(sim.projectiles.fired == fired, "nothing in range: the automated defense holds fire") var near := es.spawn(EnemySystem.TYPE_THIEF, 11.0, -6.0, Vector2.UP) var hp := es.health[es.resolve_handle(near)] _step(sim, 90) var dn := es.resolve_handle(near) r.check(sim.projectiles.fired > fired and (dn < 0 or es.health[dn] < hp), "a thief 3 m away gets shot") r.check(es.health[es.resolve_handle(far)] == es.t_hp[EnemySystem.TYPE_THIEF], "the one beyond %.0f m doesn't" % sim.config.turret_range) es.behavior = keep for dd in es.active_count: es.apply_hit(dd, 99) st.dismantle(id) _settle(sim) ## Task #10: per-instance leveling (L1-L3), independent per placed structure -- a turret's fire ## rate and L3 volley, a tar patch's footprint -- and the rules around it (undamaged, affordable, ## room for a bigger tar patch), proven for two separately-placed structures of the same type so a ## level-up only ever changes the one instance. func _leveling(r: GameTestRunner, sim: FarmSim) -> void: var st := sim.structures var es := sim.enemies _rich(sim.campaign) var keep := es.behavior es.behavior = null # drive enemies by hand: stay put in range, no AI movement _level_turrets(r, sim, st, es) _level_traps(r, sim, st) _level_rules(r, sim, st) es.behavior = keep _settle(sim) ## Two separately-placed turrets: A is leveled up through L2 and L3 while B is left at L1, so every ## check also proves the other one didn't change. func _level_turrets(r: GameTestRunner, sim: FarmSim, st: StructureSystem, es: EnemySystem) -> void: var cfg := sim.config var base := cfg.turret_fire_interval var a := st.place("automated_defense", 8.0, -6.0, 0) var b := st.place("automated_defense", 30.0, -17.5, 0) # far enough apart (> 2x turret_range) that neither's test enemy draws the other's fire r.check(st.level_of(a) == 1 and st.level_of(b) == 1, "a freshly placed turret starts at L1") var ha := es.spawn(EnemySystem.TYPE_THIEF, 9.3, -6.0, Vector2.UP) var ev := _fire_events(sim, 400, 3) r.check(ev.size() == 3 and ev.all(func(e: Array) -> bool: return int(e[1]) == 1), "L1: one projectile a shot (got %s)" % [ev]) r.check(absf(ev[1][0] - ev[0][0] - base) < 0.05 and absf(ev[2][0] - ev[1][0] - base) < 0.05, "L1: the base interval between shots (%.3f s apart, expected %.3f)" % [ev[1][0] - ev[0][0], base]) es.apply_hit_handle(ha, 99) _step(sim, 3) var cost2: Dictionary = cfg.structure_level_costs["automated_defense"][0] var shed0: Dictionary = sim.campaign.state.resources.shed.duplicate() r.check(st.upgrade(a) and st.level_of(a) == 2 and st.level_of(b) == 1, "upgrading A to L2 pays and levels only A, not B") for m in cost2: r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost2[m]), "L2 costs %s" % [cost2]) var expect2 := base / cfg.turret_level_fire_mult var ha2 := es.spawn(EnemySystem.TYPE_THIEF, 9.3, -6.0, Vector2.UP) ev = _fire_events(sim, 400, 3) r.check(ev.size() == 3 and ev.all(func(e: Array) -> bool: return int(e[1]) == 1), "L2: still one projectile a shot (got %s)" % [ev]) r.check(absf(ev[1][0] - ev[0][0] - expect2) < 0.05 and absf(ev[2][0] - ev[1][0] - expect2) < 0.05, "L2: %.1fx the fire rate (%.3f s apart, expected %.3f)" % [cfg.turret_level_fire_mult, ev[1][0] - ev[0][0], expect2]) es.apply_hit_handle(ha2, 99) _step(sim, 3) var cost3: Dictionary = cfg.structure_level_costs["automated_defense"][1] shed0 = sim.campaign.state.resources.shed.duplicate() r.check(st.upgrade(a) and st.level_of(a) == 3, "upgrading A to L3") for m in cost3: r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost3[m]), "L3 costs %s" % [cost3]) r.check(st.upgrade_cost(a).is_empty() and st.upgrade_blocker(a) == "Max level", "L3 is the max: no further cost, 'Max level'") var ha3 := es.spawn(EnemySystem.TYPE_THIEF, 9.3, -6.0, Vector2.UP) es.health[es.resolve_handle(ha3)] = 999 # outlast a few L3 volleys (3 shots each) so a 2nd volley is there to measure ev = _fire_events(sim, 400, 2) r.check(ev.size() == 2 and int(ev[0][1]) == cfg.turret_l3_projectiles and int(ev[1][1]) == cfg.turret_l3_projectiles, "L3: %d projectiles at once, in a fan (got %s)" % [cfg.turret_l3_projectiles, ev]) r.check(absf(ev[1][0] - ev[0][0] - expect2) < 0.05, "L3: keeps L2's rate (%.3f s apart, expected %.3f)" % [ev[1][0] - ev[0][0], expect2]) es.health[es.resolve_handle(ha3)] = 1 # undo the extra HP (above) before the usual kill-and-clean-up es.apply_hit_handle(ha3, 99) _step(sim, 3) r.check(st.level_of(b) == 1, "B was never upgraded, through all of A's: still L1") var hb := es.spawn(EnemySystem.TYPE_THIEF, 31.3, -17.5, Vector2.UP) ev = _fire_events(sim, 400, 2) r.check(ev.size() == 2 and ev.all(func(e: Array) -> bool: return int(e[1]) == 1) and absf(ev[1][0] - ev[0][0] - base) < 0.05, "B still fires at the unleveled base rate, one projectile (got %s)" % [ev]) es.apply_hit_handle(hb, 99) _step(sim, 3) for dd in es.active_count: if es.alive[dd] == 1: es.apply_hit(dd, 99) st.dismantle(a) st.dismantle(b) ## Two separately-placed tar patches: A is leveled up through L2 and L3 (footprint doubling, then ## tripling, its L1 size) while B is left at L1. func _level_traps(r: GameTestRunner, sim: FarmSim, st: StructureSystem) -> void: var cfg := sim.config r.check(is_equal_approx(st.trap_size_mult(1), 1.0) and is_equal_approx(st.trap_size_mult(2), 2.0) and is_equal_approx(st.trap_size_mult(3), 3.0), "trap_level_size_mult: L1 1x, L2 2x, L3 3x") var a := st.place("slowing_trap", 8.0, -12.0, 0) var b := st.place("slowing_trap", 8.0, -8.0, 0) r.check(st.level_of(a) == 1 and st.level_of(b) == 1, "a freshly placed tar patch starts at L1") var e: Dictionary = sim.campaign.state.structure(a) var half1 := 0.75 * st.trap_size_mult(1) r.check(st.try_trap(8.0 + half1 - 0.02, -12.0) and int(e["hp"]) == cfg.trap_triggers - 1, "L1 (%.2f m half): triggers just inside its edge" % half1) e["hp"] = cfg.trap_triggers r.check(not st.try_trap(8.0 + half1 + 0.05, -12.0), "L1: not just past its edge") var cost2: Dictionary = cfg.structure_level_costs["slowing_trap"][0] var shed0: Dictionary = sim.campaign.state.resources.shed.duplicate() r.check(st.upgrade(a) and st.level_of(a) == 2 and st.level_of(b) == 1, "upgrading A to L2 pays and levels only A, not B") for m in cost2: r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost2[m]), "L2 costs %s" % [cost2]) var half2 := 0.75 * st.trap_size_mult(2) r.check(is_equal_approx(half2, half1 * 2.0), "L2 doubles the L1 footprint (%.2f vs %.2f m half)" % [half2, half1]) e["hp"] = cfg.trap_triggers r.check(st.try_trap(8.0 + half1 + 0.05, -12.0), "L2: now triggers just past the old L1 edge (bigger footprint)") e["hp"] = cfg.trap_triggers r.check(not st.try_trap(8.0 + half2 + 0.05, -12.0), "L2: still not past its own (bigger) edge") var cost3: Dictionary = cfg.structure_level_costs["slowing_trap"][1] shed0 = sim.campaign.state.resources.shed.duplicate() r.check(st.upgrade(a) and st.level_of(a) == 3, "upgrading A to L3") for m in cost3: r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost3[m]), "L3 costs %s" % [cost3]) var half3 := 0.75 * st.trap_size_mult(3) r.check(is_equal_approx(half3, half1 * 3.0), "L3 triples the L1 footprint (%.2f vs %.2f m half)" % [half3, half1]) e["hp"] = cfg.trap_triggers r.check(st.try_trap(8.0 + half2 + 0.05, -12.0), "L3: now triggers past L2's old edge too") e["hp"] = cfg.trap_triggers r.check(not st.try_trap(8.0 + half3 + 0.05, -12.0), "L3: still not past its own edge") r.check(st.upgrade_cost(a).is_empty() and st.upgrade_blocker(a) == "Max level", "L3 is the max: no further cost, 'Max level'") r.check(st.level_of(b) == 1, "B was never upgraded, through all of A's: still L1") var eb: Dictionary = sim.campaign.state.structure(b) r.check(st.try_trap(8.0 + half1 - 0.02, -8.0) and int(eb["hp"]) == cfg.trap_triggers - 1 and not st.try_trap(8.0 + half1 + 0.05, -8.0), "B still triggers at its L1 size, not past it") st.dismantle(a) st.dismantle(b) ## The rules around leveling: a damaged structure must be repaired first (repair takes priority), ## a bigger tar patch refuses to overlap a neighbor, an unaffordable upgrade is refused, and the ## level survives a to_dict()/from_dict() round trip (save) and sync_from_state() (retry). func _level_rules(r: GameTestRunner, sim: FarmSim, st: StructureSystem) -> void: var s := sim.campaign.state var dmg := st.place("automated_defense", 8.0, -6.0, 0) st.damage(dmg, 1) r.check(st.upgrade_blocker(dmg) == "Repair it first" and not st.upgrade(dmg) and st.level_of(dmg) == 1, "a damaged turret must be repaired before it can be upgraded") st.repair(dmg) st.dismantle(dmg) var near_a := st.place("slowing_trap", 8.0, -12.0, 0) var near_b := st.place("slowing_trap", 9.3, -12.0, 0) # 1.3 m away: clear at L1, overlaps once doubled var why := st.upgrade_blocker(near_a) r.check(why == "Not enough room to upgrade" and not st.upgrade(near_a) and st.level_of(near_a) == 1, "a tar patch refuses to upgrade into a neighbor (got '%s')" % why) st.dismantle(near_a) st.dismantle(near_b) var poor := st.place("automated_defense", 8.0, -6.0, 0) var shed0: Dictionary = s.resources.shed.duplicate() s.resources.shed = {"wood": 0, "scrap": 0, "straw": 0} why = st.upgrade_blocker(poor) r.check(why.begins_with("Not enough:") and not st.upgrade(poor), "an unaffordable upgrade is refused (got '%s')" % why) s.resources.shed = shed0 st.dismantle(poor) var lvl := st.place("automated_defense", 8.0, -6.0, 0) st.upgrade(lvl) st.upgrade(lvl) r.check(st.level_of(lvl) == 3, "set up an L3 turret to round-trip") var d := s.to_dict() var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d, "", true, true))) r.check(back != null and int(back.structure(lvl)["level"]) == 3, "the level survives a save/load round trip") st.sync_from_state() # as a retry would: rebuild every view from the (unchanged) live state r.check(st.level_of(lvl) == 3, "and sync_from_state() (retry) keeps it") st.dismantle(lvl) ## [time_since_the_first_call, projectiles_fired_at_once] for up to `want` shots (sim.projectiles ## may fire more than one projectile in a single tick, at L3). func _fire_events(sim: FarmSim, max_ticks: int, want: int) -> Array: var events: Array = [] var last := sim.projectiles.fired var t := 0.0 var ticks := 0 while events.size() < want and ticks < max_ticks: sim.step(DT) t += DT ticks += 1 var now := sim.projectiles.fired if now > last: events.append([t, now - last]) last = now return events func _repair_and_dismantle(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var st := sim.structures var s := sim.campaign.state var id := st.place("fence", 8.0, -8.0, 0) _settle(sim) r.check(not st.damage(id, 5) and int(s.structure(id)["hp"]) == 15, "damage takes HP off") st.damage(id, 5) r.check(st.repair_cost(id) == {"wood": 1}, "half broken: repairing costs half the build cost, rounded up (1 wood)") sim.campaign.advance_phase() sim.campaign.advance_phase() r.check(s.phase == P.NIGHT, "night falls") player.global_position = Vector3(8.0, 0.0, -7.2) var wood := int(s.resources.shed["wood"]) Input.action_press("interact") _step(sim, roundi(sim.config.repair_time * 60.0) + 2) Input.action_release("interact") _step(sim, 1) r.check(int(s.structure(id)["hp"]) == sim.config.fence_hp and int(s.resources.shed["wood"]) == wood - 1, "holding interact repairs it fully, at night too") var destroyed: Array[String] = [] st.destroyed.connect(func(_i: int, t: String, _at: Vector3) -> void: destroyed.append(t)) r.check(st.damage(id, 99) and s.structure(id).is_empty() and destroyed == ["fence"], "at 0 HP it breaks (breach)") _to_day(sim) player.global_position = AWAY _settle(sim) func _persistence(r: GameTestRunner, sim: FarmSim) -> void: var c := sim.campaign var st := sim.structures var n0 := st.count() # the player-built pen ring (fences and its gate) st.place("fence", 8.0, -8.0, 0) st.place("slowing_trap", 10.0, -12.0, 0) var d := c.state.to_dict() var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d, "", true, true))) # full float precision r.check(back != null and back.to_dict() == d, "structures round-trip through JSON") var bad := d.duplicate(true) (bad["structures"] as Array)[0]["rot"] = 9 r.check(FarmState.from_dict(bad) == null, "a structure with a bad rotation is rejected") # Through the night into the next morning, then build more and fail: retry restores the morning. c.advance_phase() c.advance_phase() c.advance_phase() c.advance_phase() r.check(c.state.phase == P.MORNING and st.count() == n0 + 2, "structures stand into the next morning") var morning: Array = c.state.to_dict()["structures"] c.begin_day() st.place("automated_defense", 8.0, -4.0, 0) c.advance_phase() c.advance_phase() st.damage(int(c.state.structures[0]["id"]), 99) c.state.scarecrow_hp = 0 _step(sim, 1) c.retry_night() _step(sim, 1) r.check(c.state.to_dict()["structures"] == morning and st.count() == n0 + 2 and st._views.size() == n0 + 2, "retry brings back the morning's structures (the broken one stands, the new one is gone)") _settle(sim) ## The same night (seed, two enemies at a time, no scarecrow) against different defenses: crows ## on the crops (fences mean nothing to them, automated defenses do), and thieves after supplies ## (a fence around the shed makes them break in; automated defenses stop them). func _ab_night(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var crows_open := _night_losses(sim, player, "crow", "crops", []) var crows_fenced := _night_losses(sim, player, "crow", "crops", _field_fences()) var crows_shot := _night_losses(sim, player, "crow", "crops", _field_fences() + _field_turrets()) r.info("A/B night, crows (2 at a time, %.0f s + dawn, scarecrow away): open field lost %d crops; fenced %d (%d breaks); fenced with automated defenses %d" % [ sim.config.night_length, crows_open[0], crows_fenced[0], crows_fenced[1], crows_shot[0]]) r.check(crows_fenced[0] == crows_open[0] and crows_fenced[1] == 0, "fences don't change a crow attack (%d = %d crops lost, nothing broken)" % [crows_fenced[0], crows_open[0]]) r.check(crows_shot[0] < crows_open[0], "automated defenses shoot crows down (%d < %d crops lost)" % [crows_shot[0], crows_open[0]]) var open := _night_losses(sim, player, "thief", "supplies", []) var fenced := _night_losses(sim, player, "thief", "supplies", _shed_fences()) var defended := _night_losses(sim, player, "thief", "supplies", _shed_fences() + _shed_turrets()) r.info("A/B night, thieves after supplies (2 at a time): open shed lost %d units; fenced %d (%d breaks); fenced with automated defenses %d (%d breaks)" % [ open[0], fenced[0], fenced[1], defended[0], defended[1]]) r.check(fenced[1] >= 1 and fenced[0] <= open[0], "a fence around the shed makes thieves break in, and costs them time (%d <= %d units lost)" % [fenced[0], open[0]]) r.check(defended[0] < open[0], "defenses change the outcome of the same attack (%d < %d units lost)" % [defended[0], open[0]]) ## Task #9: the Workbench is granted (not built) once Night 1 is survived. A fresh new_campaign() ## (the A/B nights above leave the campaign well past night 1) so "before Night 1" means something. func _workbench(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var c := sim.campaign var st := sim.structures var it := sim.interactions var bench := it.workbench var es := sim.enemies c.new_campaign() _step(sim, 1) r.check(not st.has_workbench() and st.workbench_id() == -1 and not bench.visible, "a fresh vacation, morning of night 1: the Workbench isn't a structure yet, and its scene node is hidden") _rich(c) c.begin_day() player.global_position = bench.global_position + Vector3(0.0, 0.0, 1.2) var msgs: Array[String] = [] it.message.connect(func(t: String, _col: Color) -> void: msgs.append(t)) Input.action_release("interact") _tap(sim, "interact") r.check(not sim.upgrade_panel.is_open, "standing where it will be, before night 1, interact opens no shop") r.check(msgs.is_empty(), "and no workbench prompt or message fires either (it isn't focused: it doesn't exist) (%s)" % [msgs]) var coop := CoopSession.new() coop.sim = sim coop._do_request(["buy", "straw_stuffing"]) r.check(not Upgrades.owned(c.state, "straw_stuffing"), "a co-op 'buy' request for a workbench-shop item is refused before the workbench exists") # Survive night 1: DAY -> DUSK -> NIGHT -> DAWN -> MORNING. night_ending grants it (before the # morning snapshot/save, like #13's crop growth). c.advance_phase() c.advance_phase() c.advance_phase() c.advance_phase() r.check(c.state.phase == P.MORNING and c.state.nights_survived == 1, "night 1 is behind us") var id := st.workbench_id() r.check(id >= 1 and st.has_workbench() and bench.visible and not StructureSystem.ORDER.has("workbench"), "the Workbench now exists as a real (but not buildable) structure, and its scene node shows") r.check(int(c.state.structure(id)["hp"]) == st.max_hp("workbench"), "granted at full HP") var morning_structs: Array = c.state.to_dict()["structures"] r.check(morning_structs.any(func(e: Dictionary) -> bool: return String(e["type"]) == "workbench"), "it was already in state before the morning snapshot was taken") c.begin_day() player.global_position = bench.global_position + Vector3(0.0, 0.0, 1.2) msgs.clear() _tap(sim, "interact") r.check(sim.upgrade_panel.is_open, "now its shop opens like any other workbench day") _tap(sim, "interact") # Targeting (Decision 3): FarmSim._breaker_goals() treats an unbroken Workbench as guarding its # own work area, alongside whatever else is actually guarding something -- PenRing.build_gate_only # places one real guarding structure (the same single-gate setup test_roster.gd's own fence- # breaker test uses), so this proves the Workbench joins a non-empty guarding set, not just a # fallback when nothing else guards anything. var gate_id := PenRing.build_gate_only(sim) _settle(sim) var goals := sim._breaker_goals() r.check(_goals_near(sim, goals, bench.global_position) and _goals_near(sim, goals, Vector3(PenRing.EAST_X, 0.0, PenRing.GATE_Z)), "an unbroken Workbench is in the breaker goals alongside the pen gate guarding the pen") # Spawned far closer to the Work Area than to the pen, a fence breaker -- with no hand-set # state or barrier, driven only by its own AI -- heads for and smashes the Workbench on its own. # The scarecrow stays well clear (AWAY): close by, the breaker would aggro onto it instead # (ThiefBehavior._aggro, aggro_range 4 m) and never reach BREAK. player.global_position = AWAY var hb := sim.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["driveway"]) var at := _until(sim, func() -> bool: return es.resolve_handle(hb) >= 0 and es.state[es.resolve_handle(hb)] == T.BREAK, 40.0) var dh := es.resolve_handle(hb) r.check(at < 40.0 and dh >= 0 and es.barrier[dh] == id, "a fence breaker (no hand-set state) targets and walks to the Workbench on its own (%.1f s)" % at) var hp0 := int(c.state.structure(id)["hp"]) _step(sim, roundi(es.t_hit_interval[EnemySystem.TYPE_BREAKER] * 60.0) + 4) r.check(int(c.state.structure(id)["hp"]) < hp0, "and actually damages it") es.apply_hit_handle(hb, 99) _step(sim, 1) st.dismantle(gate_id) _settle(sim) # Broken at 0 HP: the record stays (repair-only, not destroyed/removed); its shop is refused, # and it drops out of the breaker goals (nothing left to gain by sending another breaker at it). var destroyed: Array[String] = [] st.destroyed.connect(func(_i: int, t: String, _at: Vector3) -> void: destroyed.append(t)) r.check(not st.damage(id, 9999) and not c.state.structure(id).is_empty() and int(c.state.structure(id)["hp"]) == 0, "damaging it to 0 HP leaves it 'broken', not destroyed: the record stays") r.check(destroyed.is_empty(), "no breach/destroyed signal for it") r.check(not _goals_near(sim, sim._breaker_goals(), bench.global_position), "a broken Workbench drops out of the breaker goals") # Just outside REPAIR_REACH (1.4 m to the footprint's edge, 0.5 m out from center) but inside # the Workbench's own reach (2.2 m, to its center): repair takes priority within REPAIR_REACH # (Interactions), so this is where its shop's own refusal shows. player.global_position = bench.global_position + Vector3(0.0, 0.0, 2.0) msgs.clear() _tap(sim, "interact") r.check(not sim.upgrade_panel.is_open and msgs.has("Broken -- repair it"), "its shop refuses to open while broken (%s)" % [msgs]) coop._do_request(["buy", "straw_stuffing"]) r.check(not Upgrades.owned(c.state, "straw_stuffing"), "a co-op 'buy' request is refused while it's broken too") # Repaired at the normal proportional cost (StructureSystem.repair_cost/repair), from within # REPAIR_REACH. var cost := st.repair_cost(id) r.check(not cost.is_empty() and cost == sim.config.costs["workbench"], "broken (0 of its HP), repairing costs the full amount (%s)" % [cost]) c.state.resources.shed = cost.duplicate() player.global_position = bench.global_position + Vector3(0.0, 0.0, 1.2) Input.action_press("interact") _step(sim, roundi(sim.config.repair_time * 60.0) + 2) Input.action_release("interact") _step(sim, 1) r.check(int(c.state.structure(id)["hp"]) == st.max_hp("workbench"), "holding interact repairs it fully, for the proportional cost") msgs.clear() _tap(sim, "interact") r.check(sim.upgrade_panel.is_open, "repaired, its shop opens again") _tap(sim, "interact") # Persistence: presence and HP survive a save (JSON) round trip and a retry. var d2 := c.state.to_dict() var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d2, "", true, true))) r.check(back != null and back.structure(id)["type"] == "workbench" and int(back.structure(id)["hp"]) == st.max_hp("workbench"), "its presence and HP survive a save (JSON) round trip") st.damage(id, 5) c.advance_phase() # DAY -> DUSK c.advance_phase() # DUSK -> NIGHT c.state.scarecrow_hp = 0 _step(sim, 1) c.retry_night() _step(sim, 1) r.check(st.has_workbench() and int(c.state.structure(st.workbench_id())["hp"]) == st.max_hp("workbench"), "a retry restores the morning's Workbench, undamaged by what happened after") player.global_position = AWAY _settle(sim) ## Whether any of FarmSim._breaker_goals()'s cells (walkable cells near a guarding barrier's ## footprint) sit near a world position -- 3 m is generous (the goal cells themselves are within ## ~1.1 m of a footprint's edge) but well short of the distance between the Workbench and the pen ## gate used alongside it above, so it can't mistake one guarding structure's goals for the other's. func _goals_near(sim: FarmSim, goals: PackedInt32Array, at: Vector3) -> bool: var p := Vector2(at.x, at.z) for cell in goals: if sim.nav.cell_center(cell).distance_to(p) <= 3.0: return true return false func _field_fences() -> Array: var parts: Array = [] for k in 15: parts.append(["fence", Vector2(16.0 + 2.0 * k, -16.5), 0]) parts.append(["fence", Vector2(16.0 + 2.0 * k, 10.5), 0]) for k in 14: parts.append(["fence", Vector2(15.0, -15.5 + 2.0 * k), 2]) parts.append(["fence", Vector2(45.0, -15.5 + 2.0 * k), 2]) return parts func _field_turrets() -> Array: var parts: Array = [] 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)]: parts.append(["automated_defense", at, 0]) return parts ## A U of fences around the shed's apron, from the barn wall out and across. func _shed_fences() -> Array: var parts: Array = [] for z in [-20.0, -18.0, -16.0, -14.0]: parts.append(["fence", Vector2(-7.0, z), 2]) if z > -19.0: # the work area's barrels close the top of the east side parts.append(["fence", Vector2(8.5, z), 2]) for k in 8: parts.append(["fence", Vector2(-6.0 + 2.0 * k, -12.75), 0]) return parts func _shed_turrets() -> Array: var parts: Array = [] for at in [Vector2(-3.5, -12.0), Vector2(5.0, -11.0), Vector2(1.0, -14.5)]: parts.append(["automated_defense", at, 0]) return parts ## Plays one night of the trickle (two of `type` at a time, after `target`) against a layout; ## returns [crops or supply units lost, barriers broken]. func _night_losses(sim: FarmSim, player: PlayerCharacter, type: String, target: String, parts: Array) -> Array[int]: var c := sim.campaign c.new_campaign() _step(sim, 1) sim.loot._rng.seed = 7 sim.waves.rng.seed = 7 sim.waves.enabled = true sim.config.night_thieves = 2 sim.config.trickle_type = type sim.config.trickle_target = target player.global_position = AWAY c.begin_day() _rich(c) var breaks: Array[int] = [] var cb := func(_i: int, _t: String, _at: Vector3) -> void: breaks.append(1) sim.structures.destroyed.connect(cb) var refused := [] for part in parts: var why := sim.structures.validate(part[0], part[1].x, part[1].y, part[2], part[1]) if why == "" or why == "The scarecrow is in the way": sim.structures.place(part[0], part[1].x, part[1].y, part[2]) else: refused.append("%s at %s: %s" % [part[0], part[1], why]) if not refused.is_empty(): push_warning("A/B layout pieces refused: %s" % [refused]) _settle(sim) c.advance_phase() c.advance_phase() var guard := 0 while c.state.phase != P.MORNING and not c.is_over() and guard < 20000: sim.step(DT) guard += 1 sim.structures.destroyed.disconnect(cb) sim.config.night_thieves = 0 sim.config.trickle_type = "crow" sim.config.trickle_target = "any" sim.waves.enabled = false var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1] return [int(e["crops_lost"]) if target == "crops" else int(e["supplies_lost"]), breaks.size()] func _to_day(sim: FarmSim) -> void: var c := sim.campaign while c.state.phase != P.DAY: if c.state.phase == P.MORNING: c.begin_day() else: c.advance_phase() ## Lets the flow-field rebuild finish. func _settle(sim: FarmSim) -> void: var guard := 0 while sim.rebuilding and guard < 2000: sim.step(DT) guard += 1 func _tap(sim: FarmSim, action: String) -> void: Input.action_press(action) sim.step(DT) Input.action_release(action) sim.step(DT) func _step(sim: FarmSim, n: int) -> void: for i in n: sim.step(DT) func _until(sim: FarmSim, cond: Callable, max_seconds: float) -> float: var t := 0.0 while t < max_seconds and not cond.call(): sim.step(DT) t += DT return t