extends RefCounted ## Construction on the real farm, with FarmSim stepped by hand: placement rules (each reason), ## 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) _place_and_rebuild(r, sim) _build_mode(r, sim, player) await _gate(r, sim, player) _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 fence", "fence", Vector2(-3.0, -11.0), 0, "Blocked"], ] 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) 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, whose only opening is shut by the pen's gate, breaks the gate to get ## out; a new gate can go back in the opening. func _breakout(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: var st := sim.structures var es := sim.enemies player.global_position = AWAY var id := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)] r.check(id >= 1 and sim.campaign.state.structure(id)["type"] == "gate" and not sim.animals.pen_open, "the vacation starts with a gate 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) r.check(reached < 20.0 and es.barrier[es.resolve_handle(h)] == id, "the thief walks to the fence and starts breaking it (%.1f s)" % reached) var took := _until(sim, func() -> bool: return broken.has(id), 30.0) var expect := ceilf(float(sim.config.gate_hp) / 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 gate in about %.0f s (took %.1f s)" % [expect, took]) r.check(sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)] < 0 and sim.animals.pen_open, "the broken gate 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) r.check(st.validate("gate", 4.0, -6.0, 2, Vector2(6.0, -6.0)) == "", "a new gate can go in the pen opening") st.place("gate", 4.0, -6.0, 2) _settle(sim) r.check(not sim.animals.pen_open, "and 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 pen's 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