harvest/game/tests/test_structures.gd
Forrest eb89268b66 Task #11: Animal Pen boundary becomes player-built
Delete the 23 fence_024 scene props (and their unused ext_resource) from
Zones/AnimalPen in farm.tscn -- their StaticBody3D colliders permanently
walled the pen in FarmNavigation.build(), so today they're the only thing
enclosing it. FarmZone.Kind.ANIMAL_PEN and AnimalSystem.update_pen_open()
already drive the open/closed check; players now build ordinary fence/gate
structures around the existing pen rect to close it.

Remove the free starting gate from GameConfig.start_structures (now an
empty array): the pen is fully player-built, nothing stands at the start.

Add game/tests/pen_ring.gd, a shared helper with the pen rect's 24-piece
fence/gate layout (the same positions the deleted props and the old
starting gate used to occupy), built through StructureSystem's normal
validate/place path at normal cost.

Rework the pen tests that assumed a pre-built pen:
- test_structures.gd gets a new _pen_boundary check (open with nothing
  built, open with a gap, shut once the ring is complete -- the task's
  acceptance test) and builds the ring there for the rest of the suite;
  _breakout no longer assumes the gate specifically breaks (a retreating
  thief now follows a global escape-to-map-edge field across equally
  breakable ring pieces, not a single gap in a solid wall), checking
  whichever piece breaks and that patching it shuts the pen again.
- test_targets.gd builds the full ring in setup (gate first, so it keeps
  structure id 1) and spawns the animal thief near the gate so its
  "breaks the gate" narrative still holds.
- test_roster.gd's fence-breaker test places only the gate (not the full
  ring): FarmSim._breaker_goals() treats every structure near a zone as
  "guarding" it, so a full ring would turn its two-barriers-then-the-
  scarecrow narrative into twenty-five.
- test_farm_state.gd and test_cycle.gd's stale "the pen's gate" wording
  and assumptions are updated for the empty start_structures.

No new FAIL lines versus the pre-existing baseline (one known-flaky
test_roster check aside, confirmed to pass on isolated reruns).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 14:34:02 -04:00

483 lines
22 KiB
GDScript

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, and an A/B night: the same attack on an open and on a fenced crop field.
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)
_repair_and_dismantle(r, sim, player)
_persistence(r, sim)
_ab_night(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)
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]])
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