This commit is contained in:
Forrest 2026-10-04 12:07:36 -04:00
parent 276d43613d
commit 4298caf5cb
552 changed files with 42990 additions and 776 deletions

View file

@ -7,11 +7,33 @@ extends SceneTree
const SUITES := [
"res://game/tests/test_farm_state.gd",
"res://game/tests/test_save.gd",
"res://game/tests/test_outcome.gd",
"res://game/tests/test_campaign.gd",
"res://game/tests/test_farm_layout.gd",
"res://game/tests/test_theft.gd",
"res://game/tests/test_scarecrow.gd",
"res://game/tests/test_weapons.gd",
"res://game/tests/test_economy.gd",
"res://game/tests/test_structures.gd",
"res://game/tests/test_targets.gd",
"res://game/tests/test_roster.gd",
"res://game/tests/test_nights.gd",
"res://game/tests/test_cycle.gd",
"res://game/tests/test_flow.gd",
"res://game/tests/test_coop.gd",
]
const TICK := 1.0 / 60.0
## Points on the farm's edge (FarmZones.edge) for tests that send an enemy in from a known side:
## on foot GameConfig.spawn_margin (3 m) outside the map, where the perimeter gaps used to be...
const EDGE := {
"north": Vector2(12.0, -48.0), "driveway": Vector2(50.0, -39.5), "east": Vector2(50.0, -18.5),
"south-east": Vector2(31.0, 18.0), "south-west": Vector2(-4.0, 18.0), "west": Vector2(-16.0, -6.0),
}
## ...and flying flyer_spawn_margin (8 m) out, where the crow approaches were.
const SKY := {
"north": Vector2(17.0, -53.0), "east": Vector2(55.0, -5.0), "south": Vector2(17.0, 23.0), "west": Vector2(-21.0, -15.0),
}
var passes: int = 0
var failures: int = 0
@ -37,6 +59,11 @@ func _main() -> void:
var suite: Object = (load(path) as GDScript).new()
await suite.call("run", self)
print("TESTS: %d checks passed, %d failed (%.1f s)" % [passes, failures, (Time.get_ticks_msec() - t0) / 1000.0])
# Free whatever suites left behind and give the audio server a mix to drop stopped sounds.
for c in root.get_children():
c.queue_free()
await process_frame
await create_timer(0.25).timeout
quit(mini(failures, 125))
@ -61,6 +88,15 @@ func make_campaign(cfg: GameConfig = null) -> CampaignController:
return c
## Marks the next n crop units that are still on the farm as lost.
static func lose_crops(s: FarmState, n: int) -> void:
var id := 1
while n > 0 and id <= s.crops_total:
if s.lose_crop(id):
n -= 1
id += 1
## Ticks at 60 Hz until the phase changes; returns the game seconds that took (INF if it
## never changed within max_seconds).
static func run_phase(c: CampaignController, max_seconds: float = 1000.0) -> float:

View file

@ -94,14 +94,14 @@ func _early_night(r: GameTestRunner) -> void:
func _night_log(r: GameTestRunner) -> void:
var c := r.make_campaign()
GameTestRunner.run_until(c, P.NIGHT)
c.state.crops -= 3
GameTestRunner.lose_crops(c.state, 3)
GameTestRunner.run_until(c, P.DAWN)
c.state.crops -= 1 # loot escaping during the dawn grace still counts for that night
GameTestRunner.lose_crops(c.state, 1) # loot escaping during the dawn grace still counts for that night
GameTestRunner.run_until(c, P.MORNING)
var e: Dictionary = c.state.night_log[0]
r.check(e["night"] == 1 and e["crops_lost"] == 4, "night 1 records 4 crops lost, dawn included (got %s)" % [e])
r.check(c.state.crops == c.config.start_crops - 4, "losses persist into the next day")
c.state.crops -= 2 # lost during the day don't count against the next night
GameTestRunner.lose_crops(c.state, 2) # lost during the day don't count against the next night
c.begin_day()
GameTestRunner.run_until(c, P.MORNING)
r.check(c.state.night_log[1]["crops_lost"] == 0, "night 2 only counts losses after it started")
@ -110,14 +110,14 @@ func _night_log(r: GameTestRunner) -> void:
func _retry(r: GameTestRunner) -> void:
var c := r.make_campaign()
GameTestRunner.run_until(c, P.NIGHT)
c.state.crops -= 3
GameTestRunner.lose_crops(c.state, 3)
c.state.scarecrow_hp -= 4
GameTestRunner.run_until(c, P.MORNING)
var morning := c.state.to_dict()
c.begin_day()
GameTestRunner.run_until(c, P.NIGHT)
c.state.crops -= 5
GameTestRunner.lose_crops(c.state, 5)
c.state.scarecrow_hp = 0
c.tick(GameTestRunner.TICK)
r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls on night 2")

325
game/tests/test_coop.gd Normal file
View file

@ -0,0 +1,325 @@
extends RefCounted
## Co-op in one process: the host's farm in the main tree and the partner's in a SubViewport
## with its own world (so the two don't share physics), joined by a loopback CoopLink and stepped
## by hand, tick by tick. Covers the join (the welcome, both scarecrows on both farms, names,
## co-op health), requests from the partner (start the day, build, buy), the partner's scarecrow
## moving, gathering, and shooting on the host (and its pick of weapon), the weapons' stabs and
## pumpkin bombs reaching the replica (drawn there, doing no damage of their own), enemies, loot,
## and shots reaching the replica,
## the co-op fall rule (one down is out until morning, both down is Game Over) and Retry, message
## sizes with a crowd, dropped unreliable messages, and either side leaving.
const P := CampaignController.Phase
const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0)
var r: GameTestRunner
var host_farm: Node3D
var client_farm: Node3D
var host: FarmSim
var client: FarmSim
var hs: CoopSession
var cs: CoopSession
var links: Array[CoopLink]
var _viewport: SubViewport
func run(p_r: GameTestRunner) -> void:
r = p_r
await _setup()
_join()
_requests()
await _partner_moves_and_gathers()
_night()
_partner_shoots()
_weapons_shown()
_fall_rule()
_crowd()
_leaving()
for l in links:
l.close()
host_farm.queue_free()
_viewport.get_parent().queue_free()
await r.process_frame
func _setup() -> void:
host_farm = (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
r.root.add_child(host_farm)
_viewport = SubViewport.new()
_viewport.own_world_3d = true
_viewport.size = Vector2i(320, 180)
var box := SubViewportContainer.new()
r.root.add_child(box)
box.add_child(_viewport)
client_farm = (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
_viewport.add_child(client_farm)
await r.process_frame
await r.physics_frame
host = host_farm.get_node("FarmSim") as FarmSim
client = client_farm.get_node("FarmSim") as FarmSim
for f: FarmSim in [host, client]:
f.set_physics_process(false)
f.coop.set_physics_process(false)
f.waves.enabled = false
host.player.global_position = AWAY
host.waves.rng.seed = 1 # repeatable arrival points
hs = host.coop
cs = client.coop
links = CoopLink.pair()
## One tick on both machines, in the order the frames would run them.
func _pump(n: int = 1) -> void:
for i in n:
for body: PlayerCharacter in _remote_bodies():
body._follow_net(DT)
host.step(DT)
hs._physics_process(DT)
client.step(DT)
cs._physics_process(DT)
func _remote_bodies() -> Array[PlayerCharacter]:
var out: Array[PlayerCharacter] = []
for f: FarmSim in [host, client]:
for a in f.avatars:
if a.body.remote_driven:
out.append(a.body)
return out
func _same_state() -> bool:
var a := host.campaign.state.to_dict()
var b := client.campaign.state.to_dict()
for d: Dictionary in [a, b]:
d.erase("phase_time_left")
d.erase("night_events")
return JSON.stringify(a, "", true, true) == JSON.stringify(b, "", true, true)
func _join() -> void:
hs.start_host(host, links[0], "Ana", "Ben")
cs.start_client(client, links[1], "Ben")
_pump(2)
r.check(hs.is_host() and cs.is_client() and client.replica and not host.replica, "the host and the partner each take their role")
r.check(host.avatars.size() == 2 and client.avatars.size() == 2 and host.partner.remote != null and not host.partner.is_local
and client.local_avatar.slot == 1 and client.avatars[0].body.remote_driven and host.partner.body.remote_driven,
"both farms have both scarecrows: the host plays P1, the partner P2")
r.check(client.player == client.avatars[1].body and client.scarecrow.slot == 1 and client.hud.kit == client.scarecrow
and (client.camera as FollowCamera).target == client.player, "the partner's HUD and camera follow P2")
r.check(host.campaign.state.coop and client.campaign.state.coop and host.campaign.state.partner_hp == host.config.scarecrow_max_hp,
"co-op is on: P2 has full health")
r.check(client.campaign.state.phase == P.MORNING and _same_state(), "the partner's farm is the host's (the welcome)")
r.check(host.avatars[0].body._tag.text == "P1 Ana" and host.avatars[1].body._tag.text == "P2 Ben"
and client.avatars[0].body._tag.text == "P1 Ana" and client.avatars[1].body._tag.text == "P2 Ben", "name tags over both")
r.check(client.campaign.save_path == "" and client.audio.remote_cues and host.audio.forward.is_valid(), "only the host saves; sounds come from the host")
func _requests() -> void:
client.review_panel._start.pressed.emit()
_pump(2)
r.check(host.campaign.state.phase == P.DAY and client.campaign.state.phase == P.DAY, "the partner can start the day (the host does it)")
host.campaign.state.resources.shed = {"wood": 40, "scrap": 30, "straw": 30}
client.player.global_position = Vector3(2.0, 0.0, 6.0)
_pump(4)
var before := host.structures.count()
client.build.place_request.call("fence", 3.5, 8.0, 0)
_pump(20)
r.check(host.structures.count() == before + 1 and client.structures.count() == before + 1 and _same_state(),
"the partner builds a fence: the host checks it, builds it, and both farms show it")
client.build.place_request.call("fence", 30.0, -30.0, 0)
_pump(20)
r.check(host.structures.count() == before + 1, "a placement out of the partner's reach is refused by the host")
client.upgrade_panel.buy_request.call("corn_shooter")
_pump(20)
r.check(Upgrades.owned(host.campaign.state, "corn_shooter") and Upgrades.owned(client.campaign.state, "corn_shooter"),
"the partner buys an upgrade at the workbench (the host does it)")
func _partner_moves_and_gathers() -> void:
var tree: GatherNode
for n in host.interactions.nodes:
if n.name == "DeadTree":
tree = n
var at := tree.global_position + Vector3(tree.reach * 0.7, 0.0, 0.0)
client.player.global_position = at
_pump(10)
r.check(host.partner.body.global_position.distance_to(at) < 0.3, "the host's copy of P2 follows the partner's own moves")
host.campaign.state.resources.pouch = {"wood": 0, "scrap": 0, "straw": 0}
Input.action_press("interact")
_pump(roundi(host.config.gather_time * 60.0) - 20)
var gathering_there := client.interactions.gathering != null and String(client.interactions.gathering.name) == "DeadTree" and client.player.rooted
_pump(40)
Input.action_release("interact")
_pump(20)
r.check(gathering_there, "while P2 gathers, the partner sees it (the channel, rooted) from the host")
r.check(int(host.campaign.state.resources.pouch["wood"]) >= 2 and int(client.campaign.state.resources.pouch["wood"]) >= 2
and int(host.campaign.state.night_events.get("gathered_wood", 0)) >= 2, "P2 gathered wood into the shared pouch (%s)" % [host.campaign.state.resources.pouch])
r.check(not client.player.rooted, "and is free to move again")
await r.process_frame
func _night() -> void:
host.campaign.advance_phase()
host.campaign.advance_phase()
_pump(2)
r.check(host.campaign.state.phase == P.NIGHT and client.campaign.state.phase == P.NIGHT, "night falls on both farms")
# Far from P1 (waiting at AWAY, on the farm's edge): where the north gaps were.
host.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["north"])
host.spawn_enemy(EnemySystem.TYPE_THIEF, LootSystem.ANY, GameTestRunner.EDGE["north"])
host.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["driveway"])
_pump(30)
var types_host := _types(host.enemies)
var types_client := _types(client.enemies)
r.check(host.enemies.alive_count() == 3 and types_client == types_host, "the enemies reach the partner's farm, by type (%s)" % [types_client])
r.check(_enemies_match(0.6), "where the host has them (within 0.6 m)")
r.check(client.characters.in_use() == 2, "the partner draws the ground enemies with characters")
# A crow steals: the loot follows on the partner's farm.
var stolen := false
for i in 1800:
_pump()
if host.loot.count(LootSystem.Status.CARRIED) > 0:
stolen = true
break
_pump(8)
var carried := -1
for id in range(1, host.loot.item_count + 1):
if host.loot.status[id] == LootSystem.Status.CARRIED:
carried = id
r.check(stolen and carried > 0 and client.loot.status[carried] == LootSystem.Status.CARRIED
and client.enemies.resolve_handle(client.loot.holder[carried]) >= 0, "a carried crop is carried on both farms, by the same enemy")
var killed := host.enemies.alive_count()
for d in host.enemies.active_count:
host.enemies.apply_hit(d, 99)
_pump(6)
r.check(killed > 0 and host.enemies.alive_count() == 0 and client.enemies.alive_count() == 0, "killed on the host, gone on the partner's farm")
func _partner_shoots() -> void:
var fired := host.partner.combat.shots_fired
var heard := int(client.audio.played.get("shot", 0))
r.check(client.combat.equip(ScarecrowCombat.Weapon.CORN_SHOOTER), "the partner takes the corn shooter (bought for both)")
client.player.global_position = Vector3(8.0, 0.0, -10.0) # open ground, nothing east of it
client.combat.device = ScarecrowCombat.Device.GAMEPAD # keeps the aim it's given
_pump(10)
r.check(host.partner.combat.weapon == ScarecrowCombat.Weapon.CORN_SHOOTER and host.avatars[0].combat.weapon == ScarecrowCombat.Weapon.PITCHFORK,
"the host sees P2 holding it, and P1 still has the pitchfork")
client.combat.aim = Vector2(1.0, 0.0)
Input.action_press("fire")
_pump(30)
r.check(client.projectiles.active_count > 0, "shots in flight show on the partner's farm (the host's, %d)" % client.projectiles.active_count)
Input.action_release("fire")
_pump(10)
r.check(host.partner.combat.shots_fired > fired, "the partner holds fire: P2's gun fires on the host (%d shots)" % (host.partner.combat.shots_fired - fired))
r.check(int(client.audio.played.get("shot", 0)) > heard, "and the partner hears the shots")
r.check(client.projectiles.fired == 0, "(the partner's own gun only aims: it fired nothing itself)")
func _weapons_shown() -> void:
var p1 := client.avatars[0].combat # the host's scarecrow, on the partner's farm
p1.models._attack_t = -1.0
host.combat.equip(ScarecrowCombat.Weapon.PITCHFORK)
host.combat.reset()
host.combat.attack_toward(Vector2(host.player.global_position.x + 3.0, host.player.global_position.z))
_pump(3)
r.check(p1.weapon == ScarecrowCombat.Weapon.PITCHFORK and p1.models._attack_t >= 0.0, "P1's pitchfork stab shows on the partner's farm")
host.campaign.state.upgrades["pumpkin_bomb"] = 1
host.combat.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB)
host.combat.ready_for_morning()
var bursts := client.bombs.bursts
host.combat.attack_toward(Vector2(host.player.global_position.x + 6.0, host.player.global_position.z))
_pump(3)
r.check(p1.weapon == ScarecrowCombat.Weapon.PUMPKIN_BOMB and client.bombs.flying() == 1, "P1's pumpkin bomb flies on the partner's farm too")
_pump(90)
r.check(client.bombs.bursts == bursts + 1 and client.bombs.enemies_hit == 0 and host.bombs.flying() == 0,
"and bursts there, harmless (the host's burst does the damage)")
r.check(client.combat.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB), "the partner can take bombs up too (bought for both)")
var thrown := host.partner.combat.bombs_thrown
Input.action_press("fire")
_pump(10)
Input.action_release("fire")
_pump(4)
r.check(host.partner.combat.bombs_thrown == thrown + 1 and client.combat.bomb_left > 0.0, "P2's throw happens on the host, and its recharge shows on the partner's HUD")
_pump(90)
for c: ScarecrowCombat in [host.combat, client.combat]:
c.equip(ScarecrowCombat.Weapon.PITCHFORK)
host.campaign.state.upgrades.erase("pumpkin_bomb")
_pump(4)
func _fall_rule() -> void:
host.partner.kit.invulnerable_left = 0.0
host.partner.kit.try_damage(99)
_pump(6)
r.check(not host.partner.kit.alive and host.campaign.state.phase == P.NIGHT and not host.campaign.is_over(),
"in co-op one scarecrow down is out until morning, not Game Over")
r.check(not client.scarecrow.alive and not client.player.alive, "the partner sees their own scarecrow fall")
client._process(0.0)
r.check((client.camera as FollowCamera).target == client.avatars[0].body, "and their camera watches P1 meanwhile")
host.scarecrow.invulnerable_left = 0.0
host.scarecrow.try_damage(99)
_pump(6)
r.check(host.campaign.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW and client.campaign.outcome == host.campaign.outcome
and client.campaign.state.phase == P.GAME_OVER, "both down: Game Over on both farms")
client.end_panel._process(EndPanel.DELAY + 0.1)
r.check(client.end_panel.mode == "failure", "with the failure screen on the partner's too")
client.end_panel._retry.pressed.emit()
_pump(4)
r.check(host.campaign.state.phase == P.MORNING and client.campaign.state.phase == P.MORNING and host.scarecrow.alive
and host.partner.kit.alive and client.scarecrow.alive and host.campaign.state.coop, "Retry from the partner: both back at the morning")
func _crowd() -> void:
host.campaign.begin_day()
host.campaign.advance_phase()
host.campaign.advance_phase()
for i in 90:
host.spawn_enemy([EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER][i % 3])
links[0].drop_every = 3 # a third of the unreliable messages lost
_pump(60)
r.check(client.enemies.alive_count() == host.enemies.alive_count() and host.enemies.alive_count() > 40,
"a crowd of %d enemies, with a third of the snapshots lost, all show" % host.enemies.alive_count())
r.check(_enemies_match(1.0), "close to where the host has them")
r.check(links[0].oversized == 0 and links[1].oversized == 0 and links[0].largest_unreliable <= CoopLink.UNRELIABLE_LIMIT,
"no unreliable message is too big for a datagram (largest %d bytes)" % links[0].largest_unreliable)
r.info("co-op traffic: host sent %d messages, %.1f KB in %d ticks; partner %d messages" % [links[0].sent_messages,
links[0].sent_bytes / 1024.0, hs.ticks, links[1].sent_messages])
links[0].drop_every = 0
func _leaving() -> void:
var gone: Array[String] = []
cs.ended.connect(func(why: String) -> void: gone.append(why))
links[1].close() # the partner quits
_pump(2)
r.check(not hs.is_active() and host.partner == null and host.avatars.size() == 1 and not host.campaign.state.coop
and not is_instance_valid(host.get_parent().get_node_or_null("Player2")) or host.get_parent().get_node("Player2").is_queued_for_deletion(),
"the partner leaves: the host plays on alone")
r.check(not cs.is_active() and gone.size() == 1, "and the partner's game is told the session is over ('%s')" % (gone[0] if not gone.is_empty() else ""))
host.campaign.state.coop = true # as a co-op morning's save would have it
host.campaign.retry_night()
r.check(not host.campaign.state.coop, "a co-op morning played alone goes back to the solo rules")
func _types(es: EnemySystem) -> Dictionary:
var out := {}
for d in es.active_count:
if es.alive[d] == 1:
out[es.type[d]] = int(out.get(es.type[d], 0)) + 1
return out
## Every host enemy has a partner-side copy within tolerance meters.
func _enemies_match(tolerance: float) -> bool:
var es := host.enemies
for d in es.active_count:
if es.alive[d] == 0:
continue
var h := cs._local_handle(es.handle_of(d))
var c := client.enemies.resolve_handle(h)
if c < 0:
return false
if Vector2(es.pos_x[d] - client.enemies.pos_x[c], es.pos_z[d] - client.enemies.pos_z[c]).length() > tolerance:
return false
return true

View file

@ -0,0 +1 @@
uid://b2asymmile7yy

231
game/tests/test_cycle.gd Normal file
View file

@ -0,0 +1,231 @@
extends RefCounted
## One complete day and night on the real farm (FarmSim stepped by hand): the night plan's
## arrivals (times, targets, random points all along the farm's edge, nothing by day or after
## sunrise), the dusk warnings, the dawn
## retreat and its record, carrying everything into the next morning (structures and their damage,
## materials, losses in every category, the scarecrow's health), the morning review panel,
## retrying from the morning snapshot, the lighting of each phase, and the phase and asset HUDs.
const P := CampaignController.Phase
const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0)
var _broken: Array[int] = []
var _start_structures: int = 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.rng.seed = 1 # tonight's 11 arrival points, drawn the same every run
var player := farm.get_node("Player") as PlayerCharacter
player.global_position = AWAY
var review := farm.get_node("Hud/ReviewPanel") as ReviewPanel
var hud := farm.get_node("Hud/PhaseHud") as PhaseHud
var assets := farm.get_node("Hud/AssetHud") as AssetHud
assets._process(0.0)
r.check(assets.describe() == "Crops 30/30 · Animals 8/8 · Supplies 10", "the asset HUD reads '%s'" % assets.describe())
sim.structures.destroyed.connect(func(_id: int, _t: String, _at: Vector3) -> void: _broken.append(1))
_morning(r, sim, review, hud)
_day(r, sim, player, hud)
var before_night := sim.campaign.state.to_dict()
_dusk(r, sim, hud)
_night(r, sim)
_dawn_and_morning(r, sim, review, before_night)
_retry(r, sim)
farm.queue_free()
await r.process_frame
func _morning(r: GameTestRunner, sim: FarmSim, review: ReviewPanel, hud: PhaseHud) -> void:
r.check(sim.campaign.state.phase == P.MORNING and review.visible and review._title.text == "The farmers are away",
"the first morning shows the review panel with the introduction")
hud._process(0.0)
r.check(hud.describe() == "Night 1 of 5 · Morning", "the phase HUD reads '%s'" % hud.describe())
sim.day_night.snap()
var day_energy := sim.sun.light_energy
r.check(sim.day_night.lantern.light_energy < 0.6 and day_energy > 0.8, "morning light: bright sun, lantern nearly off")
review._start.pressed.emit()
r.check(sim.campaign.state.phase == P.DAY and not review.visible, "Start the day ends the review")
func _day(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter, hud: PhaseHud) -> void:
var c := sim.campaign
var s := c.state
hud._process(0.0)
r.check(hud.describe() == "Night 1 of 5 · Day · 3:00 left", "the phase HUD reads '%s'" % hud.describe())
sim.day_night.snap()
r.check(is_equal_approx(sim.day_night.lantern.light_energy, 0.0) and sim.sun.light_energy > 1.0, "daylight: full sun, no lantern")
# A day's work: gather into the pouch, build, take some damage, patch up.
var tree: GatherNode
for n in sim.interactions.nodes:
if n.name == "DeadTree":
tree = n
player.global_position = tree.global_position + Vector3(tree.reach * 0.7, 0.0, 0.0)
Input.action_press("interact")
_step(sim, roundi(c.config.gather_time * 60.0) + 2)
Input.action_release("interact")
_step(sim, 1)
r.check(s.resources.pouch["wood"] == 2, "gathered 2 wood into the pouch")
s.resources.shed = {"wood": 20, "scrap": 20, "straw": 20}
_start_structures = sim.structures.count()
var fence := sim.structures.place("fence", 30.0, -18.5, 0)
sim.structures.place("automated_defense", 38.0, -17.0, 0)
sim.structures.damage(fence, 6)
s.scarecrow_hp = 7
player.global_position = AWAY
r.check(sim.structures.count() == _start_structures + 2, "built a fence and an automated defense (next to the pen's gate)")
var arrived: Array[int] = []
sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void: arrived.append(h))
_step_until(sim, P.DUSK)
r.check(arrived.is_empty() and sim.enemies.active_count == 0, "no thieves come by day")
func _dusk(r: GameTestRunner, sim: FarmSim, hud: PhaseHud) -> void:
var w := sim.waves
var plan := w.tonight()
r.check(plan != null and plan.total() == 11 and plan.type_counts() == {EnemySystem.TYPE_CROW: 11}
and plan.total(plan.count_scale_in(sim.config)) == 11, "tonight's plan: %d crows, played as designed (%d)" % [plan.total() if plan else -1,
plan.total(plan.count_scale_in(sim.config)) if plan else -1])
r.check(w.warning_active() and w.tonight_entries() == [[EnemySystem.TYPE_CROW, LootSystem.Category.CROP]], "dusk warns of what tonight brings: %s" % [w.tonight_entries()])
hud._process(0.0)
var warning := "Tonight, from every side: crows"
r.check(hud._hint.text == warning, "the HUD warns, by target: '%s'" % hud._hint.text.replace("\n", " / "))
var marked := w.get_children().filter(func(n: Node) -> bool: return n is Node3D and (n as Node3D).visible)
r.check(marked.is_empty() and sim.alerts.collect().is_empty(), "nothing marks tonight's arrivals on the farm or at the screen edge")
r.check(hud._dusk_hint.visible and hud._dusk_hint.text == plan.dusk_hint and hud._banner.text == "Dusk: %s" % plan.title,
"the dusk banner names tonight, and its hint shows: '%s'" % hud._dusk_hint.text)
r.check(sim.waves.enemies.active_count == 0, "still no thieves at dusk")
func _night(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
var w := sim.waves
var log: Array = []
var cb := func(h: int, at: Vector2) -> void:
var d := sim.enemies.resolve_handle(h)
log.append([w.night_time, at, int(sim.enemies.want[d]), int(sim.enemies.type[d])])
w.arrived.connect(cb)
_step_until(sim, P.NIGHT)
sim.day_night.snap()
r.check(sim.sun.light_energy < float(DayNight.DAY["energy"]) and sim.day_night.lantern.light_energy > 0.0,
"nightfall: the light drops and the lantern comes on")
_step(sim, roundi(DayNight.NIGHTFALL * 60.0) + 2)
sim.day_night.snap()
r.check(sim.sun.light_energy < 0.5 and sim.day_night.lantern.light_energy > 1.5 and is_equal_approx(float(sim.day_night.current["glow"]), 1.0),
"full night: moonlight, the lantern lit, enemies glowing")
_step_until(sim, P.DAWN)
w.arrived.disconnect(cb)
var plan := w.tonight()
var expect: Array = []
var cfg := sim.config
for g in plan.groups:
for k in NightPlan.scaled_count(g, plan.count_scale_in(cfg)):
expect.append([float(g["time"]) + k * NightPlan.scaled_every(g, plan.spacing_scale_in(cfg)),
WaveDirector.want_of(g), WaveDirector.type_of(g)])
expect.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0])
var match_all := log.size() == expect.size()
var edge := sim.zones.edge(cfg.flyer_spawn_margin) # tonight is all crows
var sides := {}
var spots := {}
for i in mini(log.size(), expect.size()):
var at: Vector2 = log[i][1]
match_all = match_all and absf(float(log[i][0]) - float(expect[i][0])) < DT * 1.5 and log[i][2] == expect[i][1] \
and log[i][3] == expect[i][2] and FarmZones.nearest_on_outline(edge, at).distance_to(at) < 0.01
sides[sim.zones.side_of(at)] = true
spots[Vector2i(at.round())] = true
r.check(match_all, "the night plays the plan: %d arrivals of their types at their times, after their targets, on the farm's edge (got %d)" % [expect.size(), log.size()])
# Tonight's few arrivals land on a handful of sides; many more draws cover all eight.
var drawn := {}
for type in [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF]:
for k in 200:
drawn[sim.zones.side_of(w.spawn_point(type))] = true
r.check(sides.size() >= 3 and spots.size() > log.size() * 0.8 and drawn.size() == 8,
"each arrives at its own random point, all around the farm (%d sides, %d spots for %d arrivals; %d sides in 400 draws)" % [
sides.size(), spots.size(), log.size(), drawn.size()])
var ev := c.state.night_events
r.info("night 1 with the scarecrow away: %d crops lost (%d stolen), %d animals lost (%d grabbed, %d wandered out), %d supplies taken; fence at %s HP, %d structures broken" % [
c.state.crops_total - c.state.crops, int(ev.get("crops_stolen", 0)), c.state.animals_total - c.state.animals,
int(ev.get("animals_stolen", 0)), int(ev.get("animals_strayed", 0)), int(ev.get("supplies_stolen", 0)), _fence_hp(sim), _broken.size()])
func _dawn_and_morning(r: GameTestRunner, sim: FarmSim, review: ReviewPanel, before: Dictionary) -> void:
var c := sim.campaign
r.check(c.state.phase == P.DAWN, "sunrise")
var still := 0
for d in sim.enemies.active_count:
var st := sim.enemies.state[d]
if sim.enemies.alive[d] == 1 and st != ThiefBehavior.State.RETREAT and st != ThiefBehavior.State.CARRY:
still += 1
r.check(still == 0, "at sunrise every thief retreats or runs with its loot")
var lost_before_morning := c.state.crops_total - c.state.crops
var stolen := int(c.state.night_events.get("crops_stolen", 0))
_step_until(sim, P.MORNING)
var s := c.state
r.check(sim.enemies.active_count == 0 and s.night == 2, "the next morning: no thieves left, night 2 ahead")
var e: Dictionary = s.night_log[0]
r.check(e["crops_lost"] == s.crops_total - s.crops and e["crops_lost"] >= lost_before_morning and e["crops_stolen"] == stolen,
"the night's record: %s" % [e])
var built: int = before["structures"].size()
r.check(s.to_dict()["structures"].size() == built - _broken.size() and _fence_hp(sim) <= sim.config.fence_hp - 6,
"structures stand, damage and all (%d of %d; %d broken)" % [s.structures.size(), built, _broken.size()])
var shed_before := 0
for m in ResourceStore.MATERIALS:
shed_before += int(before["resources"]["shed"][m])
r.check(s.resources.pouch == before["resources"]["pouch"] and s.resources.shed_total() == shed_before - int(e["supplies_lost"]),
"materials carry over, less what thieves carried off (pouch %s, %d lost from the shed)" % [s.resources.pouch, e["supplies_lost"]])
r.check(s.animals == s.animals_total - s.lost_animals.size() and e["animals_lost"] == s.lost_animals.size() and s.supplies_in_transit == 0,
"animal losses are recorded and no sack is left in transit")
r.check(s.scarecrow_hp == 7, "the scarecrow's health carries over")
r.check(review.visible and review._title.text == "Morning of day 2 of 5" and review._last_head.visible
and review._last_head.text == "Night 1: Crows at the crops" and review._body.text.contains("Needs repair"),
"the morning screen shows last night's results and what needs repair")
var rows := ReviewPanel.category_counts(e)
r.check(review.grid_text() == "Crops %d %d %d\nAnimals %d %d %d\nSupplies %d %d %d" % (rows["Crops"] + rows["Animals"] + rows["Supplies"])
and review._body.text.contains("%d of %d animals" % [s.animals, s.animals_total]), "with every category's taken, recovered, and lost")
var killed := int(e["killed_crow"]) + int(e["killed_thief"]) + int(e["killed_breaker"])
r.check(review._results.text.contains("Enemies defeated: ") and review._results.text.contains("Materials: gathered 2 wood")
and (killed == 0) == review._results.text.contains("defeated: none") and int(e["gathered_wood"]) == 2
and int(e["structures_built"]) == 2 and int(e["structures_damaged"]) >= 6, "enemies defeated, damage, and the day's gathering and building")
r.info("morning screen:\n" + review.grid_text() + "\n" + review._results.text + "\n" + review._body.text)
func _retry(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
var morning := c.state.to_dict()
c.begin_day()
_step(sim, 60)
c.state.resources.shed["wood"] = 0
sim.structures.place("slowing_trap", 10.0, -10.0, 0)
c.state.scarecrow_hp = 0
_step(sim, 1)
r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls on day 2")
c.retry_night()
_step(sim, 1)
var now := c.state.to_dict()
r.check(now == morning, "retry restores the morning snapshot exactly")
var n: int = morning["structures"].size()
r.check(sim.structures.count() == n and sim.structures._views.size() == n, "and the farm shows it (%d structures)" % n)
func _fence_hp(sim: FarmSim) -> int:
for e in sim.campaign.state.structures:
if e["type"] == "fence":
return int(e["hp"])
return -1
func _step_until(sim: FarmSim, phase: CampaignController.Phase) -> void:
var guard := 0
while sim.campaign.state.phase != phase and not sim.campaign.is_over() and guard < 30000:
sim.step(DT)
guard += 1
func _step(sim: FarmSim, n: int) -> void:
for i in n:
sim.step(DT)

View file

@ -0,0 +1 @@
uid://b0vulxeka70sr

316
game/tests/test_economy.gd Normal file
View file

@ -0,0 +1,316 @@
extends RefCounted
## The resource economy: ResourceStore rules (pouch capacity, deposit, paying pouch first then
## shed, all-or-nothing, validation), FarmState keeping materials, gather points, and upgrades
## through JSON, and on the real farm (FarmSim stepped by hand): the gather points' layout,
## gathering by day only (charges, rooted, cancelled by letting go / a hit / fear, a full pouch,
## nightfall), the shed drop-off, overnight regrowth, retry restoring the morning's materials,
## patching's straw cost, and buying the Straw Stuffing upgrade from the workbench's menu.
const P := CampaignController.Phase
const DT := 1.0 / 60.0
func run(r: GameTestRunner) -> void:
_store(r)
_state(r)
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
_layout(r, sim)
_gathering(r, sim, player)
_deposit_and_night(r, sim, player)
_patch_cost(r, sim)
_stuffing(r, sim, player)
farm.queue_free()
await r.process_frame
func _store(r: GameTestRunner) -> void:
var s := ResourceStore.new()
r.check(s.add_to_pouch("wood", 10) == 10 and s.add_to_pouch("straw", 10) == 5 and s.pouch_total() == 15 and s.pouch_room() == 0,
"the pouch takes only what fits (15 units across materials)")
var moved := s.deposit()
r.check(moved == {"wood": 10, "straw": 5} and s.pouch_total() == 0 and s.shed["wood"] == 10, "deposit moves the whole pouch into the shed")
s = ResourceStore.new()
s.shed["wood"] = 3
s.pouch["wood"] = 2
r.check(s.available("wood") == 5 and s.pay({"wood": 4}) and s.pouch["wood"] == 0 and s.shed["wood"] == 1,
"costs are paid from the pouch first, then the shed")
r.check(not s.pay({"wood": 2}) and s.shed["wood"] == 1 and s.missing({"wood": 2}) == {"wood": 1},
"a cost that can't be met pays nothing and says what's missing")
s.shed["straw"] = 5
r.check(not s.pay({"straw": 1, "scrap": 3}) and s.shed["straw"] == 5, "a cost is all-or-nothing across materials")
r.check(ResourceStore.describe({"straw": 2, "wood": 6}) == "6 wood, 2 straw", "costs read in material order")
s.pouch["scrap"] = 4
var back := ResourceStore.from_dict(JSON.parse_string(JSON.stringify(s.to_dict())))
r.check(back != null and back.to_dict() == s.to_dict(), "the store round-trips through JSON")
var bad := {
"a negative amount": func(d: Dictionary) -> void: d["shed"]["wood"] = -1,
"an unknown material": func(d: Dictionary) -> void: d["pouch"]["gold"] = 1,
"an overfull pouch": func(d: Dictionary) -> void: d["pouch"]["wood"] = 99,
"a missing part": func(d: Dictionary) -> void: d.erase("shed"),
}
for label: String in bad:
var d := s.to_dict()
d["shed"] = (d["shed"] as Dictionary).duplicate()
d["pouch"] = (d["pouch"] as Dictionary).duplicate()
(bad[label] as Callable).call(d)
r.check(ResourceStore.from_dict(d) == null, "the store rejects %s" % label)
func _state(r: GameTestRunner) -> void:
var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
var s := FarmState.create(cfg)
r.check(s.resources.shed == {"wood": cfg.start_wood, "scrap": cfg.start_scrap, "straw": cfg.start_straw}
and s.resources.pouch_capacity == cfg.pouch_capacity, "a new farm starts with the configured stock and pouch size")
s.resources.add_to_pouch("scrap", 3)
s.gather_charges = {"Snag": 1, "Wreck": 0}
s.upgrades = {"straw_stuffing": 1}
var d := s.to_dict()
var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d)))
r.check(back != null and back.to_dict() == d, "FarmState keeps materials, used gather points, and upgrades through JSON")
d["gather_charges"] = {"Snag": -2}
r.check(FarmState.from_dict(d) == null, "FarmState rejects negative gather charges")
func _layout(r: GameTestRunner, sim: FarmSim) -> void:
var by_material := {}
var names := {}
for n in sim.interactions.nodes:
by_material[n.material] = int(by_material.get(n.material, 0)) + 1
names[String(n.name)] = true
var zone := sim.zones.zone_at(n.global_position)
var want := {"wood": FarmZone.Kind.WOOD, "scrap": FarmZone.Kind.SCRAP, "straw": FarmZone.Kind.STRAW}[n.material] as FarmZone.Kind
r.check(zone != null and zone.kind == want and n.get_child_count() >= 2, "%s (%s) stands in its zone with its props" % [n.name, n.material])
var inside := {}
var outside := {}
for n in sim.interactions.nodes:
var bucket := inside if sim.zones.is_inside_fence(n.global_position) else outside
bucket[n.material] = int(bucket.get(n.material, 0)) + 1
if bucket == outside:
r.check(n.yield_amount > 2 and sim.zones.zone_at(n.global_position).outside, "%s, outside the fence, yields more (%d)" % [n.name, n.yield_amount])
for m in ResourceStore.MATERIALS:
r.check(int(inside.get(m, 0)) >= 3 and int(inside.get(m, 0)) <= 5, "3-5 gather points for %s on the farm (%d)" % [m, int(inside.get(m, 0))])
r.check(int(outside.get(m, 0)) >= 2, "and more outside the fence (%d)" % int(outside.get(m, 0)))
r.check(sim.zones.outside_zones().size() == 4 and sim.zones.zone(FarmZone.Kind.WOOD).display_name == "Woodlot",
"four gathering areas outside, and the farm's own zones still come first")
r.check(names.size() == sim.interactions.nodes.size(), "gather point names are unique (they key the farm state)")
# The scarecrow's body must be able to stand within reach of every point (and the workbench),
# walking there from its start: out through the gaps for the points outside.
var nav := FarmNavigation.new()
nav.build(sim.get_parent(), sim.zones.roam, 0.5, FarmSim.SCARECROW_RADIUS, 1 | 4)
var from := nav.nearest_free(nav.cell_of(sim.player.global_position.x, sim.player.global_position.z))
var walk := nav.distance_field(PackedInt32Array([from]))
var spots: Array[Node3D] = []
spots.assign(sim.interactions.nodes)
spots.append(sim.interactions.workbench)
for n in spots:
var reach: float = n.reach
var c := Vector2(n.global_position.x, n.global_position.z)
var closest := INF
for cell in nav.free_cells_in(Rect2(c - Vector2.ONE * reach, Vector2.ONE * reach * 2.0)):
if walk[cell] < FarmNavigation.UNREACHABLE:
closest = minf(closest, nav.cell_center(cell).distance_to(c))
r.check(closest <= reach - 0.25, "the scarecrow can walk to within reach of %s (%.1f of %.1f m)" % [n.name, closest, reach])
r.check(sim.interactions.workbench != null and sim.zones.zone(FarmZone.Kind.WORK_AREA).contains(sim.interactions.workbench.global_position),
"the workbench stands in the work area")
func _gathering(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var it := sim.interactions
var res := sim.campaign.state.resources
var tree := _node(it, "DeadTree")
var msgs: Array[String] = []
it.message.connect(func(t: String, _c: Color) -> void: msgs.append(t))
_stand_at(player, tree)
_hold(sim, 30)
r.check(res.pouch_total() == 0 and msgs.has("Gathering is for daytime"), "no gathering before the day starts (once per press: %d)" % msgs.size())
Input.action_release("interact")
sim.campaign.begin_day()
_step(sim, 1)
_hold(sim, 30)
r.check(it.gathering == tree and player.rooted and not it.can_shoot(), "holding interact gathers: rooted, no shooting")
_hold(sim, roundi(sim.config.gather_time * 60.0) - 30 + 2)
r.check(res.pouch["wood"] == tree.yield_amount and it.charges(tree) == tree.max_charges - 1,
"after %.1f s: +%d wood in the pouch, one charge used" % [sim.config.gather_time, tree.yield_amount])
_hold(sim, roundi(sim.config.gather_time * 60.0) + 4)
r.check(it.charges(tree) == 0 and res.pouch["wood"] == tree.yield_amount * 2, "holding on gathers again until the point runs out")
_hold(sim, 10)
r.check(it.gathering == null and msgs.has("Nothing left here; it grows back overnight"), "a used-up point can't be gathered")
# Next to both a used-up point and a full one, interact goes to the full one.
var logs := _node(it, "LogPile")
player.global_position = (tree.global_position + logs.global_position) * 0.5
player.global_position.y = 0.0
Input.action_release("interact")
_step(sim, 1)
var both := Vector2(player.global_position.x - tree.global_position.x, player.global_position.z - tree.global_position.z).length() <= tree.reach \
and Vector2(player.global_position.x - logs.global_position.x, player.global_position.z - logs.global_position.z).length() <= logs.reach
_hold(sim, 5)
r.check(both and it.gathering == logs, "between a used-up point and a full one, the full one is gathered")
Input.action_release("interact")
_step(sim, 1)
res.pouch["wood"] = tree.yield_amount * 2
Input.action_release("interact")
_step(sim, 1)
var snag := _node(it, "Snag")
_stand_at(player, snag)
_hold(sim, 40)
Input.action_release("interact")
_step(sim, 1)
r.check(it.gathering == null and it.charges(snag) == snag.max_charges and not player.rooted, "letting go early gathers nothing")
_hold(sim, 40)
sim.scarecrow.try_damage(1)
r.check(it.gathering == null, "a hit stops gathering")
sim.scarecrow.invulnerable_left = 0.0
sim.campaign.state.scarecrow_hp = sim.campaign.state.scarecrow_max_hp
Input.action_release("interact")
_step(sim, 1)
_hold(sim, 40)
sim.scarecrow.use_fear()
sim.scarecrow.fear_left = 0.0
r.check(it.gathering == null, "using fear stops gathering")
Input.action_release("interact")
_step(sim, 1)
res.add_to_pouch("scrap", res.pouch_room() - 1)
_hold(sim, 20)
r.check(it.gathering == null and msgs.has("Pouch full: drop it off at the supply shed") and it.charges(snag) == snag.max_charges,
"without room for the whole yield, nothing is gathered (and no charge is wasted)")
Input.action_release("interact")
_step(sim, 1)
func _deposit_and_night(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign
var res := c.state.resources
var it := sim.interactions
var shed_before: Dictionary = res.shed.duplicate()
var pouch: Dictionary = res.pouch.duplicate()
var moved: Array[Dictionary] = []
it.deposited.connect(func(m: Dictionary) -> void: moved.append(m))
var shed := sim.zones.zone(FarmZone.Kind.SUPPLY_SHED)
player.global_position = shed.global_position + Vector3(0.0, 0.0, 2.0)
_step(sim, 1)
r.check(res.pouch_total() == 0 and moved.size() == 1 and res.shed["wood"] == int(shed_before["wood"]) + int(pouch["wood"])
and res.shed["scrap"] == int(shed_before["scrap"]) + int(pouch["scrap"]), "walking into the supply shed stores the pouch")
var tree := _node(it, "DeadTree")
var deadfall := _node(it, "Deadfall")
c.state.gather_charges["Deadfall"] = 0
deadfall.regen_per_night = 1
c.advance_phase()
c.advance_phase()
r.check(c.state.phase == P.NIGHT, "night falls")
_stand_at(player, _node(it, "LogPile"))
_hold(sim, 30)
r.check(it.gathering == null and res.pouch_total() == 0, "no gathering at night")
Input.action_release("interact")
_step(sim, 1)
c.advance_phase()
c.advance_phase()
r.check(c.state.phase == P.MORNING and it.charges(tree) == tree.max_charges and it.charges(deadfall) == 1,
"overnight the points grow back (a point regrowing 1 a night has 1 again)")
deadfall.regen_per_night = 20
# Retry brings back the morning's materials and points.
var morning := c.state.to_dict()
c.begin_day()
_stand_at(player, _node(it, "Wreck"))
_hold(sim, roundi(sim.config.gather_time * 60.0) + 2)
Input.action_release("interact")
_step(sim, 1)
r.check(res.pouch["scrap"] > 0, "scrap gathered on day 2")
c.advance_phase()
c.advance_phase()
c.state.scarecrow_hp = 0
_step(sim, 1)
c.retry_night()
_step(sim, 1)
r.check(c.state.resources.to_dict() == morning["resources"] and c.state.gather_charges == morning["gather_charges"],
"retry restores the morning's materials and gather points")
func _patch_cost(r: GameTestRunner, sim: FarmSim) -> void:
var s := sim.campaign.state
var kit := sim.scarecrow
var denied: Array[Dictionary] = []
kit.patch_denied.connect(func(m: Dictionary) -> void: denied.append(m))
s.resources.shed["straw"] = 2
s.resources.pouch["straw"] = 0
s.scarecrow_hp = 5
Input.action_press("patch")
_step(sim, roundi(sim.config.patch_time * 60.0) + 2)
r.check(s.scarecrow_hp == 5 + sim.config.patch_heal and s.resources.available("straw") == 0, "a patch costs 2 straw")
_step(sim, 30)
r.check(not kit.patching and denied.size() == 1 and denied[0] == {"straw": 2}, "without straw the patch is refused, once per press")
Input.action_release("patch")
_step(sim, 1)
s.scarecrow_hp = s.scarecrow_max_hp
func _stuffing(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign
var s := c.state
var it := sim.interactions
var bench := it.workbench
var menu := sim.upgrade_panel
var add := int(sim.config.upgrades["straw_stuffing"]["add"])
var msgs: Array[String] = []
it.message.connect(func(t: String, _col: Color) -> void: msgs.append(t))
menu.message.connect(func(t: String, _col: Color) -> void: msgs.append(t))
player.global_position = bench.global_position + Vector3(0.0, 0.0, 1.2)
_press(sim)
r.check(not menu.is_open and msgs[-1] == "The work area is for daytime", "no upgrades during the morning review")
c.begin_day()
s.resources.shed = {"wood": 0, "scrap": 0, "straw": 3}
_press(sim)
r.check(menu.is_open and player.rooted and not it.can_shoot(), "interact at the workbench opens the upgrade menu; the scarecrow stands still")
var row := menu._rows["straw_stuffing"] as Button
r.check(row.disabled and row.text.contains("Need 4 wood, 9 straw more"), "short of materials, the row says what's missing: '%s'" % row.text)
s.resources.shed = {"wood": 3, "scrap": 0, "straw": 12}
s.resources.pouch = {"wood": 1, "scrap": 0, "straw": 0}
menu.refresh()
var max_hp := s.scarecrow_max_hp
row.pressed.emit()
r.check(Upgrades.owned(s, "straw_stuffing") and s.scarecrow_max_hp == max_hp + add and s.scarecrow_hp == s.scarecrow_max_hp,
"Straw stuffing: +%d max HP (%s)" % [add, msgs[-1]])
r.check(s.resources.shed == {"wood": 0, "scrap": 0, "straw": 0} and s.resources.pouch["wood"] == 0, "it costs 12 straw and 4 wood")
r.check(row.disabled and row.text.contains("Done"), "it can only be bought once")
_press(sim)
r.check(not menu.is_open and not player.rooted, "interact again closes the menu")
_press(sim)
menu.close()
func _node(it: Interactions, node_name: String) -> GatherNode:
for n in it.nodes:
if n.name == node_name:
return n
return null
## Puts the scarecrow next to a gather point, within its reach.
func _stand_at(player: PlayerCharacter, n: GatherNode) -> void:
var to_center := Vector3(n.global_position.x, 0.0, n.global_position.z)
player.global_position = to_center + Vector3(n.reach * 0.7, 0.0, 0.0)
func _hold(sim: FarmSim, ticks: int) -> void:
Input.action_press("interact")
_step(sim, ticks)
func _press(sim: FarmSim) -> void:
Input.action_release("interact")
_step(sim, 1)
Input.action_press("interact")
_step(sim, 1)
Input.action_release("interact")
_step(sim, 1)
func _step(sim: FarmSim, n: int) -> void:
for i in n:
sim.step(DT)

View file

@ -0,0 +1 @@
uid://ceja0c6gemx3k

View file

@ -1,8 +1,10 @@
extends RefCounted
## The playable farm: every zone exists once inside the 60 x 60 m map without overlapping,
## lookups by position, the crop units, the perimeter markers, a perimeter fence without holes
## except its gaps, ground navigation from every gap to every zone, scarecrow-only bounds,
## zone-to-zone travel times (printed as the table kept in game/LAYOUT.md), and the zone banner.
## lookups by position, the crop units, the farm's edge (where enemies arrive) and the gaps in
## what's left of the perimeter fence (the north and east sides, without holes except their gaps;
## the south and west are open), ground navigation from anywhere on the edge to every zone,
## scarecrow-only bounds, zone-to-zone travel times (printed as the table kept in
## game/LAYOUT.md), and the zone banner.
const RUN_SPEED := 5.0 # PlayerCharacter.run_speed
const MAX_TRAVEL := 12.0
@ -73,52 +75,84 @@ func _crops(r: GameTestRunner, zones: FarmZones) -> void:
func _markers(r: GameTestRunner, zones: FarmZones) -> void:
var map := zones.playable
var gaps := zones.markers(FarmMarker.Kind.GAP)
r.check(gaps.size() == 6, "6 perimeter gaps (got %d)" % gaps.size())
var gaps := zones.gaps()
r.check(gaps.size() == 3, "3 gaps in what's left of the perimeter fence (got %d)" % gaps.size())
for m in gaps:
var p := Vector2(m.global_position.x, m.global_position.z)
r.check(not map.has_point(p) and map.grow(4.0).has_point(p), "%s sits just outside the perimeter" % m.name)
var crows := zones.markers(FarmMarker.Kind.CROW)
r.check(crows.size() == 4, "4 crow approach directions (got %d)" % crows.size())
for m in crows:
r.check(not map.grow(4.0).has_point(Vector2(m.global_position.x, m.global_position.z)), "%s is well outside the fence" % m.name)
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var edge := zones.edge(cfg.spawn_margin)
var on_edge := true
for k in 40:
var p := zones.edge_point(k / 40.0 + 0.01, cfg.spawn_margin)
on_edge = on_edge and FarmZones.nearest_on_outline(edge, p).distance_to(p) < 1e-3
r.check(on_edge and zones.edge_point(0.0, cfg.spawn_margin).is_equal_approx(edge.position)
and zones.edge_point(0.5, cfg.spawn_margin).is_equal_approx(edge.end), "edge_point walks the farm's edge, %.0f m out" % cfg.spawn_margin)
var names := [zones.side_of(Vector2(17.0, -48.0)), zones.side_of(Vector2(50.0, -40.0)), zones.side_of(Vector2(-16.0, -15.0)),
zones.side_of(Vector2(31.0, 18.0)), zones.side_of(map.get_center())]
r.check(names == ["north", "north-east", "west", "south-east", ""], "the farm's sides are named by thirds: %s" % [names])
## Every free cell on the fence line is part of a gap (near a gap marker), and every gap is open.
## What's left of the perimeter fence (the north and east sides) has no holes except its gaps, and
## every gap is open; the south and west sides are open ground.
func _fence(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
var map := zones.playable
var gaps := zones.markers(FarmMarker.Kind.GAP)
var gaps := zones.gaps()
var corners := [map.position, Vector2(map.end.x, map.position.y), map.end, Vector2(map.position.x, map.end.y)]
var holes: Array[Vector2] = []
for side in 4:
var free_share: Array[float] = []
for side in 4: # north, east, south, west
var a: Vector2 = corners[side]
var b: Vector2 = corners[(side + 1) % 4]
var steps := ceili(a.distance_to(b) / (CELL * 0.5))
var free := 0
for k in steps + 1:
var p := a.lerp(b, k / float(steps))
if nav.is_free(nav.cell_of(p.x, p.y)) and not gaps.any(func(m: FarmMarker) -> bool:
if not nav.is_free(nav.cell_of(p.x, p.y)):
continue
free += 1
if side < 2 and not gaps.any(func(m: FarmMarker) -> bool:
return Vector2(m.global_position.x, m.global_position.z).distance_to(p) < 4.5):
holes.append(p)
r.check(holes.is_empty(), "the perimeter fence has no holes outside its gaps %s" % [holes.slice(0, 5)])
free_share.append(free / float(steps + 1))
r.check(holes.is_empty(), "the north and east fence has no holes outside its gaps %s" % [holes.slice(0, 5)])
r.check(free_share[2] > 0.9 and free_share[3] > 0.5, "the south and west sides are open (%.0f%% and %.0f%% free)" % [free_share[2] * 100.0, free_share[3] * 100.0])
for m in gaps:
var g := Vector2(m.global_position.x, m.global_position.z)
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
r.check(nav.is_free(nav.cell_of(edge.x, edge.y)), "%s is open for ground enemies" % m.name)
## Ground enemies arrive anywhere on the edge with a route in (as FarmSim picks them: a route to
## the pen) and can walk from there to every zone; the lengths printed are from the middle of each
## side (the table in game/LAYOUT.md).
func _enemy_routes(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
var gaps := zones.markers(FarmMarker.Kind.GAP)
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var edge := zones.edge(cfg.spawn_margin)
var ring := nav.free_cells_on_outline(edge, CELL * 0.75)
var pen := nav.distance_field(nav.free_cells_in(zones.zone(FarmZone.Kind.ANIMAL_PEN).rect().grow(-1.0)))
var spawns := PackedInt32Array()
for c in ring:
if pen[c] < FarmNavigation.UNREACHABLE:
spawns.append(c)
r.check(spawns.size() > ring.size() * 0.9, "enemies can arrive on nearly all of the farm's edge (%d of %d free cells)" % [spawns.size(), ring.size()])
var mid := edge.get_center()
var middles := {"north": Vector2(mid.x, edge.position.y), "east": Vector2(edge.end.x, mid.y), "south": Vector2(mid.x, edge.end.y), "west": Vector2(edge.position.x, mid.y)}
for zone in zones.zones():
var goal := nav.free_cells_in(zone.rect())
r.check(goal.size() > 0, "%s has walkable ground (%d cells)" % [zone.display_name, goal.size()])
var field := nav.distance_field(goal)
var cut_off := 0
for s in spawns:
if field[s] >= FarmNavigation.UNREACHABLE:
cut_off += 1
r.check(cut_off == 0, "ground enemies can walk from anywhere on the edge to the %s and back (%d cells can't)" % [zone.display_name, cut_off])
var lengths: Array[String] = []
for m in gaps:
var c := nav.nearest_free(nav.cell_of(m.global_position.x, m.global_position.z))
var reachable := c >= 0 and field[c] < FarmNavigation.UNREACHABLE
r.check(reachable, "ground enemies can walk from %s to the %s and back" % [m.name, zone.display_name])
lengths.append("%.0f" % nav.meters(field[c]) if reachable else "-")
r.info("%-12s from gaps (m): %s" % [zone.display_name, ", ".join(lengths)])
for side: String in middles:
var at: Vector2 = middles[side]
var m := nav.nearest_free(nav.cell_of(at.x, at.y))
lengths.append("%s %.0f" % [side, nav.meters(field[m])] if m >= 0 and field[m] < FarmNavigation.UNREACHABLE else "%s -" % side)
r.info("%-12s from the edge (m): %s" % [zone.display_name, ", ".join(lengths)])
func _scarecrow(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
@ -127,16 +161,26 @@ func _scarecrow(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
r.check(zones.playable.has_point(Vector2(player.global_position.x, player.global_position.z)), "the scarecrow starts inside the map")
r.check(bounds.collision_layer == 4 and (player.collision_mask & 4) != 0 and (player.collision_mask & 1) != 0,
"PlayerBounds is on the player_bounds layer, which only the scarecrow collides with")
# Stand in each gap and try to walk out: the invisible wall stops the scarecrow.
# Stand in each gap and walk out: nothing stops the scarecrow (the gathering areas outside).
var start := player.global_transform
for m in zones.markers(FarmMarker.Kind.GAP):
for m in zones.gaps():
var g := Vector2(m.global_position.x, m.global_position.z)
var map := zones.playable
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
var out := (g - edge).normalized()
player.global_position = Vector3(edge.x - out.x * 1.0, 0.3, edge.y - out.y * 1.0)
player.global_position = Vector3(edge.x - out.x * 1.0, 0.6, edge.y - out.y * 1.0) # above the driveway's road
var hit := player.move_and_collide(Vector3(out.x, 0.0, out.y) * 3.0, true)
r.check(hit != null, "the scarecrow can't walk out through %s" % m.name)
r.check(hit == null, "the scarecrow can walk out through %s" % m.name)
# ...but not past the old farm's outer fences: the invisible walls are there now.
var roam := zones.roam
var sides := {"north": [Vector2(-20.0, roam.position.y + 1.0), Vector2(0, -1)], "south": [Vector2(5.0, roam.end.y - 1.0), Vector2(0, 1)],
"west": [Vector2(roam.position.x + 1.0, 0.0), Vector2(-1, 0)], "east": [Vector2(roam.end.x - 1.0, -30.0), Vector2(1, 0)]}
for side: String in sides:
var at: Vector2 = sides[side][0]
var dir: Vector2 = sides[side][1]
player.global_position = Vector3(at.x, 0.3, at.y)
var hit := player.move_and_collide(Vector3(dir.x, 0.0, dir.y) * 3.0, true)
r.check(hit != null, "the scarecrow can't go past the %s edge of the roaming area" % side)
player.global_transform = start

View file

@ -1,6 +1,7 @@
extends RefCounted
## FarmState: creation from config, exact to_dict/from_dict round trips (also through JSON),
## rejection of invalid data, snapshot independence, and night loss records.
## FarmState: creation from config (all three asset categories and the pen's gate), exact
## to_dict/from_dict round trips (also through JSON), rejection of invalid data, snapshot
## independence, and night loss records for every category.
func run(r: GameTestRunner) -> void:
@ -10,7 +11,11 @@ func run(r: GameTestRunner) -> void:
r.check(s.phase == CampaignController.Phase.MORNING, "a new farm starts in the morning")
r.check(s.scarecrow_hp == cfg.scarecrow_max_hp and s.scarecrow_max_hp == cfg.scarecrow_max_hp, "scarecrow starts at full HP")
r.check(s.crops == cfg.start_crops and s.crops_total == cfg.start_crops, "crops start at the configured count")
r.check(s.animals_total == 0 and s.supplies_total == 0, "animals and supplies are not in play until Step 8")
r.check(s.animals == cfg.start_animals and s.animals_total == cfg.start_animals, "animals start at the configured count")
var stock := cfg.start_wood + cfg.start_scrap + cfg.start_straw
r.check(s.supplies == stock and s.supplies_total == stock and not s.shed_raided, "supplies are the shed's starting stock (%d)" % stock)
r.check(s.structures.size() == cfg.start_structures.size() and s.structures[0]["type"] == "gate"
and s.structures[0]["hp"] == cfg.gate_hp and s.next_structure_id == 2, "the pen's gate stands from the start")
r.check(s.is_valid(), "a new farm is valid")
# A state with every field away from its default.
@ -20,13 +25,15 @@ func run(r: GameTestRunner) -> void:
s.phase_time_left = 12.5
s.scarecrow_hp = 6
s.crops_total = 40
s.crops = 31
s.animals_total = 8
s.animals = 5
for id in [3, 7, 8, 12, 19, 20, 21, 33, 40]:
s.lose_crop(id)
s.night_events = {"crops_stolen": 2, "crops_recovered": 1, "animals_strayed": 1, "supplies_lost": 5}
for id in [2, 5, 7]:
s.lose_animal(id)
s.supplies_total = 120
s.supplies = 77
s.night_log.append({"night": 1, "crops_lost": 4, "animals_lost": 0, "supplies_lost": 0})
s.night_log.append({"night": 2, "crops_lost": 5, "animals_lost": 3, "supplies_lost": 43})
s.shed_raided = true
s.night_log.append(_entry(1, 4, 0, 0))
s.night_log.append(_entry(2, 5, 3, 43))
var d := s.to_dict()
var copy := FarmState.from_dict(d)
@ -43,17 +50,35 @@ func run(r: GameTestRunner) -> void:
_night_records(r, cfg)
func _entry(night: int, crops: int, animals: int, supplies: int) -> Dictionary:
var e := {"night": night}
for key in FarmState.LOG_KEYS:
if key != "night":
e[key] = 0
e["crops_lost"] = crops
e["animals_lost"] = animals
e["supplies_lost"] = supplies
e["crops_stolen"] = crops + 1
e["animals_stolen"] = animals
e["supplies_stolen"] = supplies + 5
return e
func _rejects(r: GameTestRunner, good: Dictionary) -> void:
var cases := {
"another version": func(d: Dictionary) -> void: d["version"] = FarmState.VERSION + 1,
"a missing key": func(d: Dictionary) -> void: d.erase("crops"),
"a missing key": func(d: Dictionary) -> void: d.erase("lost_crops"),
"an unknown phase": func(d: Dictionary) -> void: d["phase"] = 42,
"more crops than the total": func(d: Dictionary) -> void: d["crops"] = d["crops_total"] + 1,
"negative animals": func(d: Dictionary) -> void: d["animals"] = -1,
"a lost crop id beyond the total": func(d: Dictionary) -> void: d["lost_crops"] = [d["crops_total"] + 1],
"a crop lost twice": func(d: Dictionary) -> void: d["lost_crops"] = [3, 3],
"an unknown night event": func(d: Dictionary) -> void: d["night_events"] = {"cows_tipped": 1},
"a lost animal id beyond the total": func(d: Dictionary) -> void: d["lost_animals"] = [d["animals_total"] + 1],
"an animal lost twice": func(d: Dictionary) -> void: d["lost_animals"] = [2, 2],
"negative supplies in play": func(d: Dictionary) -> void: d["supplies_total"] = -1,
"HP above max": func(d: Dictionary) -> void: d["scarecrow_hp"] = d["scarecrow_max_hp"] + 1,
"night 0": func(d: Dictionary) -> void: d["night"] = 0,
"more nights survived than played": func(d: Dictionary) -> void: d["nights_survived"] = d["night"] + 1,
"a malformed night log": func(d: Dictionary) -> void: d["night_log"] = [{"night": 1}],
"a malformed night log": func(d: Dictionary) -> void: d["night_log"] = [{"night": 1, "crops_lost": 0, "animals_lost": 0, "supplies_lost": 0}],
}
for name: String in cases:
var d := good.duplicate(true)
@ -64,8 +89,33 @@ func _rejects(r: GameTestRunner, good: Dictionary) -> void:
func _night_records(r: GameTestRunner, cfg: GameConfig) -> void:
var s := FarmState.create(cfg)
var start := s.asset_counts()
s.crops -= 7
for id in range(1, 8):
s.lose_crop(id)
s.lose_animal(3)
s.record_event("crops_stolen")
s.record_event("crops_stolen")
s.record_event("crops_recovered")
s.record_event("supplies_stolen", 5)
s.record_event("supplies_lost", 5)
s.resources.shed["wood"] = 99 # stored and spent materials don't count as losses
s.log_night(start)
var e: Dictionary = s.night_log[0]
r.check(s.night_log.size() == 1 and e["night"] == 1 and e["crops_lost"] == 7 and e["animals_lost"] == 0,
"log_night records the losses since the night started")
r.check(s.night_log.size() == 1 and e["night"] == 1 and e["crops_lost"] == 7 and e["animals_lost"] == 1,
"log_night records the crops and animals lost since the night started")
r.check(e["supplies_lost"] == 5 and e["supplies_stolen"] == 5, "supplies lost are the units carried off (%d)" % e["supplies_lost"])
r.check(e["crops_stolen"] == 2 and e["crops_recovered"] == 1 and s.night_events.is_empty(),
"log_night copies the night's theft events and clears them")
s = FarmState.create(cfg)
r.check(s.lose_crop(5) and not s.lose_crop(5) and not s.lose_crop(0) and not s.lose_crop(s.crops_total + 1),
"lose_crop accepts each known unit once")
r.check(s.crops == s.crops_total - 1 and s.is_crop_lost(5) and not s.is_crop_lost(6), "crops is derived from the lost units")
r.check(s.lose_animal(1) and not s.lose_animal(1) and not s.lose_animal(0) and s.animals == s.animals_total - 1,
"lose_animal accepts each known animal once; animals is derived")
s.supplies_in_transit = 4
r.check(s.supplies == s.resources.shed_total() + 4, "supplies count the shed's stock and the sacks still on the farm")
s.supplies_in_transit = 0
s.animals_total = 0
s.supplies_total = 0
s.lose_all_crops()
r.check(s.crops == 0 and s.is_stripped(), "losing every crop unit strips a crops-only farm")

385
game/tests/test_flow.gd Normal file
View file

@ -0,0 +1,385 @@
extends RefCounted
## The whole game through its entry scene (main.tscn, with test save and settings paths): the
## main menu over the paused farm; New vacation, Continue, and their questions; pausing freezes
## the simulation tick; settings apply and persist from the pause menu; Restart the night and
## Save & quit to menu put the farm back at the saved morning without touching the save; a
## damaged save can't be continued; the failure screen and Retry; the farmers' return and the
## final assessment; the first day's and night's tips; and the sounds hooked to the game.
const P := CampaignController.Phase
const SAVE := "user://test_flow_save.json"
const SETTINGS := "user://test_flow_settings.cfg"
const DT := 1.0 / 60.0
var r: GameTestRunner
var main: Main
var sim: FarmSim
var c: CampaignController
func run(p_r: GameTestRunner) -> void:
r = p_r
_clean()
main = (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
main.save_path = SAVE
main.settings_path = SETTINGS
r.root.add_child(main)
await r.process_frame
await r.physics_frame
sim = main.sim
c = sim.campaign
await _title_screen()
await _pause()
await _settings()
await _restart_and_quit_to_menu()
await _continue_and_new()
await _tutorial()
await _failure()
await _ending()
_audio()
main.queue_free()
r.paused = false
await r.process_frame
_clean()
func _clean() -> void:
for p in [SAVE, SAVE + ".tmp", SETTINGS]:
if FileAccess.file_exists(p):
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
func _press(action: String) -> void:
for pressed in [true, false]:
var e := InputEventAction.new()
e.action = StringName(action)
e.pressed = pressed
Input.parse_input_event(e)
await r.process_frame
await r.process_frame
func _hud_visible() -> bool:
return (main.farm.get_node("Hud") as CanvasLayer).visible
func _same(a: Dictionary, b: Dictionary) -> bool:
return JSON.stringify(a, "", true, true) == JSON.stringify(b, "", true, true)
func _title_screen() -> void:
r.check(main.screen == Main.Screen.MENU and r.paused and main.main_menu.visible and not _hud_visible()
and main.get_viewport().get_camera_3d() == main._menu_camera, "the game starts at the main menu: the farm paused behind it, no HUD")
r.check(main.main_menu.continue_button.disabled and main.main_menu.save_note.text == "No saved vacation",
"with nothing to continue, Continue is off and says so")
await r.process_frame
r.check(main.main_menu.new_button.has_focus(), "and New vacation has the focus (keyboard and gamepad)")
r.check(sim.audio.music_track == "farm" and (sim.audio._music["farm"] as AudioStreamPlayer).playing,
"\"On the Farm\" plays on the title screen (the paused farm's morning)")
r.check(not SaveGame.exists(SAVE), "the farm behind the menu isn't saved")
r.check(ProjectSettings.get_setting("gui/theme/custom") == "res://game/resources/ui_theme.tres"
and load("res://game/resources/ui_theme.tres") is Theme and main.main_menu.new_button.has_theme_stylebox("focus"),
"the UI theme is the project's default")
main.main_menu.new_button.pressed.emit()
var saved := SaveGame.read(SAVE)
r.check(main.screen == Main.Screen.PLAYING and not r.paused and _hud_visible() and c.state.phase == P.MORNING
and sim.review_panel.visible and main.get_viewport().get_camera_3d() == sim.camera,
"New vacation (no save to replace) starts at once: the morning screen, the HUD, the follow camera")
r.check(saved.status == SaveGame.Status.OK and saved.state.night == 1, "and saves the new vacation's first morning")
func _pause() -> void:
c.begin_day()
for i in 3:
await r.physics_frame
r.check(c.state.phase == P.DAY and c.state.phase_time_left < c.phase_length(P.DAY), "the day's clock runs while playing")
await _press("pause")
r.check(main.screen == Main.Screen.PAUSED and r.paused and main.pause_menu.visible, "Escape / Start pauses")
var t := c.state.phase_time_left
var player := sim.player.global_position
for i in 10:
await r.physics_frame
r.check(c.state.phase_time_left == t and sim.player.global_position == player, "pausing freezes the simulation tick")
r.check(main.pause_menu._where.text == "Night 1 of 5 · Day" and main.pause_menu._note.text.contains("morning of day 1"),
"the pause menu says where you are and what Continue picks up ('%s')" % main.pause_menu._where.text)
r.check(main.pause_menu.resume_button.has_focus(), "with Resume focused")
await _press("pause")
r.check(main.screen == Main.Screen.PLAYING and not r.paused and not main.pause_menu.visible, "Escape / Start again resumes")
await r.physics_frame
await r.physics_frame
r.check(c.state.phase_time_left < t, "and the clock runs again")
func _settings() -> void:
main.pause()
main.pause_menu.settings_button.pressed.emit()
var menu := main.settings_menu
r.check(menu.visible and menu.is_open, "Settings opens from the pause menu")
await r.process_frame
(menu.controls["volume/Music"] as HSlider).value = 0.3
var music := AudioServer.get_bus_index("Music")
r.check(is_equal_approx(GameSettings.load_from(SETTINGS).volume["Music"], 0.3)
and is_equal_approx(AudioServer.get_bus_volume_db(music), linear_to_db(0.3)), "a change applies and is saved at once")
(menu.controls["show_tips"] as CheckBox).button_pressed = false
r.check(not sim.tutorial.enabled and not GameSettings.load_from(SETTINGS).show_tips, "turning tips off reaches the tutorial")
(menu.controls["show_tips"] as CheckBox).button_pressed = true
(menu.controls["aim_dead_zone"] as HSlider).value = 0.4
r.check(is_equal_approx(sim.config.aim_dead_zone, 0.4), "the aim dead zone reaches the gun's config")
r.check(SettingsMenu.describe_keys(["fear"]) == "Q" and SettingsMenu.describe_pad(["fear"]) == "LB"
and SettingsMenu.describe_keys(["fire"]) == "Left mouse" and SettingsMenu.describe_pad(["fire"]).contains("RT")
and SettingsMenu.describe_keys(["hide_tips"]) == "Backspace" and SettingsMenu.describe_pad(["pause"]) == "Start",
"the bindings list reads the real input map")
await _press("ui_cancel")
r.check(not menu.visible and main.screen == Main.Screen.PAUSED and r.paused, "Escape / B closes Settings back to the pause menu")
await r.process_frame
r.check(main.pause_menu.settings_button.has_focus(), "with the focus back on Settings")
main.settings_menu.open(main.settings)
var reset := menu.back_button.get_parent().get_child(1) as Button
reset.pressed.emit()
r.check(is_equal_approx(GameSettings.load_from(SETTINGS).volume["Music"], GameSettings.DEFAULT_VOLUME["Music"])
and is_equal_approx((menu.controls["volume/Music"] as HSlider).value, GameSettings.DEFAULT_VOLUME["Music"]),
"Reset to defaults resets and saves")
menu.back_button.pressed.emit()
main.resume()
func _restart_and_quit_to_menu() -> void:
var morning := SaveGame.read(SAVE).state.to_dict()
c.state.resources.pouch["wood"] = 4
main.pause()
main.pause_menu.restart_button.pressed.emit()
r.check(main.confirm.is_open and main.confirm.message.text.contains("Restart night 1") and main.screen == Main.Screen.PAUSED,
"Restart the night asks first")
await r.process_frame
r.check(main.confirm.no_button.has_focus(), "with Cancel focused")
main.confirm.yes_button.pressed.emit()
r.check(main.screen == Main.Screen.PLAYING and not r.paused and c.state.phase == P.MORNING and _same(c.state.to_dict(), morning),
"and restarts from the saved morning")
c.begin_day()
c.state.resources.pouch["scrap"] = 3
var file := FileAccess.get_file_as_string(SAVE)
main.pause()
main.pause_menu.menu_button.pressed.emit()
r.check(main.screen == Main.Screen.MENU and r.paused and main.main_menu.visible and not _hud_visible()
and c.state.phase == P.MORNING and c.state.resources.pouch["scrap"] == 0,
"Save & quit to menu: back at the menu, the farm at the saved morning")
r.check(FileAccess.get_file_as_string(SAVE) == file, "and the save itself is untouched")
r.check(not main.main_menu.continue_button.disabled and main.main_menu.save_note.text.begins_with("Morning of day 1 of 5"),
"Continue now offers that morning ('%s')" % main.main_menu.save_note.text)
await r.process_frame
r.check(main.main_menu.continue_button.has_focus(), "and has the focus")
func _continue_and_new() -> void:
main.main_menu.continue_button.pressed.emit()
r.check(main.screen == Main.Screen.PLAYING and _hud_visible() and c.state.phase == P.MORNING
and _same(c.state.to_dict(), SaveGame.read(SAVE).state.to_dict()), "Continue resumes at the saved morning")
main.to_menu()
main.main_menu.new_button.pressed.emit()
r.check(main.confirm.is_open and main.confirm.message.text.contains("replaces your saved one") and main.screen == Main.Screen.MENU,
"New vacation over a save asks first")
await _press("ui_cancel")
r.check(not main.confirm.is_open and main.screen == Main.Screen.MENU, "Escape / B cancels")
main.main_menu.new_button.pressed.emit()
main.confirm.yes_button.pressed.emit()
r.check(main.screen == Main.Screen.PLAYING and c.state.night == 1 and c.state.night_log.is_empty(), "confirming starts the new vacation")
main.to_menu()
var f := FileAccess.open(SAVE, FileAccess.WRITE)
f.store_string("{\"game\": \"harvest-season\", \"state\": {\"version\": 3}}")
f.close()
main.show_main_menu()
r.check(main.main_menu.continue_button.disabled and main.main_menu.save_note.text.contains("damaged"),
"a damaged save can't be continued, and the menu says why")
r.check(not main.continue_vacation() and main.screen == Main.Screen.MENU, "Continue refuses it")
main.main_menu.new_button.pressed.emit()
r.check(main.screen == Main.Screen.PLAYING and SaveGame.read(SAVE).status == SaveGame.Status.OK,
"New vacation doesn't ask about a damaged save and replaces it")
func _tutorial() -> void:
var t := sim.tutorial
t.done = {}
t.dismissed = false
t._process(0.0)
r.check(t.current == "" and not t._box.visible, "no tips during the morning screen")
c.begin_day()
t._process(0.0)
r.check(t.current == "move" and t._box.visible and t._text.text.contains("[W A S D]"), "day 1 starts with how to move")
sim.player.global_position += Vector3(5.0, 0.0, 0.0)
t._process(0.0)
r.check(t.done.has("move") and t._text.text.begins_with("Done!"), "moving finishes it (and says so)")
t._process(1.0)
t._process(0.0)
r.check(t.current == "gather", "then gathering")
c.state.resources.pouch["wood"] = 2
c.state.record_event("gathered_wood", 2)
t._process(0.0)
t._process(1.0)
t._process(0.0)
r.check(t.current == "store", "then storing at the shed, once the pouch has something")
sim.interactions.deposited.emit({"wood": 2})
c.state.resources.pouch["wood"] = 0
t._process(1.0)
t._process(0.0)
r.check(t.current == "build", "then building")
c.state.record_event("structures_built")
t._process(0.0)
t._process(1.0)
t._process(0.0)
r.check(t.current == "" and not t._box.visible, "and nothing more by day")
c.advance_phase()
t._process(0.0)
r.check(t.current == "dusk" and t._text.text.contains("nightfall"), "dusk says when and where the thieves come")
c.advance_phase()
sim.spawn_enemy(EnemySystem.TYPE_CROW)
t._process(0.0)
t._process(1.0)
t._process(0.0)
r.check(t.current == "shoot", "with an enemy in at night: how to shoot")
c.state.scarecrow_hp -= 1
t._process(0.0)
r.check(t.current == "patch", "hurt: how to patch up (more urgent than shooting)")
c.state.scarecrow_hp += 1
await _press("hide_tips")
t._process(0.0)
r.check(t.dismissed and not t._box.visible, "[Backspace / Back] hides the tips")
t.dismissed = false
t.enabled = false
t._process(0.0)
r.check(not t._box.visible, "and with tips off in Settings there are none")
t.enabled = true
c.retry_night()
func _failure() -> void:
var morning := SaveGame.read(SAVE).state.to_dict()
var panel := sim.end_panel
c.begin_day()
c.advance_phase()
c.advance_phase()
r.check(c.state.phase == P.NIGHT, "night 1")
c.state.scarecrow_hp = 0
c.tick(DT)
panel._process(EndPanel.DELAY + 0.1)
r.check(c.state.phase == P.GAME_OVER and panel.is_visible_in_tree() and panel.mode == "failure" and panel._title.text == "The scarecrow has fallen"
and panel._rating.text.begins_with("Night 1 of 5: Crows at the crops"), "the failure screen gives the cause and the night ('%s')" % panel._rating.text)
r.check(panel._detail.text.contains("You kept the farm for 0 nights.") and panel._detail.text.contains("Left: 30 of 30 crops")
and panel._detail.text.contains("Tonight: "), "what was kept, what's left, and what tonight cost")
r.check(panel._retry.visible and panel._retry.has_focus() and panel._menu.visible and not panel._new.visible
and panel._retry.text.contains("morning of day 1"), "Retry the night (focused) and Main menu")
panel._retry.pressed.emit()
r.check(c.state.phase == P.MORNING and not panel.visible and _same(c.state.to_dict(), morning), "Retry restores the saved morning")
c.begin_day()
c.state.strip()
c.tick(DT)
panel._process(EndPanel.DELAY + 0.1)
r.check(panel.mode == "failure" and panel._title.text == "The farm was stripped bare", "a stripped farm says so")
panel._menu.pressed.emit()
r.check(main.screen == Main.Screen.MENU and main.main_menu.visible and c.state.phase == P.MORNING and not panel.visible,
"Main menu goes back to the menu")
main.main_menu.continue_button.pressed.emit()
r.check(main.screen == Main.Screen.PLAYING and _same(c.state.to_dict(), morning), "and Continue retries the failed night's morning")
func _ending() -> void:
var cfg := c.config
var s := FarmState.create(cfg)
s.night = cfg.campaign_nights
s.nights_survived = cfg.campaign_nights - 1
GameTestRunner.lose_crops(s, 2)
for n in range(1, cfg.campaign_nights):
var e := {"night": n, "crops_lost": 1 if n <= 2 else 0, "animals_lost": 0}
for k in FarmState.EVENTS:
e[k] = 0
e["killed_crow"] = 10
e["killed_thief"] = 2
e["gathered_wood"] = 12
s.night_log.append(e)
c.load_state(s)
r.check(SaveGame.read(SAVE).state.night == cfg.campaign_nights, "the last morning is saved")
c.begin_day()
for i in 4: # dusk, night, dawn, and the end of the dawn grace
c.advance_phase()
var ending := sim.ending
r.check(c.state.phase == P.FARMERS_RETURN and not SaveGame.exists(SAVE), "the last dawn ends the vacation and deletes the save")
r.check(ending.running and ending.stage == "drive" and main.get_viewport().get_camera_3d() == ending._camera and not _hud_visible(),
"the farmers' return starts: the cutscene camera, no HUD")
var horn := int(sim.audio.played.get("horn", 0))
var steps := 0
while ending.stage == "drive" and steps < 3000:
ending.step(DT)
steps += 1
var park: Vector3 = FarmersReturn.ROUTE[FarmersReturn.ROUTE.size() - 1]
var car := ending._car.global_position
r.check(ending.stage == "walk" and Vector2(car.x - park.x, car.z - park.z).length() < 0.3 and steps * DT > 4.0 and steps * DT < 20.0,
"the car drives in by the driveway and parks by the house (%.1f s)" % (steps * DT))
r.check(int(sim.audio.played.get("horn", 0)) == horn + 1 and ending._farmers[0].visible and ending._farmers[1].visible,
"with a honk, and the farmers get out")
while not ending.done and steps < 9000:
ending.step(DT)
steps += 1
var at := true
for i in 2:
at = at and ending._farmers[i].global_position.distance_to(FarmersReturn.FARMER_SPOTS[i]) < 0.1 \
and ending._anims[i].current_animation == &"Cheering"
r.check(ending.done and ending.stage == "end" and at and steps * DT < 35.0,
"they walk to the door, wave, and cheer (%.1f s in all)" % (steps * DT))
r.info("farmers' return: %.1f s in all" % (steps * DT))
var panel := sim.end_panel
panel._process(0.1)
r.check(panel.is_visible_in_tree() and _hud_visible() and panel.mode == "assessment" and panel._title.text == "The farmers are home!"
and panel._rating.text.contains("points") and panel._bars.visible and panel._menu.visible and panel._menu.has_focus()
and not panel._retry.visible, "then the final assessment ('%s')" % panel._rating.text)
var a := Assessment.of(c.state, cfg)
r.check(panel._rating.text == "%s · %d points" % [a["tier"], a["score"]] and panel._stats.text.contains("Enemies defeated: 40 crows and 8 thieves")
and panel._stats.text.contains("Gathered 48 wood"), "with the rating, the shares kept, and the vacation's totals")
r.info("assessment: %s\n%s\n%s" % [panel._rating.text, panel._detail.text, panel._stats.text])
ending.clear()
ending.start()
ending.skip()
r.check(ending.done and ending._farmers[0].global_position.distance_to(FarmersReturn.FARMER_SPOTS[0]) < 0.01
and ending._car.global_position.distance_to(park) < 0.3, "skipping jumps to the end")
panel._menu.pressed.emit()
r.check(main.screen == Main.Screen.MENU and c.state.night == 1 and not ending.running and not SaveGame.exists(SAVE)
and main.main_menu.continue_button.disabled, "Main menu after the ending: a fresh farm behind the menu, nothing to continue")
func _audio() -> void:
var audio := sim.audio
var missing: Array[String] = []
for cue: String in FarmAudio.CUES:
var bus := String(FarmAudio.CUES[cue].get("bus", "SFX"))
if (audio.streams.get(cue, []) as Array).is_empty() or AudioServer.get_bus_index(bus) < 0:
missing.append(cue)
r.check(missing.is_empty(), "every sound cue has its sounds and its bus (%d cues; missing: %s)" % [FarmAudio.CUES.size(), missing])
r.check(audio._day.playing and audio._night.playing and (audio._day.stream as AudioStreamWAV).loop_mode == AudioStreamWAV.LOOP_FORWARD
and audio._day.bus == &"Ambience", "the day and night ambience loop on the Ambience bus")
main.new_vacation()
var before := audio.played.duplicate()
var count := func(cue: String) -> int: return int(audio.played.get(cue, 0)) - int(before.get(cue, 0))
sim.combat.fired.emit()
c.begin_day()
var day_music := audio.music_track
c.advance_phase()
var dusk_music := audio.music_track
r.check(count.call("shot") == 1 and count.call("bell") == 1 and count.call("dusk") == 1, "the gun, the dusk bell, and the dusk stinger play")
var id := sim.structures.place("fence", 2.0, 8.0, 0)
sim.structures.damage(id, 3)
sim.structures.damage(id, 999)
r.check(count.call("build") == 1 and count.call("structure_hit") == 1 and count.call("smash") == 1 and count.call("breach") == 1,
"building, a hit, and a broken fence (with the breach alarm)")
sim.scarecrow.try_damage(1)
r.check(count.call("hurt") == 1, "the scarecrow's hurt sound")
c.advance_phase()
var night_music := audio.music_track
c.advance_phase()
r.check(day_music == "farm" and dusk_music == "" and night_music == "night" and audio.music_track == "",
"music by phase: the farm tune by day, Purgatory at night, only ambience at dusk and dawn")
r.check((audio._music["farm"] as AudioStreamPlayer).bus == &"Music" and ((audio._music["night"] as AudioStreamPlayer).stream as AudioStreamOggVorbis).loop
and ((audio._music["farm"] as AudioStreamPlayer).stream as AudioStreamWAV).loop_mode == AudioStreamWAV.LOOP_FORWARD,
"both tracks loop on the Music bus")
audio._last.erase("crow_arrive")
r.check(audio.play("crow_arrive") and not audio.play("crow_arrive"), "a cue rests for its gap (no caw pile-ups)")
r.check(main.main_menu.new_button.has_meta(&"sounds") and sim.review_panel._start.has_meta(&"sounds"),
"menu and panel buttons have hover and click sounds")
main.to_menu()

View file

@ -0,0 +1 @@
uid://6yaguapi3704

278
game/tests/test_nights.gd Normal file
View file

@ -0,0 +1,278 @@
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() == 3 and waves_5 >= 3 and n[4].night_length > sim.config.night_length,
"night 5: all three types 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 change the systems they're about, can't be bought twice 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}
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)")
for id in Upgrades.ORDER:
spent += _sum(Upgrades.cost(cfg, id))
var text := Upgrades.buy(c, id, st)
r.check(Upgrades.owned(s, id) and text.contains("done:"), "bought %s: '%s'" % [id, text])
r.check(s.resources.shed_total() == shed - spent, "all %d cost %d materials together" % [Upgrades.ORDER.size(), spent])
r.check(player.can_sprint(), "sprint: the scarecrow can sprint")
r.check(Upgrades.buy(c, "rapid_fire", st).contains("already done"), "an upgrade can't be bought twice")
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, "rapid_fire") == "Done" and Upgrades.buy(c, "long_range", 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.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)

View file

@ -0,0 +1 @@
uid://bxtlwyndaeris

View file

@ -1,7 +1,8 @@
extends RefCounted
## Outcome rules: scarecrow destruction, a stripped farm (only categories in play count),
## completing the vacation, the failure-before-completion tie policy, failure in every phase,
## and terminal phases staying terminal.
## Outcome rules: scarecrow destruction, a stripped farm (all three categories; only those in
## play count; supplies only when thieves emptied the shed), completing the vacation, the
## failure-before-completion tie policy, failure in every phase, and terminal phases staying
## terminal.
const O := CampaignController.Outcome
const P := CampaignController.Phase
@ -18,20 +19,34 @@ func run(r: GameTestRunner) -> void:
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "0 HP is a Game Over")
s = FarmState.create(cfg)
s.crops = 0
s.animals_total = 0
s.supplies_total = 0
s.lose_all_crops()
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "with only crops in play, no crops left is a stripped farm")
s = _all_categories(cfg)
s.crops = 0
s = FarmState.create(cfg)
s.lose_all_crops()
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "losing every crop alone does not end the game")
s.animals = 0
s.lose_all_animals()
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "losing crops and animals with supplies left does not end the game")
s.supplies = 0
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "losing every category ends the game")
for m in ResourceStore.MATERIALS:
s.resources.shed[m] = 0
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "spending the last supplies doesn't strip the farm")
s.shed_raided = true
s.supplies_in_transit = 5
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "a sack of supplies still on the farm keeps it going")
s.supplies_in_transit = 0
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "losing every category ends the game (thieves emptied the shed)")
s.resources.shed["straw"] = 2
s.settle_supplies()
s.resources.shed["straw"] = 0
r.check(not s.shed_raided and CampaignController.check_outcome(s, n) == O.CONTINUE,
"storing anything clears the raid: spending it again doesn't strip the farm")
s = FarmState.create(cfg)
s.crops_total = 0
s.crops = 0
s.animals_total = 0
s.supplies_total = 0
r.check(not s.is_stripped(), "a farm with nothing in play is not 'stripped'")
s = FarmState.create(cfg)
@ -44,7 +59,7 @@ func run(r: GameTestRunner) -> void:
s.scarecrow_hp = 0
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "tie: scarecrow destroyed on the final night loses")
s.scarecrow_hp = 1
s.crops = 0
s.strip()
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "tie: farm stripped on the final night loses")
s.scarecrow_hp = 0
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "scarecrow destruction is reported before a stripped farm")
@ -54,15 +69,6 @@ func run(r: GameTestRunner) -> void:
_terminal(r)
func _all_categories(cfg: GameConfig) -> FarmState:
var s := FarmState.create(cfg)
s.animals_total = 8
s.animals = 8
s.supplies_total = 50
s.supplies = 50
return s
func _failure_in_every_phase(r: GameTestRunner) -> void:
for phase: CampaignController.Phase in [P.MORNING, P.DAY, P.DUSK, P.NIGHT, P.DAWN]:
var c := r.make_campaign()
@ -75,7 +81,7 @@ func _failure_in_every_phase(r: GameTestRunner) -> void:
"scarecrow destroyed during %s ends the game once" % P.keys()[phase])
c = r.make_campaign()
GameTestRunner.run_until(c, phase)
c.state.crops = 0
c.state.strip()
c.tick(GameTestRunner.TICK)
r.check(c.state.phase == P.GAME_OVER and c.outcome == O.GAME_OVER_STRIPPED,
"farm stripped during %s ends the game" % P.keys()[phase])

366
game/tests/test_roster.gd Normal file
View file

@ -0,0 +1,366 @@
extends RefCounted
## The enemy roster (Step 9) on the real farm, with FarmSim stepped by hand at 60 Hz: the type
## table; crows flying over fences and traps but shot down by automated defenses, and never
## fighting; ground thieves going only for animals and supplies; fence breakers smashing the
## barriers that guard valuables, opening gaps other thieves walk through, and turning on the
## scarecrow; the character pool for ground enemies; the alert manager's grouping, priorities,
## escalation, and cap; and the debug scenarios.
const P := CampaignController.Phase
const C := LootSystem.Category
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
player.global_position = AWAY
sim.campaign.begin_day()
sim.campaign.state.resources.shed = {"wood": 60, "scrap": 60, "straw": 60}
_table(r, sim)
_crows(r, sim, player)
_thieves(r, sim, player)
_breakers(r, sim, player)
_characters(r, sim)
_alerts(r, farm, sim, player)
_scenarios(r, farm, sim)
farm.queue_free()
await r.process_frame
func _table(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var ok := es.t_flying[EnemySystem.TYPE_CROW] == 1 and es.t_flying[EnemySystem.TYPE_THIEF] == 0 and es.t_flying[EnemySystem.TYPE_BREAKER] == 0
ok = ok and es.t_targets[EnemySystem.TYPE_CROW] == 1 << C.CROP
ok = ok and es.t_targets[EnemySystem.TYPE_THIEF] == (1 << C.ANIMAL) | (1 << C.SUPPLY)
ok = ok and es.t_targets[EnemySystem.TYPE_BREAKER] == 0 and es.t_breaks[EnemySystem.TYPE_BREAKER] == 1
r.check(ok, "the type table: crows fly after crops, thieves walk after animals and supplies, fence breakers after structures")
r.check(es.t_hp[EnemySystem.TYPE_CROW] == 1 and es.t_hp[EnemySystem.TYPE_THIEF] == 3 and es.t_hp[EnemySystem.TYPE_BREAKER] == 6
and es.t_speed[EnemySystem.TYPE_CROW] > es.t_speed[EnemySystem.TYPE_THIEF] and es.t_speed[EnemySystem.TYPE_THIEF] > es.t_speed[EnemySystem.TYPE_BREAKER]
and es.t_structure_damage[EnemySystem.TYPE_BREAKER] > es.t_structure_damage[EnemySystem.TYPE_THIEF],
"crows are fast and fragile, breakers slow, tough, and heavy-handed")
## Crows ignore fences and traps, but not automated defenses, and never fight.
func _crows(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
var st := sim.structures
var loot := sim.loot
# A wall of fences across its way, and a trap under it.
var fences: Array[int] = []
for k in 6:
fences.append(st.place("fence", 47.0 - 0.6, -9.0 + 2.0 * k, 2))
var trap := st.place("slowing_trap", 44.5, -3.0, 0)
_settle(sim)
var h := es.spawn(EnemySystem.TYPE_CROW, 52.0, -3.0, Vector2.LEFT)
var d := es.resolve_handle(h)
_step(sim, 1)
var unit := es.target[d]
r.check(unit > 0 and loot.category[unit] == C.CROP, "a crow goes for a crop")
var crossed := false
var slowed := false
var t := 0.0
while t < 20.0 and es.resolve_handle(h) >= 0 and es.state[es.resolve_handle(h)] == T.SEEK:
sim.step(DT)
t += DT
d = es.resolve_handle(h)
if d >= 0:
crossed = crossed or (es.pos_x[d] < 46.0 and absf(es.pos_z[d] + 3.0) < 2.0)
slowed = slowed or es.slow_left[d] > 0.0
d = es.resolve_handle(h)
r.check(crossed and d >= 0 and es.state[d] == T.STEAL, "it flies straight over a fence line to its crop (%.1f s)" % t)
r.check(not slowed and int(sim.campaign.state.structure(trap)["hp"]) == sim.config.trap_triggers, "a slowing trap does nothing to it")
r.check(fences.all(func(id: int) -> bool: return int(sim.campaign.state.structure(id)["hp"]) == sim.config.fence_hp), "and it breaks nothing")
# Standing right next to the scarecrow, it doesn't fight.
player.global_position = Vector3(es.pos_x[d] + 0.5, 0.0, es.pos_z[d])
var attacks := es.attacks_attempted
_step(sim, 90)
r.check(es.attacks_attempted == attacks, "a crow never attacks the scarecrow")
player.global_position = AWAY
es.apply_hit_handle(h, 99)
_step(sim, 1)
for id in fences:
st.dismantle(id)
st.dismantle(trap)
# An automated defense in its way shoots it down.
var turret := st.place("automated_defense", 42.0, -3.0, 0)
_settle(sim)
h = es.spawn(EnemySystem.TYPE_CROW, 52.0, -3.0, Vector2.LEFT)
var gone := _until(sim, func() -> bool: return es.resolve_handle(h) < 0, 15.0)
r.check(gone < 15.0 and es.kills >= 2, "an automated defense shoots a crow down (%.1f s)" % gone)
st.dismantle(turret)
_settle(sim)
## Ground thieves go only for animals and supplies.
func _thieves(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
var loot := sim.loot
var s := sim.campaign.state
var h := sim.spawn_enemy(EnemySystem.TYPE_THIEF, C.CROP, GameTestRunner.EDGE["east"])
_step(sim, 1)
var item := es.target[es.resolve_handle(h)]
r.check(item > 0 and loot.category[item] != C.CROP, "a thief sent for crops goes for %s instead" % LootSystem.CATEGORY_KEYS[loot.category[item]])
es.apply_hit_handle(h, 99)
_step(sim, 1)
# A hit while it fills a sack restarts it.
h = sim.spawn_enemy(EnemySystem.TYPE_THIEF, C.SUPPLY, GameTestRunner.EDGE["north"])
_until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.STEAL, 40.0)
_step(sim, 60)
var d := es.resolve_handle(h)
var sack := es.target[d]
r.check(loot.progress[sack] > 0.2, "it fills a sack (%.0f %%)" % (loot.progress[sack] * 100.0))
es.apply_hit(d)
r.check(es.timer[d] == 0.0 and loot.progress[sack] == 0.0 and es.health[d] == es.t_hp[EnemySystem.TYPE_THIEF] - 1,
"a hit while stealing restarts the theft")
es.apply_hit(d, 99)
_step(sim, 1)
# Nothing of its own left: it leaves, though the crops are still there.
var keep := s.lost_animals.duplicate()
var shed: Dictionary = s.resources.shed.duplicate()
s.lose_all_animals()
loot.sync_from_state()
for m in ResourceStore.MATERIALS:
s.resources.shed[m] = 0
h = sim.spawn_enemy(EnemySystem.TYPE_THIEF, LootSystem.ANY, GameTestRunner.EDGE["east"])
var events: Array[StringName] = []
var listen := func(kind: StringName, _id: int, _p: Vector3) -> void: events.append(kind)
loot.loot_event.connect(listen)
_step(sim, 2)
loot.loot_event.disconnect(listen)
d = es.resolve_handle(h)
r.check((d < 0 or es.state[d] == T.RETREAT) and not events.has(&"targeted") and s.crops > 0,
"with no animals or supplies left it claims nothing and leaves, crops or not")
if d >= 0:
es.apply_hit(d, 99)
_step(sim, 1)
s.lost_animals = keep
s.resources.shed = shed
loot.sync_from_state()
sim.animals.sync_from_state()
player.global_position = AWAY
## Fence breakers smash what guards the valuables, open gaps thieves walk through, and fight.
func _breakers(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
var st := sim.structures
var s := sim.campaign.state
var gate := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)]
var far_fence := st.place("fence", 25.0, -30.0, 0) # guards nothing
var shed_fence := st.place("fence", 1.0, -12.0, 0) # by the shed
_settle(sim)
var broken: Array[int] = []
st.destroyed.connect(func(id: int, _t: String, _at: Vector3) -> void: broken.append(id))
var h := sim.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["south-west"])
var at := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.BREAK, 40.0)
var d := es.resolve_handle(h)
var first := es.barrier[d]
var first_type := _type_of(sim, first)
r.check(at < 40.0 and (first == gate or first == shed_fence), "a fence breaker walks to a barrier guarding valuables (%.1f s; the %s)" % [at, first_type])
r.check(es.target[d] < 0 and es.carry[d] < 0, "it claims nothing to steal")
var took := _until(sim, func() -> bool: return broken.has(first), 20.0)
var hits := ceili(float(st.max_hp(first_type)) / es.t_structure_damage[EnemySystem.TYPE_BREAKER])
r.check(took < (hits - 1) * es.t_hit_interval[EnemySystem.TYPE_BREAKER] + 1.0, "it smashes it in %d heavy hits (%.1f s)" % [hits, took])
var second := _until(sim, func() -> bool:
var dd := es.resolve_handle(h)
return dd >= 0 and es.state[dd] == T.BREAK and es.barrier[dd] != first, 40.0)
d = es.resolve_handle(h)
r.check(second < 40.0 and (es.barrier[d] == gate or es.barrier[d] == shed_fence), "then it goes for the next guarding barrier (%.1f s)" % second)
_until(sim, func() -> bool: return broken.has(gate) and broken.has(shed_fence), 30.0)
r.check(not broken.has(far_fence) and not s.structure(far_fence).is_empty(), "guarding barriers come first: a fence guarding nothing still stands")
# Thieves walk through the breach.
var thief := sim.spawn_enemy(EnemySystem.TYPE_THIEF, C.ANIMAL, GameTestRunner.EDGE["west"])
var breaks := 0
var t := 0.0
while t < 40.0 and es.resolve_handle(thief) >= 0 and es.state[es.resolve_handle(thief)] != T.CARRY:
sim.step(DT)
t += DT
if es.resolve_handle(thief) >= 0 and es.state[es.resolve_handle(thief)] == T.BREAK:
breaks += 1
r.check(t < 40.0 and breaks == 0, "a thief walks in through the gap it opened and takes an animal (%.1f s, no breaking)" % t)
es.apply_hit_handle(thief, 99)
_step(sim, 1)
# With nothing guarding valuables left, it hunts the scarecrow.
st.dismantle(far_fence)
_settle(sim)
player.global_position = Vector3(-6.0, 0.0, 10.0)
var hunting := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.FIGHT, 10.0)
var hp := s.scarecrow_hp
var reached := _until(sim, func() -> bool: return s.scarecrow_hp < hp, 40.0)
r.check(hunting < 10.0 and reached < 40.0 and hp - s.scarecrow_hp == es.t_damage[EnemySystem.TYPE_BREAKER],
"with nothing left to break it hunts the scarecrow down and hits it hard (-%d HP, %.1f s)" % [hp - s.scarecrow_hp, reached])
player.global_position = AWAY
es.apply_hit_handle(h, 99)
_step(sim, 1)
# Shot from range, a breaker turns on the scarecrow; it takes 6 hits.
st.place("gate", 4.0, -6.0, 2)
_settle(sim)
h = sim.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["south-west"])
_step(sim, 30)
d = es.resolve_handle(h)
es.apply_hit(d)
r.check(es.state[d] == T.FIGHT, "shot, it turns on the scarecrow")
for k in es.t_hp[EnemySystem.TYPE_BREAKER] - 2:
es.apply_hit(d)
_step(sim, 1)
r.check(es.resolve_handle(h) >= 0, "five hits don't stop it")
es.apply_hit_handle(h)
_step(sim, 1)
r.check(es.resolve_handle(h) < 0, "the sixth does")
s.scarecrow_hp = s.scarecrow_max_hp
_settle(sim)
## Ground enemies are drawn by pooled characters; flyers aren't.
func _characters(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var ch := sim.characters
var thieves := ch.free_count(EnemySystem.TYPE_THIEF)
r.check(thieves == EnemyCharacters.POOL[EnemySystem.TYPE_THIEF] and ch.in_use() == 0, "%d thief characters waiting in the pool (%d of them corpses still fading)" % [thieves, ch.corpses()])
var crow := es.spawn(EnemySystem.TYPE_CROW, 20.0, -30.0, Vector2.UP)
var handles: Array[int] = []
for k in thieves + 2:
handles.append(es.spawn(EnemySystem.TYPE_THIEF, 12.0 + k * 0.7, -30.0, Vector2.UP)) # all inside the farm's edge
var spawned := handles.filter(func(hh: int) -> bool: return hh >= 0).size()
r.check(crow >= 0 and spawned == thieves and ch.in_use() == thieves and ch.free_count(EnemySystem.TYPE_THIEF) == 0,
"one character per ground enemy, none for a crow; past the pool, spawns are skipped (%d of %d)" % [spawned, handles.size()])
var corpses := ch.corpses()
es.apply_hit_handle(handles[0], 99)
_step(sim, 1)
r.check(ch.in_use() == thieves - 1 and ch.corpses() == corpses + 1 and ch.free_count(EnemySystem.TYPE_THIEF) == 1,
"a killed thief's character lies there a moment, free to be taken over")
var again := es.spawn(EnemySystem.TYPE_THIEF, 25.0, -30.0, Vector2.UP)
r.check(again >= 0 and ch.in_use() == thieves and ch.corpses() == corpses, "a new thief takes it over")
handles.append(again)
for hh in handles + [crow]:
if hh >= 0:
es.apply_hit_handle(hh, 99)
_step(sim, 1)
ch._process(EnemyCharacters.CORPSE_TIME + 0.1)
## The alert manager groups alerts by kind, type, and zone, orders them, escalates escapes, and
## caps how many show.
func _alerts(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: PlayerCharacter) -> void:
var am := farm.get_node("Hud/Alerts") as AlertManager
var es := sim.enemies
var loot := sim.loot
var keep := es.behavior
es.behavior = null # everyone holds still where they're put
var crows: Array[int] = []
var units: Array[int] = []
for k in 3:
var u := _home_crop(loot, units)
units.append(u)
var h := es.spawn(EnemySystem.TYPE_CROW, loot.home[u].x, loot.home[u].y, Vector2.UP)
loot.holder[u] = h
crows.append(h)
var list := am.collect()
var theft := list.filter(func(a: Dictionary) -> bool: return a["kind"] == AlertManager.Kind.THEFT)
r.check(theft.size() == 1 and int(theft[0]["count"]) == 3 and theft[0]["label"] == "3 crows — Crop Field",
"three crows at the crops make one alert: '%s'" % (theft[0]["label"] if not theft.is_empty() else "-"))
# A carrier near the fence outranks one in the middle of the field, and both outrank thefts.
var near := _carrier(sim, Vector2(45.5, 5.0), _home_crop(loot, units))
var mid := _carrier(sim, Vector2(30.0, -3.0), _home_crop(loot, units))
list = am.collect()
var escapes := list.filter(func(a: Dictionary) -> bool: return a["kind"] == AlertManager.Kind.ESCAPE)
r.check(escapes.size() == 1 and int(escapes[0]["count"]) == 2, "two crows escaping from the field are grouped too")
r.check(list[0]["kind"] == AlertManager.Kind.ESCAPE and float(list[0]["escalation"]) > 0.7 and String(list[0]["label"]).contains("!"),
"escapes come first, escalated by the one nearly out: '%s'" % list[0]["label"])
var raw: Array[Dictionary] = [am._alert(AlertManager.Kind.ESCAPE, EnemySystem.TYPE_CROW, C.CROP, Vector2(45.5, 5.0), am._escalation(es.resolve_handle(near), Vector2(45.5, 5.0))),
am._alert(AlertManager.Kind.ESCAPE, EnemySystem.TYPE_CROW, C.CROP, Vector2(30.0, -3.0), am._escalation(es.resolve_handle(mid), Vector2(30.0, -3.0)))]
r.check(float(raw[0]["escalation"]) > float(raw[1]["escalation"]), "escape alerts escalate as the carrier nears its exit (%.2f > %.2f)" % [raw[0]["escalation"], raw[1]["escalation"]])
# A breach outranks a theft; at most MAX_SHOWN show.
var many: Array[Dictionary] = []
for k in 8:
many.append(am._alert(AlertManager.Kind.LOOSE if k % 2 == 0 else AlertManager.Kind.THEFT, k % 3, k % 3, Vector2(-10.0 + k * 7.0, -40.0 + k * 6.0), 0.0))
many.append(am._alert(AlertManager.Kind.BREACH, -1, -1, Vector2(3.5, -6.0), 1.0))
var sorted := AlertManager.sort_alerts(AlertManager.group_alerts(many))
var shown := AlertManager.cap(sorted, AlertManager.MAX_SHOWN)
r.check(sorted[0]["kind"] == AlertManager.Kind.BREACH and sorted[0]["label"] == "Breach! — Animal Pen", "a breach comes before thefts: '%s'" % sorted[0]["label"])
r.check(sorted.size() > AlertManager.MAX_SHOWN and shown.size() == AlertManager.MAX_SHOWN and shown[0] == sorted[0],
"of %d alerts, the top %d show" % [sorted.size(), AlertManager.MAX_SHOWN])
es.behavior = keep
for hh in crows + [near, mid]:
es.apply_hit_handle(hh, 99)
_step(sim, 1)
loot.return_dropped()
player.global_position = AWAY
## Debug scenarios (F2): one enemy type at a time, then pairs, then all three.
func _scenarios(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
var dbg := farm.get_node("CampaignDebug") as CampaignDebug
var c := sim.campaign
var titles: Array[String] = []
for k in CampaignDebug.SCENARIOS.size():
dbg.cycle_scenario()
titles.append(sim.waves.debug_plan.title if sim.waves.debug_plan != null else "")
r.check(not titles.has("") and titles.size() == 6, "F2 cycles through %d scenarios: %s" % [titles.size(), ", ".join(titles)])
r.check(sim.waves.tonight() == sim.waves.debug_plan and sim.waves.debug_plan.title == "All three", "the scenario is tonight's plan")
var types := {}
sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void: types[sim.enemies.type[sim.enemies.resolve_handle(h)]] = true)
var skipped_before := sim.enemies.spawn_skipped
sim.waves.enabled = true
while c.state.phase != P.NIGHT:
if c.state.phase == P.MORNING:
c.begin_day()
else:
c.advance_phase()
_step(sim, 60 * 45)
r.check(types.size() == 3, "'All three' sends in crows, thieves, and a fence breaker (%s; %d spawns skipped)" % [types.keys(), sim.enemies.spawn_skipped - skipped_before])
dbg.cycle_scenario()
r.check(sim.waves.debug_plan == null and sim.waves.tonight() == sim.waves.plan_for(c.state.night), "and back to the night's own plan")
sim.waves.enabled = false
func _carrier(sim: FarmSim, p: Vector2, unit: int) -> int:
var es := sim.enemies
var h := es.spawn(EnemySystem.TYPE_CROW, p.x, p.y, Vector2.RIGHT)
sim.loot.holder[unit] = h
sim.loot.pick_up(unit, h)
es.carry[es.resolve_handle(h)] = unit
es.state[es.resolve_handle(h)] = T.CARRY
return h
func _home_crop(loot: LootSystem, not_these: Array[int]) -> int:
for id in range(1, loot.unit_count + 1):
if loot.status[id] == LootSystem.Status.HOME and loot.holder[id] == -1 and not not_these.has(id):
return id
return -1
func _type_of(sim: FarmSim, id: int) -> String:
var e := sim.campaign.state.structure(id)
return String(e.get("type", "gate"))
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)
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

View file

@ -0,0 +1 @@
uid://bod0f1rp68iwq

253
game/tests/test_save.gd Normal file
View file

@ -0,0 +1,253 @@
extends RefCounted
## Saving and settings without the farm scene: a save written and read back reproduces the farm
## state field for field; missing, damaged, newer, and too-old saves are refused with a reason
## and version 2 saves are upgraded; the campaign autosaves every morning, a retry restores that
## morning, and finishing the vacation deletes the save; settings persist, fall back on bad
## values, and apply to the audio buses, the dead zones, and the config; and the final
## assessment's score and tiers.
const P := CampaignController.Phase
const SAVE := "user://test_savegame.json"
const SETTINGS := "user://test_settings.cfg"
func run(r: GameTestRunner) -> void:
_clean()
_round_trip(r)
_bad_saves(r)
_migration(r)
_autosave(r)
_settings(r)
_assessment(r)
_clean()
func _clean() -> void:
for p in [SAVE, SAVE + ".tmp", SETTINGS]:
if FileAccess.file_exists(p):
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
## A morning with something in every field.
static func busy_state(cfg: GameConfig) -> FarmState:
var s := FarmState.create(cfg)
s.night = 3
s.nights_survived = 2
s.phase = P.MORNING
s.scarecrow_max_hp = 12
s.scarecrow_hp = 7
s.lose_crop(4)
s.lose_crop(17)
s.lose_animal(2)
s.resources.shed = {"wood": 13, "scrap": 2, "straw": 21}
s.resources.pouch = {"wood": 0, "scrap": 3, "straw": 1}
s.gather_charges = {"DeadTree": 1, "Haystack": 0}
s.upgrades = {"rapid_fire": 1, "sticky_tar": 1}
s.structures.append({"id": s.next_structure_id, "type": "fence", "x": 30.5, "z": -18.5, "rot": 3, "hp": 11})
s.next_structure_id += 1
s.structures.append({"id": s.next_structure_id, "type": "slowing_trap", "x": 12.0, "z": -7.25, "rot": 0, "hp": 2})
s.next_structure_id += 1
for n in [1, 2]:
var e := {"night": n, "crops_lost": n, "animals_lost": n - 1}
for k in FarmState.EVENTS:
e[k] = n * 3 + FarmState.EVENTS.find(k)
s.night_log.append(e)
return s
func _round_trip(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var s := busy_state(cfg)
var before := s.to_dict()
var err := SaveGame.write(before, SAVE)
r.check(err == OK and FileAccess.file_exists(SAVE) and not FileAccess.file_exists(SAVE + ".tmp"),
"the save is written (through a temporary file that's renamed into place)")
var loaded := SaveGame.read(SAVE)
r.check(loaded.status == SaveGame.Status.OK and loaded.state != null and loaded.message == "" and loaded.saved_at != "",
"and reads back (saved at %s)" % loaded.saved_at)
if loaded.state == null:
return
var after := loaded.state.to_dict()
var differ: Array[String] = []
for key in before:
if JSON.stringify(before[key], "", true, true) != JSON.stringify(after.get(key), "", true, true):
differ.append(key)
r.check(differ.is_empty() and before.size() == after.size(), "saving then loading reproduces the farm state field for field (differ: %s)" % [differ])
r.check(loaded.state.crops == s.crops and loaded.state.animals == s.animals and loaded.state.supplies == s.supplies
and loaded.state.structures[-2]["x"] == 30.5 and loaded.state.structures[-1]["z"] == -7.25
and loaded.state.night_log[1]["killed_crow"] == s.night_log[1]["killed_crow"],
"derived counts, positions, and the nightly records survive")
func _bad_saves(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
_clean()
var missing := SaveGame.read(SAVE)
r.check(missing.status == SaveGame.Status.MISSING and missing.state == null and missing.message == "No saved vacation",
"no save: MISSING")
_write_text("{ this is not json")
var garbage := SaveGame.read(SAVE)
r.check(garbage.status == SaveGame.Status.CORRUPT and garbage.state == null and garbage.message.contains("damaged"),
"unreadable JSON: CORRUPT ('%s')" % garbage.message)
_write_text(JSON.stringify({"game": "another-game", "state": {}}))
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "another game's file: CORRUPT")
var d := busy_state(cfg).to_dict()
d["scarecrow_hp"] = 99 # more than its maximum
SaveGame.write(d, SAVE)
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a state that breaks the rules: CORRUPT")
d = busy_state(cfg).to_dict()
d["phase"] = int(P.NIGHT)
SaveGame.write(d, SAVE)
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a save that isn't a morning: CORRUPT")
d = busy_state(cfg).to_dict()
d.erase("night_log")
SaveGame.write(d, SAVE)
r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a missing field: CORRUPT")
d = busy_state(cfg).to_dict()
d["version"] = FarmState.VERSION + 1
SaveGame.write(d, SAVE)
var newer := SaveGame.read(SAVE)
r.check(newer.status == SaveGame.Status.NEWER and newer.state == null and newer.version == FarmState.VERSION + 1
and newer.message.contains("newer"), "a save from a newer version: NEWER, not loaded")
d["version"] = 1
SaveGame.write(d, SAVE)
var old := SaveGame.read(SAVE)
r.check(old.status == SaveGame.Status.OLD and old.state == null and old.message.contains("older"),
"a save from version 1 (no way forward): OLD, not loaded")
func _migration(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var s := busy_state(cfg)
var d := s.to_dict()
d["version"] = 2
var v2_keys := ["night", "crops_lost", "animals_lost", "supplies_lost", "crops_stolen", "crops_recovered",
"animals_stolen", "animals_strayed", "animals_recovered", "supplies_stolen", "supplies_recovered"]
for e: Dictionary in d["night_log"]:
for k in e.keys():
if not v2_keys.has(k):
e.erase(k)
SaveGame.write(d, SAVE)
var loaded := SaveGame.read(SAVE)
r.check(loaded.status == SaveGame.Status.OK and loaded.version == 2, "a version 2 save is upgraded and loads")
if loaded.state == null:
return
var e: Dictionary = loaded.state.night_log[1]
r.check(e["crops_stolen"] == s.night_log[1]["crops_stolen"] and e["killed_crow"] == 0 and e["gathered_wood"] == 0
and loaded.state.scarecrow_hp == 7 and loaded.state.structures.size() == s.structures.size(),
"keeping what it had and counting the new nightly records from zero")
func _autosave(r: GameTestRunner) -> void:
_clean()
var c := r.make_campaign()
c.save_path = SAVE
c.new_campaign()
var first := SaveGame.read(SAVE)
r.check(first.status == SaveGame.Status.OK and first.state.night == 1 and c.last_save_error == OK,
"a new vacation is saved at once (the morning of night 1)")
GameTestRunner.run_until(c, P.DAY)
c.state.resources.shed["wood"] = 99
GameTestRunner.run_until(c, P.NIGHT)
GameTestRunner.run_until(c, P.MORNING)
var second := SaveGame.read(SAVE)
r.check(second.status == SaveGame.Status.OK and second.state.night == 2 and second.state.resources.shed["wood"] == 99
and second.state.night_log.size() == 1, "every morning is autosaved (now the morning of night 2)")
var morning := c.state.to_dict()
GameTestRunner.run_until(c, P.NIGHT)
c.state.scarecrow_hp = 1
GameTestRunner.lose_crops(c.state, 5)
r.check(c.retry_night() and JSON.stringify(c.state.to_dict(), "", true, true) == JSON.stringify(morning, "", true, true)
and JSON.stringify(SaveGame.read(SAVE).state.to_dict(), "", true, true) == JSON.stringify(morning, "", true, true),
"retry restores the morning state, which is also what's saved")
var guard := 0
while not c.is_over() and guard < 100:
GameTestRunner.run_until(c, P.MORNING if c.state.phase != P.MORNING else P.DAY)
guard += 1
r.check(c.outcome == CampaignController.Outcome.VACATION_COMPLETE and not SaveGame.exists(SAVE),
"finishing the vacation deletes the save (nothing left to continue)")
c.queue_free()
var quiet := r.make_campaign()
r.check(quiet.save_path == "" and not SaveGame.exists(SAVE), "without a save path nothing is written")
quiet.queue_free()
func _settings(r: GameTestRunner) -> void:
_clean()
var fresh := GameSettings.load_from(SETTINGS)
r.check(fresh.volume == GameSettings.DEFAULT_VOLUME and fresh.show_tips and fresh.vsync and not fresh.fullscreen
and fresh.resolution_scale == 1.0, "no settings file: the defaults")
var g := GameSettings.new()
g.volume = {"Master": 0.5, "Music": 0.25, "SFX": 0.0, "Ambience": 1.0, "Voice": 0.6}
g.move_dead_zone = 0.35
g.aim_dead_zone = 0.15
g.fullscreen = true
g.vsync = false
g.resolution_scale = 0.75
g.show_tips = false
g.player_name = "Ana"
g.microphone = false
r.check(g.save_to(SETTINGS) == OK, "settings save")
var back := GameSettings.load_from(SETTINGS)
r.check(back.volume == g.volume and back.move_dead_zone == 0.35 and back.aim_dead_zone == 0.15 and back.fullscreen
and not back.vsync and back.resolution_scale == 0.75 and not back.show_tips and back.player_name == "Ana"
and not back.microphone, "and load back unchanged (co-op name and microphone too)")
var f := ConfigFile.new()
f.set_value("audio", "master", 7.0)
f.set_value("audio", "music", "loud")
f.set_value("display", "fullscreen", "yes")
f.set_value("display", "resolution_scale", 0.1)
f.save(SETTINGS)
var odd := GameSettings.load_from(SETTINGS)
r.check(odd.volume["Master"] == 1.0 and odd.volume["Music"] == GameSettings.DEFAULT_VOLUME["Music"] and not odd.fullscreen
and odd.resolution_scale == 0.5, "out-of-range and wrong-typed values are clamped or fall back")
var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
g.apply(null, cfg)
var music := AudioServer.get_bus_index("Music")
var sfx := AudioServer.get_bus_index("SFX")
r.check(music >= 0 and sfx >= 0 and AudioServer.get_bus_index("Ambience") >= 0, "the audio buses exist (Master, Music, SFX, Ambience)")
r.check(is_equal_approx(AudioServer.get_bus_volume_db(music), linear_to_db(0.25)) and AudioServer.is_bus_mute(sfx)
and not AudioServer.is_bus_mute(music), "volumes apply to the buses (and zero mutes)")
r.check(is_equal_approx(InputMap.action_get_deadzone("move_left"), 0.35) and is_equal_approx(cfg.aim_dead_zone, 0.15),
"dead zones apply to the move actions and the aim")
GameSettings.new().apply(null, cfg) # back to the defaults for the other suites
func _assessment(r: GameTestRunner) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var s := FarmState.create(cfg)
GameTestRunner.lose_crops(s, 3)
s.lose_animal(1)
s.lose_animal(2)
var e := {"night": 1, "crops_lost": 3, "animals_lost": 2}
for k in FarmState.EVENTS:
e[k] = 0
e["gathered_wood"] = 50
e["gathered_straw"] = 40
e["supplies_lost"] = 4
s.night_log.append(e)
var a := Assessment.of(s, cfg)
var handled := s.supplies_total + 90
var want := roundi(100.0 * (0.5 * 27.0 / 30.0 + 0.3 * 6.0 / 8.0 + 0.2 * (1.0 - 4.0 / handled)))
r.check(a["score"] == want and a["tier"] == "Bumper crop" and a["supplies_handled"] == handled and a["supplies_lost"] == 4,
"the score weighs each category kept (%d points, %s)" % [a["score"], a["tier"]])
var perfect := Assessment.of(FarmState.create(cfg), cfg)
r.check(perfect["score"] == 100 and perfect["tier"] == "Blue-ribbon harvest" and perfect["text"] != "", "nothing lost: 100, the top tier")
s.lose_all_crops()
s.lose_all_animals()
r.check(Assessment.of(s, cfg)["tier"] == "Hanging by a thread", "little left: the bottom tier")
var no_animals := FarmState.create(cfg)
no_animals.animals_total = 0
GameTestRunner.lose_crops(no_animals, 15)
var b := Assessment.of(no_animals, cfg)
r.check(not (b["parts"] as Dictionary).has("animals") and b["score"] == roundi(100.0 * (0.5 * 0.5 + 0.2) / 0.7),
"categories not in play are left out and the weights renormalized")
r.check(Assessment.enemies_line({"killed_crow": 3, "killed_thief": 1, "killed_breaker": 0}) == "3 crows and 1 thief"
and Assessment.materials_line({"spent_wood": 4, "spent_straw": 2}, "spent_") == "4 wood, 2 straw"
and Assessment.materials_line({}, "gathered_") == "nothing", "the totals read as words")
func _write_text(text: String) -> void:
var f := FileAccess.open(SAVE, FileAccess.WRITE)
f.store_string(text)
f.close()

View file

@ -0,0 +1 @@
uid://b630ievxokts1

View file

@ -0,0 +1,304 @@
extends RefCounted
## The scarecrow's kit on the real farm, with FarmSim stepped by hand at 60 Hz: health and
## invulnerability (several hits on one tick cost one), thief melee (touching, on a cooldown,
## not through cover, not while fleeing), fear (only thieves in range flee, carriers drop their
## crop, thieves mid-steal lose their progress, the cooldown, thieves come back afterwards),
## patching up (heals after the full channel while rooted; release, a hit, or fear cancel it;
## not at full health), sprint (only with the Sprint upgrade: faster while held and moving, 3 s at
## most, then a 10 s recharge; letting go or stopping ends it early; the HUD line), defeat (Game
## Over ahead of a stripped farm, the fall, the end panel and its Retry), the morning revive, and
## the new input actions.
const S := LootSystem.Status
const T := ThiefBehavior.State
const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0)
const SPOT := Vector2(8.0, -10.0) # open ground between the pen, the shed, and the field
func run(r: GameTestRunner) -> void:
_input_actions(r)
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 = Vector3(SPOT.x, 0.0, SPOT.y)
r.check(sim.scarecrow != null and sim.scarecrow.hp() == sim.config.scarecrow_max_hp and sim.scarecrow.fear_left == 0.0,
"the scarecrow starts at full health with fear ready")
_damage(r, sim)
_melee(r, sim)
_fear(r, sim)
_patch(r, sim, player)
await _sprint(r, sim, player, farm.get_node("Hud/ScarecrowHud") as ScarecrowHud)
_defeat(r, sim, player, farm.get_node("Hud/EndPanel") as EndPanel)
farm.queue_free()
await r.process_frame
func _input_actions(r: GameTestRunner) -> void:
for action in ["fear", "patch", "interact", "build_mode", "rotate_left", "rotate_right", "cancel", "pause", "sprint"]:
var keyboard := false
var pad := false
if InputMap.has_action(action):
for e in InputMap.action_get_events(action):
keyboard = keyboard or e is InputEventKey or e is InputEventMouseButton
pad = pad or e is InputEventJoypadButton
r.check(keyboard and pad, "input action '%s' has a keyboard/mouse and a gamepad binding" % action)
func _damage(r: GameTestRunner, sim: FarmSim) -> void:
var kit := sim.scarecrow
var s := sim.campaign.state
var hits: Array[int] = [] # lambdas capture ints by value, so count in an array
kit.damaged.connect(func(hp: int) -> void: hits.append(hp))
r.check(kit.try_damage(1) and s.scarecrow_hp == 9 and is_equal_approx(kit.invulnerable_left, sim.config.invulnerability_time),
"an accepted hit costs 1 HP and starts the invulnerability")
r.check(not kit.try_damage(1) and s.scarecrow_hp == 9 and kit.rejected_hits == 1, "hits during invulnerability are rejected")
_step(sim, roundi(sim.config.invulnerability_time * 60.0) + 1)
var accepted := 0
for i in 3:
if kit.try_damage(1):
accepted += 1
r.check(accepted == 1 and s.scarecrow_hp == 8 and hits == [9, 8], "three hits on one tick cost one hit")
_heal(sim)
func _melee(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var kit := sim.scarecrow
var s := sim.campaign.state
var h := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x + 0.6, SPOT.y, Vector2.LEFT)
_step(sim, 1)
r.check(s.scarecrow_hp == s.scarecrow_max_hp - 1 and es.attacks_attempted == 1, "a thief touching the scarecrow hits it")
var d := es.resolve_handle(h)
r.check(es.attack_cd[d] > 1.0, "the thief's attack cooldown started")
_place(es, h, Vector2(SPOT.x + 0.6, SPOT.y))
_step(sim, 30)
r.check(s.scarecrow_hp == s.scarecrow_max_hp - 1 and es.attacks_attempted == 1, "no second attack while the cooldown runs")
# Fleeing thieves don't fight.
_heal(sim)
_place(es, h, Vector2(SPOT.x + 0.6, SPOT.y))
d = es.resolve_handle(h)
es.attack_cd[d] = 0.0
es.state[d] = T.FLEE
es.timer[d] = 5.0
es.grid.rebuild(es.pos_x, es.pos_z, es.active_count)
es.evaluate_attacks(SPOT, FarmSim.SCARECROW_RADIUS, kit)
r.check(s.scarecrow_hp == s.scarecrow_max_hp, "a fleeing thief doesn't attack")
# Cover: a thief on the far side of the south fence, within (an enlarged) reach.
es.state[d] = T.SEEK
_place(es, h, Vector2(20.25, 15.75))
es.grid.rebuild(es.pos_x, es.pos_z, es.active_count)
var blocked := es.attacks_blocked_by_cover
es.evaluate_attacks(Vector2(20.25, 14.6), 0.8, kit)
r.check(es.attacks_blocked_by_cover == blocked + 1 and s.scarecrow_hp == s.scarecrow_max_hp, "a thief can't hit through the fence")
_kill_all(sim)
func _fear(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var loot := sim.loot
var kit := sim.scarecrow
var near := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x + 3.0, SPOT.y, Vector2.LEFT)
var far := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x + 9.0, SPOT.y, Vector2.LEFT)
var carrier := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x, SPOT.y + 4.0, Vector2.UP)
var stealer := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x - 3.0, SPOT.y - 3.5, Vector2.UP)
var cu := _home_unit(loot, -1)
loot.holder[cu] = carrier
loot.pick_up(cu, carrier)
es.carry[es.resolve_handle(carrier)] = cu
es.state[es.resolve_handle(carrier)] = T.CARRY
var su := _home_unit(loot, cu)
loot.holder[su] = stealer
loot.set_progress(su, stealer, 0.6)
es.target[es.resolve_handle(stealer)] = su
es.state[es.resolve_handle(stealer)] = T.STEAL
var used: Array[int] = []
kit.fear_used.connect(func(_p: Vector3, n: int) -> void: used.append(n))
Input.action_press("fear")
_step(sim, 1)
Input.action_release("fear")
r.check(used == [3], "the fear action scares the 3 thieves within %.0f m (got %s)" % [sim.config.fear_radius, used])
for h in [near, carrier, stealer]:
r.check(es.state[es.resolve_handle(h)] == T.FLEE, "a thief in range flees")
r.check(es.state[es.resolve_handle(far)] != T.FLEE, "the thief 9 m away is unaffected")
r.check(loot.status[cu] == S.DROPPED and es.carry[es.resolve_handle(carrier)] == -1, "the scared carrier drops its crop")
r.check(loot.holder[su] == -1 and loot.progress[su] == 0.0, "the scared thief loses its claim and progress")
var d0 := Vector2(es.pos_x[es.resolve_handle(near)], es.pos_z[es.resolve_handle(near)]).distance_to(SPOT)
_step(sim, 30)
var d1 := Vector2(es.pos_x[es.resolve_handle(near)], es.pos_z[es.resolve_handle(near)]).distance_to(SPOT)
r.check(d1 > d0 + 1.0, "fleeing thieves run away from the scarecrow (%.1f -> %.1f m)" % [d0, d1])
r.check(kit.use_fear() == -1 and kit.fear_left > 10.0, "fear can't be used again during its cooldown")
_step(sim, roundi(sim.config.fear_duration * 60.0))
r.check(es.state[es.resolve_handle(near)] == T.SEEK and es.state[es.resolve_handle(carrier)] == T.SEEK,
"after %.0f s the thieves get back to stealing" % sim.config.fear_duration)
_kill_all(sim)
var readied: Array[int] = []
kit.fear_ready.connect(func() -> void: readied.append(1))
_step(sim, roundi(sim.config.fear_cooldown * 60.0))
r.check(kit.fear_left == 0.0 and readied.size() == 1 and kit.use_fear() == 0, "fear is ready again after its cooldown")
kit.fear_left = 0.0
_step(sim, 1)
_return_crops(sim)
func _patch(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var kit := sim.scarecrow
var s := sim.campaign.state
s.resources.shed["straw"] = 40 # patching costs straw (Step 5)
kit.step_patch(DT, true)
r.check(not kit.patching, "no patching at full health")
s.scarecrow_hp = 5
Input.action_press("patch")
_step(sim, 30)
r.check(kit.patching and player.rooted and not kit.can_shoot(), "patching roots the scarecrow and stops it shooting")
_step(sim, roundi(sim.config.patch_time * 60.0) - 30 + 2) # +2: float sums land a tick late
r.check(s.scarecrow_hp == 5 + sim.config.patch_heal,
"a full %.0f s patch restores %d HP (now %d)" % [sim.config.patch_time, sim.config.patch_heal, s.scarecrow_hp])
r.check(kit.patching, "still holding (and not at full health): the next patch starts")
Input.action_release("patch")
_step(sim, 1)
r.check(not kit.patching and not player.rooted, "letting go frees the scarecrow")
s.scarecrow_hp = 5
Input.action_press("patch")
_step(sim, 60)
Input.action_release("patch")
_step(sim, 60)
r.check(s.scarecrow_hp == 5 and not kit.patching, "releasing early cancels the patch")
Input.action_press("patch")
_step(sim, 60)
kit.invulnerable_left = 0.0
kit.try_damage(1)
r.check(not kit.patching and s.scarecrow_hp == 4, "a hit cancels the patch")
_step(sim, 60)
r.check(s.scarecrow_hp == 4 and kit.patching, "holding on starts the patch over from the beginning")
kit.use_fear()
r.check(not kit.patching, "using fear cancels the patch")
Input.action_release("patch")
_step(sim, 1)
kit.fear_left = 0.0
_heal(sim)
func _sprint(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter, hud: ScarecrowHud) -> void:
var cfg := sim.config
var s := sim.campaign.state
s.upgrades.erase("sprint")
hud._process(0.0)
r.check(not player.can_sprint() and not hud._sprint_label.visible, "no sprint (and no sprint line on the HUD) before the upgrade")
# On the real body, over physics frames: the open ground south-west of the pen.
player.global_position = Vector3(0.0, 0.0, 6.0)
player.velocity = Vector3.ZERO
Input.action_press("move_right")
Input.action_press("sprint")
await _frames(r, 30)
var speed := Vector2(player.velocity.x, player.velocity.z).length()
r.check(not player.sprinting and speed <= player.run_speed + 0.05, "without it, holding sprint just runs (%.1f m/s)" % speed)
s.upgrades["sprint"] = 1
await _frames(r, 30)
speed = Vector2(player.velocity.x, player.velocity.z).length()
r.check(player.sprinting and absf(speed - player.run_speed * cfg.sprint_speed_mult) < 0.1,
"with the Sprint upgrade, holding sprint while moving sprints: %.1f m/s (runs at %.1f)" % [speed, player.run_speed])
r.check(player.animation_player.current_animation == player.run_animation and player.animation_player.speed_scale > 1.5,
"the run clip plays faster (x%.2f)" % player.animation_player.speed_scale)
r.check(player.move_strength() > 1.5, "the partner's machine is told it's sprinting (strength %.2f)" % player.move_strength())
hud._process(0.0)
r.check(hud._sprint_label.visible and hud._sprint_label.text.begins_with("Sprinting"), "the HUD shows the sprint running: '%s'" % hud._sprint_label.text)
Input.action_release("move_right")
await _frames(r, 2)
r.check(not player.sprinting and player.sprint_recharge > cfg.sprint_cooldown - 0.1, "stopping ends it, and the recharge starts")
hud._process(0.0)
r.check(hud._sprint_label.text == "Sprint %.0f s" % ceilf(player.sprint_recharge), "the HUD counts the recharge down: '%s'" % hud._sprint_label.text)
Input.action_release("sprint")
await _frames(r, 30)
player.velocity = Vector3.ZERO
player.global_position = Vector3(SPOT.x, 0.0, SPOT.y)
# The timing, tick by tick.
player.reset_sprint()
var ticks := 0
player.step_sprint(DT, true, true)
while player.sprinting and ticks < 1200:
player.step_sprint(DT, true, true)
ticks += 1
r.check(absf(ticks * DT - cfg.sprint_time) < DT * 2.0, "held, a sprint lasts %.1f s" % (ticks * DT))
ticks = 0
while not player.sprinting and ticks < 1200:
player.step_sprint(DT, true, true)
ticks += 1
r.check(absf(ticks * DT - cfg.sprint_cooldown) < DT * 2.0, "then %.1f s to recharge, and still held it starts again" % (ticks * DT))
player.step_sprint(1.0, true, true)
player.step_sprint(DT, false, true)
r.check(not player.sprinting and is_equal_approx(player.sprint_recharge, cfg.sprint_cooldown), "letting go early ends it, and the full recharge starts")
player.step_sprint(DT, true, false)
r.check(not player.sprinting, "and it doesn't start standing still")
sim.scarecrow.reset_for_morning()
hud._process(0.0)
r.check(player.sprint_recharge == 0.0 and hud._sprint_label.text == "Sprint hold Shift / L3", "a new morning has it ready: '%s'" % hud._sprint_label.text)
s.upgrades.erase("sprint")
func _frames(r: GameTestRunner, n: int) -> void:
for i in n:
await r.physics_frame
func _defeat(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter, panel: EndPanel) -> void:
var kit := sim.scarecrow
var c := sim.campaign
var s := c.state
s.scarecrow_hp = 1
s.strip() # the farm is stripped on the same tick the scarecrow falls
r.check(kit.try_damage(1) and not kit.alive and not player.alive, "the last HP lost: the scarecrow falls")
r.check(player.animation_player.current_animation == player.death_animation, "the death clip plays")
sim.step(DT)
r.check(c.state.phase == CampaignController.Phase.GAME_OVER and c.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW,
"Game Over, reported as the scarecrow's fall ahead of the stripped farm")
r.check(not kit.try_damage(1) and kit.use_fear() == -1 and not kit.can_shoot(), "a fallen scarecrow takes no hits and can't act")
r.check(not panel.visible, "the end panel waits a moment so the fall can play")
panel._process(EndPanel.DELAY + 0.1)
r.check(panel.visible and panel._retry.visible and panel._retry.has_focus(), "the end panel shows with Retry focused")
panel._retry.pressed.emit()
sim.step(DT)
r.check(c.state.phase == CampaignController.Phase.MORNING and not panel.visible, "Retry goes back to the morning")
r.check(kit.alive and player.alive and kit.fear_left == 0.0 and c.state.scarecrow_hp == c.state.scarecrow_max_hp and c.state.crops == c.state.crops_total,
"the scarecrow is back on its feet and the farm as it was that morning")
func _heal(sim: FarmSim) -> void:
sim.campaign.state.scarecrow_hp = sim.campaign.state.scarecrow_max_hp
sim.scarecrow.invulnerable_left = 0.0
func _kill_all(sim: FarmSim) -> void:
for d in sim.enemies.active_count:
sim.enemies.apply_hit(d, 99)
_step(sim, 1)
_heal(sim)
func _return_crops(sim: FarmSim) -> void:
sim.loot.return_dropped()
func _place(es: EnemySystem, handle: int, p: Vector2) -> void:
var d := es.resolve_handle(handle)
es.pos_x[d] = p.x
es.pos_z[d] = p.y
es.prev_x[d] = p.x
es.prev_z[d] = p.y
func _home_unit(loot: LootSystem, other: int) -> int:
for id in range(1, loot.unit_count + 1):
if id != other and loot.status[id] == S.HOME and loot.holder[id] == -1:
return id
return -1
func _step(sim: FarmSim, n: int) -> void:
for i in n:
sim.step(DT)

View file

@ -0,0 +1 @@
uid://nl0xkav8xpmi

View file

@ -0,0 +1,436 @@
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

View file

@ -0,0 +1 @@
uid://3doiag5vf4yk

460
game/tests/test_targets.gd Normal file
View file

@ -0,0 +1,460 @@
extends RefCounted
## All three farm targets on the real farm, with FarmSim stepped by hand at 60 Hz: the animals in
## the pen (wandering, kept in by the pen's gate), an animal thief breaking in, catching and
## carrying one off, a dropped animal running for the farm's edge, leading animals back (at most
## three, through a gate), a pen breach letting animals wander out at night (and not by day), supply
## thieves taking bundles from the shed's piles (never more than there is), dropping, recovering,
## and losing them, the piles growing and shrinking with the stock, thieves falling back to another
## target, the asset HUD, the end of the dawn grace, retry, and a farm stripped of all three.
const P := CampaignController.Phase
const S := LootSystem.Status
const C := LootSystem.Category
const T := ThiefBehavior.State
const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0)
var _events: Array = [] # [kind, id]
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 # every thief here is sent in by hand
var player := farm.get_node("Player") as PlayerCharacter
player.global_position = AWAY
sim.loot.loot_event.connect(func(kind: StringName, id: int, _p: Vector3) -> void: _events.append([kind, id]))
sim.campaign.begin_day()
_layout(r, sim)
_pen_by_day(r, sim)
_animal_theft(r, sim, player)
_leading(r, sim, player)
_breach(r, sim, player)
_supplies(r, sim, player)
_bundle_limits(r, sim)
_piles(r, sim)
_fallback(r, sim)
_hud(r, farm, sim)
_stripped(r, sim)
farm.queue_free()
await r.process_frame
func _layout(r: GameTestRunner, sim: FarmSim) -> void:
var loot := sim.loot
var cfg := sim.config
r.check(sim.animals.count == cfg.start_animals and loot.animal_count == cfg.start_animals and sim.campaign.state.animals == cfg.start_animals,
"%d animals in the pen, matching GameConfig.start_animals" % sim.animals.count)
r.check(loot.item_count == loot.unit_count + loot.animal_count + LootSystem.SACKS and loot.category[loot.unit_count] == C.CROP
and loot.category[loot.animal_item(1)] == C.ANIMAL and loot.category[loot.first_sack()] == C.SUPPLY,
"one id space: crops, then animals, then sacks")
var kinds := {}
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN)
var inside := true
for id in range(1, sim.animals.count + 1):
kinds[sim.animals.kind(id)] = true
inside = inside and pen.rect().has_point(sim.animals.position(id))
r.check(inside and kinds.keys().size() == 3, "chickens, pigs, and sheep (%s), all inside the pen" % [kinds.keys()])
r.check(not sim.animals.pen_open and sim.campaign.state.structure(1).get("type", "") == "gate", "the pen's gate shuts the pen")
var gap := _edge_cell(sim, "south-west")
r.check(sim.animal_field[gap] < FarmNavigation.UNREACHABLE, "thieves have a route into the pen (through its gate)")
for m in ResourceStore.MATERIALS:
var spot := sim.shed_stock.spot(m)
var c := sim.nav.cell_of(spot.x, spot.y)
r.check(sim.nav.is_walkable(c) and sim.supply_fields[m][_edge_cell(sim, "north")] < FarmNavigation.UNREACHABLE
and sim.escape_field[c] < FarmNavigation.UNREACHABLE, "the %s pile has a spot thieves can reach and leave" % m)
## By day the animals wander but stay in the pen: the gate keeps them in.
func _pen_by_day(r: GameTestRunner, sim: FarmSim) -> void:
var start := sim.animals.pos.duplicate()
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect()
var outside := 0
for i in 1800:
sim.step(DT)
for id in range(1, sim.animals.count + 1):
if not pen.has_point(sim.animals.position(id)):
outside += 1
var moved := 0
for id in range(1, sim.animals.count + 1):
if sim.animals.position(id).distance_to(start[id]) > 1.0:
moved += 1
r.check(moved >= sim.animals.count / 2.0 and outside == 0, "30 s by day: %d of %d animals wandered, none left the pen" % [moved, sim.animals.count])
## An animal thief breaks the pen's gate, catches an animal, and carries it; killed, it drops the
## animal, which runs for the edge of the farm; touched, the animal follows the scarecrow.
func _animal_theft(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
var loot := sim.loot
var s := sim.campaign.state
var gate := 1
var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["south-west"])
_step(sim, 1)
var item := es.target[es.resolve_handle(h)]
r.check(item > 0 and loot.category[item] == C.ANIMAL, "an animal thief claims an animal")
loot.update_visuals()
r.check(loot.threat[item] == LootSystem.Threat.TARGETED, "the animal shows as targeted")
var at_gate := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.BREAK, 40.0)
r.check(at_gate < 40.0 and es.barrier[es.resolve_handle(h)] == gate, "the thief comes to the pen's gate and breaks it (%.1f s)" % at_gate)
var caught := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 50.0)
var d := es.resolve_handle(h)
r.check(caught < 50.0 and s.structure(gate).is_empty() and loot.status[item] == S.CARRIED and es.carry[d] == item,
"it gets in through the broken gate and catches the animal (%.1f s more)" % caught)
r.check(int(s.night_events.get("animals_stolen", 0)) == 1, "the theft counts toward the night's record")
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect().grow(1.5)
var out := _until(sim, func() -> bool: return not pen.has_point(Vector2(es.pos_x[es.resolve_handle(h)], es.pos_z[es.resolve_handle(h)])), 20.0)
d = es.resolve_handle(h)
var index := loot.animal_index(item)
r.check(out < 20.0 and sim.animals.position(index).distance_to(Vector2(es.pos_x[d], es.pos_z[d])) < 0.1,
"the animal rides with its thief out of the pen (%.1f s)" % out)
var at := Vector2(es.pos_x[d], es.pos_z[d])
es.apply_hit(d, 99)
_step(sim, 1)
r.check(loot.status[item] == S.DROPPED and sim.animals.position(index).distance_to(at) < 0.2, "killing the carrier drops the animal where it fell")
var near_edge := _edge_distance(sim, sim.animals.position(index))
_step(sim, 300)
var later := _edge_distance(sim, sim.animals.position(index))
r.check(loot.status[item] == S.DROPPED and later < near_edge - 2.0, "the loose animal makes for the edge of the farm (%.1f m -> %.1f m from it)" % [near_edge, later])
var p := sim.animals.position(index)
player.global_position = Vector3(p.x + 0.8, 0.0, p.y)
_step(sim, 1)
r.check(loot.status[item] == S.FOLLOWING and _has(&"following", item), "walking up to it: it follows the scarecrow")
loot.status[item] = S.DROPPED # loose again for the next part
sim.animals.place(index, p)
player.global_position = AWAY
_step(sim, 1)
## Lead loose animals back: at most three follow at once; they pass through a gate behind the
## scarecrow, and inside the pen they are home.
func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var loot := sim.loot
var st := sim.structures
var s := sim.campaign.state
s.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
r.check(st.validate("gate", 4.0, -6.0, 2, Vector2(6.0, -6.0)) == "" and st.place("gate", 4.0, -6.0, 2) > 0, "a new gate goes in the pen opening")
_settle(sim)
r.check(not sim.animals.pen_open, "the pen is shut again")
var loose: Array[int] = []
for id in range(1, sim.animals.count + 1):
if loot.status[loot.animal_item(id)] == S.DROPPED:
loose.append(id)
for id in range(1, sim.animals.count + 1):
if loose.size() < 4 and loot.status[loot.animal_item(id)] == S.HOME:
loose.append(id)
for k in loose.size():
_make_loose(sim, loose[k], Vector2(9.0 + k * 3.0, -2.0))
var recovered_before := int(s.night_events.get("animals_recovered", 0))
for k in loose.size():
player.global_position = Vector3(9.0 + k * 3.0 + 0.6, 0.0, -2.0)
_step(sim, 1)
r.check(loot.followers() == sim.config.max_following_animals and loot.status[loot.animal_item(loose[3])] == S.DROPPED
and _has(&"follow_full", loot.animal_item(loose[3])), "three animals follow; the fourth waits (and the scarecrow is told why)")
# Walk the line in through the gate: east of the pen, then west through the opening.
var path: Array[Vector2] = [Vector2(15.0, -2.0), Vector2(7.5, -2.0), Vector2(7.5, -6.0), Vector2(0.0, -6.0), Vector2(-3.0, -6.0)]
var from := Vector2(player.global_position.x, player.global_position.z)
for target in path:
while from.distance_to(target) > 0.05:
from = from.move_toward(target, 4.5 * DT)
player.global_position = Vector3(from.x, 0.0, from.y)
sim.step(DT)
_step(sim, 120)
var home := 0
for k in 3:
if loot.status[loot.animal_item(loose[k])] == S.HOME:
home += 1
r.check(home == 3 and not st.validate("gate", 4.0, -6.0, 2, Vector2(6.0, -6.0)).is_empty(), "the three follow the scarecrow through the gate into the pen")
r.check(int(s.night_events.get("animals_recovered", 0)) == recovered_before + 3, "each counts as led back")
_make_loose(sim, loose[3], Vector2(-1.0, -2.5)) # the fourth wanders back in by itself
_step(sim, 1)
r.check(loot.status[loot.animal_item(loose[3])] == S.HOME, "a loose animal inside the pen is home again")
player.global_position = AWAY
_step(sim, 1)
## With the gate down at night, animals wander out of the pen one at a time; a loose one that
## reaches the farm's edge is lost. By day an open pen keeps its animals. The end of the dawn grace brings
## loose ones back; retry restores the morning.
func _breach(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign
var loot := sim.loot
var st := sim.structures
var gate := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)]
st.damage(gate, 999)
_settle(sim)
r.check(sim.animals.pen_open, "a broken gate opens the pen")
_events.clear()
_step(sim, roundi(sim.config.animal_wander_interval * 60.0))
r.check(not _has(&"strayed", -1) and loot.count(S.HOME, C.ANIMAL) == loot.animal_count - loot.count(S.LOST, C.ANIMAL),
"by day the animals stay in an open pen")
_to_night(sim)
var morning_lost := c.state.lost_animals.duplicate()
var first := _until(sim, func() -> bool: return _has(&"strayed", -1), sim.config.animal_wander_interval + 1.0)
r.check(first <= sim.config.animal_wander_interval * 0.3 + 0.1, "at night an animal soon wanders out of the open pen (%.1f s)" % first)
var strays := _until(sim, func() -> bool: return _count(&"strayed") >= 2, sim.config.animal_wander_interval + 1.0)
r.check(strays <= sim.config.animal_wander_interval + 0.1, "then another every %.0f s" % sim.config.animal_wander_interval)
var lost := _until(sim, func() -> bool: return c.state.lost_animals.size() > morning_lost.size(), 90.0)
r.check(lost < 90.0, "a wandering animal that reaches the farm's edge is lost (%.1f s later)" % lost)
var loose_at_dawn := loot.count(S.DROPPED, C.ANIMAL)
r.check(loose_at_dawn > 0, "some are still loose on the farm (%d)" % loose_at_dawn)
var still_lost := c.state.lost_animals.duplicate()
c.advance_phase()
c.advance_phase()
r.check(c.state.phase == P.MORNING and loot.count(S.DROPPED, C.ANIMAL) == 0 and c.state.lost_animals == still_lost
and loot.count(S.HOME, C.ANIMAL) == loot.animal_count - still_lost.size(), "the end of the dawn grace brings the loose ones back to the pen")
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect()
var inside := true
for id in range(1, sim.animals.count + 1):
if loot.status[loot.animal_item(id)] == S.HOME:
inside = inside and pen.has_point(sim.animals.position(id))
r.check(inside and sim.animals.pen_open, "every animal left is in the pen (still open: the gate is gone)")
r.check(sim.review_panel._body.text.contains("The pen is open"), "the morning review says the pen is open")
var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
r.check(e["animals_lost"] == still_lost.size() - morning_lost.size() and e["animals_strayed"] >= 2, "the night's record: %s" % [e])
# Retry: lose another one tonight, fall, and the morning comes back.
var morning := c.state.to_dict()
c.begin_day()
c.state.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
st.place("gate", 4.0, -6.0, 2)
_to_night(sim)
var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["west"])
_until(sim, func() -> bool: return sim.enemies.resolve_handle(h) == -1, 90.0)
r.check(c.state.lost_animals.size() >= still_lost.size() + 1, "an unopposed animal thief carries one off the farm")
c.state.scarecrow_hp = 0
_step(sim, 1)
c.retry_night()
_step(sim, 1)
r.check(c.state.to_dict() == morning and loot.count(S.LOST, C.ANIMAL) == still_lost.size() and sim.animals.pen_open,
"retry restores the morning (that animal is back, the new gate gone)")
player.global_position = AWAY
c.begin_day()
c.state.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
st.place("gate", 4.0, -6.0, 2)
_settle(sim)
## A supply thief takes a bundle of the material the shed holds most of; killed, it drops the
## sack, which the scarecrow takes back to the shed; unopposed, it carries it off.
func _supplies(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
var loot := sim.loot
var s := sim.campaign.state
var r0 := s.resources
r0.shed = {"wood": 3, "scrap": 9, "straw": 4}
var total := r0.shed_total()
var stolen0 := int(s.night_events.get("supplies_stolen", 0))
var h := sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
_step(sim, 1)
var sack := es.target[es.resolve_handle(h)]
r.check(sack >= loot.first_sack() and loot.sack_material[sack] == "scrap" and loot.home[sack] == sim.shed_stock.spot("scrap"),
"a supply thief heads for the pile the shed holds most of (scrap)")
var took := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 40.0)
r.check(took < 40.0 and int(r0.shed["scrap"]) == 9 - sim.config.supply_bundle and loot.sack_amount[sack] == sim.config.supply_bundle
and loot.status[sack] == S.CARRIED, "it fills a sack with %d scrap (%.1f s)" % [sim.config.supply_bundle, took])
r.check(s.supplies == total and s.supplies_in_transit == sim.config.supply_bundle
and int(s.night_events.get("supplies_stolen", 0)) == stolen0 + sim.config.supply_bundle, "a carried sack still counts as on the farm")
_step(sim, 60)
var d := es.resolve_handle(h)
var at := Vector2(es.pos_x[d], es.pos_z[d])
es.apply_hit(d, 99)
_step(sim, 1)
loot.update_visuals()
r.check(loot.status[sack] == S.DROPPED and loot.ground[sack].distance_to(at) < 0.2 and loot._tokens[sack].visible, "killing the carrier drops the sack")
player.global_position = Vector3(at.x + 0.8, 0.0, at.y)
_step(sim, 1)
r.check(loot.status[sack] == S.HOME and int(r0.shed["scrap"]) == 9 and s.supplies_in_transit == 0 and loot.sack_amount[sack] == 0,
"walking up to the sack puts the scrap back in the shed")
player.global_position = AWAY
# Unopposed, it gets away with the sack.
var lost0 := int(s.night_events.get("supplies_lost", 0))
h = sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
_until(sim, func() -> bool: return es.resolve_handle(h) == -1, 70.0)
r.check(int(r0.shed["scrap"]) == 9 - sim.config.supply_bundle and s.supplies == total - sim.config.supply_bundle
and int(s.night_events.get("supplies_lost", 0)) == lost0 + sim.config.supply_bundle, "an unopposed thief carries %d scrap off the farm" % sim.config.supply_bundle)
r.check(loot.count(S.HOME, C.SUPPLY) == LootSystem.SACKS and s.supplies_in_transit == 0, "its sack is free for the next theft")
## A bundle never holds more than the shed has; an emptied shed leaves the thief nothing to take.
func _bundle_limits(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var loot := sim.loot
var s := sim.campaign.state
s.resources.shed = {"wood": 2, "scrap": 1, "straw": 0}
var h := sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
_until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 40.0)
var d := es.resolve_handle(h)
var sack := es.carry[d]
r.check(sack > 0 and loot.sack_amount[sack] == 2 and int(s.resources.shed["wood"]) == 0, "with 2 wood in the shed, the bundle is 2 wood")
es.apply_hit(d, 99)
_step(sim, 1)
loot.return_dropped()
r.check(int(s.resources.shed["wood"]) == 2, "(the dropped sack goes back)")
h = sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
_until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.STEAL, 40.0)
d = es.resolve_handle(h)
sack = es.target[d]
for m in ResourceStore.MATERIALS:
s.resources.shed[m] = 0 # spent while the thief fills its sack
_until(sim, func() -> bool: return es.resolve_handle(h) < 0 or es.state[es.resolve_handle(h)] != T.STEAL, 10.0)
d = es.resolve_handle(h)
r.check(d >= 0 and es.carry[d] == -1 and loot.status[sack] == S.HOME and s.supplies_in_transit == 0 and s.resources.shed_total() == 0,
"the shed emptied before it finished: it takes nothing")
r.check(not s.shed_raided, "spending the last supplies isn't a raid")
_step(sim, 1)
d = es.resolve_handle(h)
r.check(d >= 0 and (es.target[d] < 0 or loot.category[es.target[d]] != C.SUPPLY), "and goes for something else")
es.apply_hit(d, 99)
_step(sim, 1)
r.check(not loot.available(C.SUPPLY), "an empty shed has nothing to claim")
s.resources.shed = {"wood": 3, "scrap": 0, "straw": 0}
h = sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
_until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 40.0)
r.check(s.resources.shed_total() == 0 and s.shed_raided, "a thief taking the last of the stock raids the shed")
es.apply_hit(es.resolve_handle(h), 99)
_step(sim, 1)
loot.return_dropped()
_step(sim, 1)
r.check(int(s.resources.shed["wood"]) == 3 and not s.shed_raided, "stock back in the shed: no longer raided")
## The shed's piles show one prop per few units, and hidden props don't collide.
func _piles(r: GameTestRunner, sim: FarmSim) -> void:
var ss := sim.shed_stock
var s := sim.campaign.state
var wood: Array = ss.slots["wood"]
var per: int = ShedStock.PILES["wood"]["per"]
for amount in [0, per * 2 + 1, 999]:
s.resources.shed["wood"] = amount
ss._process(0.0)
var want := mini(ceili(amount / float(per)), wood.size())
var shown := 0
var colliding := 0
for n: Node3D in wood:
if n.visible:
shown += 1
for b: CollisionObject3D in n.find_children("*", "CollisionObject3D", true, false):
if b.collision_layer != 0:
colliding += 1
r.check(shown == want and colliding == want, "%d wood: %d of %d log piles shown (and colliding)" % [amount, shown, wood.size()])
s.resources.shed["wood"] = 10
ss._process(0.0)
## A thief whose target is gone goes for another; one with no set target takes anything.
func _fallback(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var loot := sim.loot
var s := sim.campaign.state
var keep := s.lost_animals.duplicate()
s.lose_all_animals()
loot.sync_from_state()
var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["south-west"])
_step(sim, 1)
var item := es.target[es.resolve_handle(h)]
r.check(item > 0 and loot.category[item] != C.ANIMAL, "with no animals left, an animal thief goes for %s" % LootSystem.CATEGORY_KEYS[loot.category[item]])
es.apply_hit_handle(h, 99)
var any := sim.spawn_thief(LootSystem.ANY, GameTestRunner.EDGE["east"])
_step(sim, 1)
r.check(es.target[es.resolve_handle(any)] > 0, "a thief with no set target claims something")
es.apply_hit_handle(any, 99)
_step(sim, 1)
s.lost_animals = keep
loot.sync_from_state()
sim.animals.sync_from_state()
func _hud(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
var hud := farm.get_node("Hud/AssetHud") as AssetHud
var s := sim.campaign.state
hud._process(0.0)
var before := hud.describe()
s.lose_animal(s.animals_total if not s.is_animal_lost(s.animals_total) else 1)
hud._process(0.05)
r.check(hud.describe() == "Crops %d/%d · Animals %d/%d · Supplies %d" % [s.crops, s.crops_total, s.animals, s.animals_total, s.supplies]
and hud.describe() != before and hud._flash[1] > 0.0 and hud._flash_color[1] == AssetHud.LOSS, "the asset HUD updates and flashes red on a loss: '%s'" % hud.describe())
## The farm is stripped when the last supplies are carried off with every crop and animal gone.
func _stripped(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
var s := c.state
s.lose_all_crops()
s.lose_all_animals()
sim.loot.sync_from_state()
s.resources.shed = {"wood": 0, "scrap": 4, "straw": 0}
_step(sim, 1)
r.check(c.state.phase != P.GAME_OVER, "crops and animals gone, supplies left: the vacation goes on")
var h := sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
var stolen := _until(sim, func() -> bool: return sim.enemies.resolve_handle(h) >= 0 and sim.enemies.carry[sim.enemies.resolve_handle(h)] > 0, 40.0)
r.check(stolen < 40.0 and c.state.phase != P.GAME_OVER, "the last supplies in a thief's sack still count")
_until(sim, func() -> bool: return c.is_over(), 70.0)
r.check(c.state.phase == P.GAME_OVER and c.outcome == CampaignController.Outcome.GAME_OVER_STRIPPED,
"carried off with nothing else left: the farm is stripped (D2)")
## Puts an animal loose at p (as if dropped there).
func _make_loose(sim: FarmSim, id: int, p: Vector2) -> void:
var item := sim.loot.animal_item(id)
sim.loot.status[item] = S.DROPPED
sim.loot.holder[item] = -1
sim.loot.ground[item] = p
sim.animals.place(id, p)
func _to_night(sim: FarmSim) -> void:
var c := sim.campaign
while c.state.phase != P.NIGHT:
if c.state.phase == P.MORNING:
c.begin_day()
else:
c.advance_phase()
func _has(kind: StringName, id: int) -> bool:
for e in _events:
if e[0] == kind and (id < 0 or e[1] == id):
return true
return false
func _count(kind: StringName) -> int:
var n := 0
for e in _events:
if e[0] == kind:
n += 1
return n
func _edge_distance(sim: FarmSim, p: Vector2) -> float:
return sim.nav.meters(sim.escape_field[sim.nav.cell_of(p.x, p.y)])
func _edge_cell(sim: FarmSim, side: String) -> int:
var p: Vector2 = GameTestRunner.EDGE[side]
return sim.nav.nearest_free(sim.nav.cell_of(p.x, p.y))
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)
## Steps until cond() holds; returns the seconds it took (or max_seconds).
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

View file

@ -0,0 +1 @@
uid://bf0qhvcwr8pxg

334
game/tests/test_theft.gd Normal file
View file

@ -0,0 +1,334 @@
extends RefCounted
## Crop theft and recovery on the real farm, with FarmSim stepped by hand at 60 Hz. Crops are the
## crows' (Step 9): claiming a crop (targeted), flying in and landing on it, the steal timer,
## carrying it off over the fence, the crop lost when the crow escapes, one hit killing a crow and
## dropping its crop exactly once, recovery by touch, stale handles after slot reuse, shots
## hitting thieves and cruising crows and stopping at walls, the sunrise retreat, the end-of-dawn
## rules (carriers take their loot, dropped crops return), retrying a night, and FarmState staying
## consistent with the loot state.
const P := CampaignController.Phase
const S := LootSystem.Status
const DT := 1.0 / 60.0
## Where the scarecrow waits when it must not touch anything.
const AWAY := Vector3(-11.0, 0.0, 13.0)
var _events: Dictionary = {}
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 # no automatic arrivals: every thief here is sent in by hand
var player := farm.get_node("Player") as PlayerCharacter
player.global_position = AWAY
sim.loot.loot_event.connect(func(kind: StringName, _id: int, _p: Vector3) -> void:
_events[kind] = int(_events.get(kind, 0)) + 1)
r.info("farm sim loaded in %d ms (nav %d cells)" % [sim.load_msec, sim.nav.cell_count()])
r.check(sim.loot.unit_count == 30 and sim.loot.count(S.HOME, LootSystem.Category.CROP) == 30 and sim.campaign.state.crops == 30,
"30 crop units start at home")
var edge_cells := [Vector2(-16.0, -6.0), Vector2(20.0, 18.0), Vector2(50.0, 0.0), Vector2(-16.0, 10.0)].filter(func(p: Vector2) -> bool:
return sim.escape_field[sim.nav.cell_of(p.x, p.y)] == 0)
r.check(edge_cells.size() == 4 and sim.escape_field[sim.nav.cell_of(10.0, -8.0)] > 0, "the farm's edge, all around, is where carriers escape")
_steal_and_drop(r, sim, player)
_escape(r, sim)
_stale_handles(r, sim)
_shots(r, sim)
_combat_input(r, sim, player)
_sunrise_and_dawn_end(r, sim)
_retry(r, sim)
_night_arrivals(r, sim)
farm.queue_free()
await r.process_frame
func _steal_and_drop(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
var loot := sim.loot
var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
_step(sim, 1)
var d := es.resolve_handle(h)
var unit := es.target[d]
loot.update_visuals()
r.check(unit >= 1 and loot.category[unit] == LootSystem.Category.CROP and loot.is_claimed_by(unit, h)
and loot.threat[unit] == LootSystem.Threat.TARGETED, "a new crow claims a crop, which shows as targeted")
var steal_at := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == ThiefBehavior.State.STEAL, 30.0)
r.check(steal_at < 30.0, "the crow flies in from the east to its crop (%.1f s)" % steal_at)
var steal := sim.config.crop_steal_time * es.t_steal[EnemySystem.TYPE_CROW]
_step(sim, 60)
d = es.resolve_handle(h)
r.check(loot.progress[unit] > 0.4 and loot.progress[unit] < 0.6, "after 1 s of %.1f s the ring shows %.0f %%" % [steal, loot.progress[unit] * 100.0])
r.check(absf(es.alt[d] - sim.config.land_altitude) < 0.3, "it has come down onto the crop (altitude %.1f m)" % es.alt[d])
var took := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == ThiefBehavior.State.CARRY, 10.0)
r.check(absf(took + 1.0 - steal) < 0.1, "a full steal takes %.1f s (took %.2f s)" % [steal, took + 1.0])
d = es.resolve_handle(h)
r.check(loot.status[unit] == S.CARRIED and es.carry[d] == unit and not loot._units[unit].visible,
"the crop is carried: gone from its plot, riding on the crow")
r.check(int(sim.campaign.state.night_events.get("crops_stolen", 0)) == 1, "the steal counts toward the night's record")
_step(sim, 30)
d = es.resolve_handle(h)
var at := Vector2(es.pos_x[d], es.pos_z[d])
es.apply_hit(es.resolve_handle(h))
_step(sim, 1)
r.check(es.resolve_handle(h) == -1 and loot.status[unit] == S.DROPPED and loot.ground[unit].distance_to(at) < 0.2,
"one hit kills the crow, and it drops the crop where it fell")
r.check(int(_events.get(&"dropped", 0)) == 1 and not es.apply_hit_handle(h), "the crop drops exactly once; the dead crow takes no more hits")
_step(sim, 30)
r.check(loot.status[unit] == S.DROPPED, "a dropped crop stays put while the scarecrow is away")
var g := loot.ground[unit]
player.global_position = Vector3(g.x + 1.0, 0.0, g.y)
_step(sim, 1)
r.check(loot.status[unit] == S.HOME and loot._units[unit].visible and int(sim.campaign.state.night_events.get("crops_recovered", 0)) == 1,
"walking up to the dropped crop recovers it to its plot")
player.global_position = AWAY
_consistent(r, sim)
func _escape(r: GameTestRunner, sim: FarmSim) -> void:
var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["south"])
var took := _until(sim, func() -> bool: return sim.enemies.resolve_handle(h) == -1, 60.0)
r.check(took < 60.0 and sim.enemies.escapes == 1, "an unopposed crow steals a crop and flies off over the fence (%.1f s)" % took)
r.check(sim.loot.count(S.LOST, LootSystem.Category.CROP) == 1 and sim.campaign.state.crops == 29 and sim.campaign.state.lost_crops.size() == 1,
"the escaped crop is lost for good")
var lost := sim.campaign.state.lost_crops[0]
r.check(not sim.loot._units[lost].visible and int(_events.get(&"lost", 0)) == 1, "a lost crop stays gone from its plot")
_consistent(r, sim)
func _stale_handles(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var h1 := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
_step(sim, 1)
var unit := es.target[es.resolve_handle(h1)]
es.apply_hit(es.resolve_handle(h1), 99)
_step(sim, 1)
r.check(not sim.loot.is_claimed_by(unit, h1) and sim.loot.holder[unit] == -1, "a killed crow's claim is released")
var h2 := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
r.check(es.resolve_handle(h1) == -1 and es.resolve_handle(h2) >= 0 and (h1 & EnemySystem.ID_MASK) == (h2 & EnemySystem.ID_MASK),
"the reused slot has a new generation: the old handle is stale")
var some := 1
while not sim.loot.is_home(some):
some += 1
sim.loot.holder[some] = h1 # a claim forged with the stale handle
r.check(not sim.loot.pick_up(some, h2) and sim.loot.status[some] == S.HOME, "another handle can't take a unit it doesn't hold")
sim.loot.holder[some] = -1
sim.loot.drop(some, h1, 0.0, 0.0)
sim.loot.escape(some, h1)
r.check(sim.loot.status[some] == S.HOME and not sim.campaign.state.is_crop_lost(some), "a stale handle can't drop or lose a crop")
es.apply_hit_handle(h2, 99)
_step(sim, 1)
_consistent(r, sim)
func _shots(r: GameTestRunner, sim: FarmSim) -> void:
var es := sim.enemies
var h := es.spawn(EnemySystem.TYPE_THIEF, 10.0, -8.0, Vector2.DOWN)
_step(sim, 1)
var d := es.resolve_handle(h)
var y := sim.config.combat_height
var hp := es.health[d]
es.pos_x[d] = 10.0
es.pos_z[d] = -8.0
es.prev_x[d] = 10.0
es.prev_z[d] = -8.0
es.grid.rebuild(es.pos_x, es.pos_z, es.active_count)
sim.projectiles.fire(Vector3(10.0, y, -2.0), Vector3(10.0, y, -3.0), Vector3(0, 0, -1))
for i in 20:
sim.projectiles.step(DT)
r.check(es.health[d] == hp - 1 and sim.projectiles.hits_enemy == 1, "a shot hits the thief in its path")
var walls := sim.projectiles.hits_world
sim.projectiles.fire(Vector3(1.0, y, -16.0), Vector3(1.0, y, -17.0), Vector3(0, 0, -1))
for i in 30:
sim.projectiles.step(DT)
r.check(sim.projectiles.hits_world == walls + 1 and sim.projectiles.active_count == 0, "a shot stops at the barn")
es.apply_hit(d, 99)
_step(sim, 1)
# A crow cruising high is still hit by a shot at combat height (its altitude is only visual).
var keep := es.behavior
es.behavior = null
var crow := es.spawn(EnemySystem.TYPE_CROW, 10.0, -8.0, Vector2.DOWN)
_step(sim, 1)
var c := es.resolve_handle(crow)
r.check(es.alt[c] > y + 1.0, "a crow cruises at %.1f m" % es.alt[c])
sim.projectiles.fire(Vector3(10.0, y, -2.0), Vector3(10.0, y, -3.0), Vector3(0, 0, -1))
for i in 20:
sim.projectiles.step(DT)
_step(sim, 1)
r.check(es.resolve_handle(crow) == -1, "a shot brings it down")
es.behavior = keep
## The real input path: right-stick aim at a thief and the fire action held (after the fresh
## press the gun requires) shoot it.
func _combat_input(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies
player.global_position = Vector3(8.0, 0.0, -9.0)
var keep := es.behavior
es.behavior = null # it stands still
var h := es.spawn(EnemySystem.TYPE_THIEF, 14.0, -9.0, Vector2.LEFT)
_step(sim, 1)
var d := es.resolve_handle(h)
var hp := es.health[d]
var b := sim.camera.global_transform.basis
var fwd := Vector2(-b.z.x, -b.z.z).normalized()
var right := Vector2(b.x.x, b.x.z).normalized()
var want := Vector2(es.pos_x[d] - 8.0, es.pos_z[d] + 9.0).normalized()
var stick := Vector2(want.dot(right), want.dot(fwd))
Input.action_press("aim_right" if stick.x > 0.0 else "aim_left", absf(stick.x))
Input.action_press("aim_up" if stick.y > 0.0 else "aim_down", absf(stick.y))
sim.campaign.state.upgrades["corn_shooter"] = 1 # the gun, from the workbench
r.check(sim.combat.equip(ScarecrowCombat.Weapon.CORN_SHOOTER), "(the corn shooter in hand)")
sim.combat.reset() # as every new morning does
Input.action_press("fire")
_step(sim, 10)
r.check(sim.combat.shots_fired == 0, "a fire button held through a reset doesn't shoot until pressed again")
Input.action_release("fire")
_step(sim, 1)
Input.action_press("fire")
_step(sim, 30)
for a in ["aim_right", "aim_left", "aim_up", "aim_down", "fire"]:
Input.action_release(a)
d = es.resolve_handle(h)
r.check(sim.combat.device == ScarecrowCombat.Device.GAMEPAD and sim.combat.aim.dot(want) > 0.99,
"the right stick aims camera-relative")
r.check(sim.combat.shots_fired >= 2 and (d < 0 or es.health[d] < hp), "holding fire shoots the thief (%d shots)" % sim.combat.shots_fired)
sim.campaign.state.upgrades.erase("corn_shooter")
sim.combat.tick(DT, true)
r.check(sim.combat.weapon == ScarecrowCombat.Weapon.PITCHFORK, "(back to the pitchfork)")
es.behavior = keep
if d >= 0:
es.apply_hit(d, 99)
_step(sim, 1)
player.global_position = AWAY
func _sunrise_and_dawn_end(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
var es := sim.enemies
var loot := sim.loot
c.begin_day()
c.advance_phase()
c.advance_phase()
r.check(c.state.phase == P.NIGHT, "night falls")
var lost_before := c.state.crops
# A crow taking a crop retreats at sunrise and leaves without it.
var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
_until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == ThiefBehavior.State.STEAL, 30.0)
var unit := es.target[es.resolve_handle(h)]
# A carrier, and a crop lying dropped, both forced into place.
var carrier := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["west"])
_place(es, carrier, Vector2(20.0, -5.0))
var cu := _home_unit(loot, unit)
loot.holder[cu] = carrier
loot.pick_up(cu, carrier)
es.carry[es.resolve_handle(carrier)] = cu
es.state[es.resolve_handle(carrier)] = ThiefBehavior.State.CARRY
var victim := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["north"])
_place(es, victim, Vector2(8.0, -10.0))
var du := _home_unit(loot, cu)
loot.holder[du] = victim
loot.pick_up(du, victim)
es.carry[es.resolve_handle(victim)] = du
es.apply_hit(es.resolve_handle(victim), 99)
_step(sim, 1)
r.check(loot.status[du] == S.DROPPED, "a crop lies dropped")
c.advance_phase()
r.check(c.state.phase == P.DAWN and es.state[es.resolve_handle(h)] == ThiefBehavior.State.RETREAT and loot.holder[unit] == -1,
"sunrise: the stealing crow gives up its crop and retreats")
r.check(es.state[es.resolve_handle(carrier)] == ThiefBehavior.State.CARRY, "sunrise: the carrier keeps running")
_step(sim, 30)
var stolen := int(c.state.night_events.get("crops_stolen", 0))
c.advance_phase() # the dawn grace ends now
r.check(c.state.phase == P.MORNING and es.active_count == 0, "the end of the dawn grace clears the farm of enemies")
r.check(loot.status[cu] == S.LOST and c.state.is_crop_lost(cu), "a carrier still on the farm takes its crop along")
r.check(loot.status[du] == S.HOME and loot.status[unit] == S.HOME, "the dropped crop returns, the abandoned one is untouched")
var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
r.check(e["crops_lost"] == lost_before - c.state.crops and e["crops_lost"] == 1 and e["crops_stolen"] == stolen,
"the night's record: %s" % [e])
_consistent(r, sim)
func _retry(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
var es := sim.enemies
var morning_lost := c.state.lost_crops.duplicate()
c.begin_day()
c.advance_phase()
c.advance_phase()
var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["south"])
_until(sim, func() -> bool: return es.resolve_handle(h) == -1, 60.0)
r.check(c.state.lost_crops.size() == morning_lost.size() + 1, "a crop is lost on the second night")
c.state.scarecrow_hp = 0
_step(sim, 1)
r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls")
c.retry_night()
_step(sim, 1)
r.check(c.state.lost_crops == morning_lost and sim.loot.count(S.LOST, LootSystem.Category.CROP) == morning_lost.size() and es.active_count == 0,
"retry restores the morning: the crop lost that night is back in its plot")
_consistent(r, sim)
## Trickle mode (tests and soaks): crows trickle in one at a time, and only at night.
func _night_arrivals(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
sim.config.night_thieves = 1
sim.waves.enabled = true
c.begin_day()
_step(sim, 600)
r.check(sim.enemies.active_count == 0, "no crows arrive by day")
c.advance_phase()
c.advance_phase()
_step(sim, roundi(WaveDirector.FIRST_TRICKLE_DELAY * 60.0) + 2)
r.check(sim.enemies.alive_count() == 1 and sim.enemies.type[0] == EnemySystem.TYPE_CROW,
"the first crow arrives %.0f s into the night" % WaveDirector.FIRST_TRICKLE_DELAY)
var most := 0
for i in 1200:
sim.step(DT)
most = maxi(most, sim.enemies.alive_count())
r.check(most == 1, "never more than one at a time (night_thieves = 1)")
sim.config.night_thieves = 0
sim.waves.enabled = false
## FarmState's lost crops and the loot system's LOST units are the same set.
func _consistent(r: GameTestRunner, sim: FarmSim) -> void:
var lost := PackedInt32Array()
for id in range(1, sim.loot.unit_count + 1):
if sim.loot.status[id] == S.LOST:
lost.append(id)
r.check(lost == sim.campaign.state.lost_crops and sim.campaign.state.crops == sim.loot.unit_count - lost.size(),
"FarmState agrees with the loot state (%d lost)" % lost.size())
func _place(es: EnemySystem, handle: int, p: Vector2) -> void:
var d := es.resolve_handle(handle)
es.pos_x[d] = p.x
es.pos_z[d] = p.y
es.prev_x[d] = p.x
es.prev_z[d] = p.y
func _home_unit(loot: LootSystem, other: int) -> int:
for id in range(1, loot.unit_count + 1):
if id != other and loot.status[id] == S.HOME and loot.holder[id] == -1:
return id
return -1
func _step(sim: FarmSim, n: int) -> void:
for i in n:
sim.step(DT)
## Steps until cond() holds; returns the seconds it took (or max_seconds).
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

View file

@ -0,0 +1 @@
uid://djllti2122mck

261
game/tests/test_weapons.gd Normal file
View file

@ -0,0 +1,261 @@
extends RefCounted
## The scarecrow's three weapons on the real farm (FarmSim stepped by hand at 60 Hz): only the
## pitchfork to start; its stab (in reach and in the arc of the aim only, the nearest few, its
## damage, once per interval, again and again while fire is held, not through a wall); the corn
## shooter and pumpkin bombs bought at the workbench (rapid fire and heavy seeds need the corn
## shooter first; a weapon bought goes into the hand); switching (Tab / 1-3, owned ones only, not
## in build mode; one no longer owned falls back to the pitchfork); a bomb's throw (at the aim,
## its range clamped), flight, and burst (everything in its radius, crows too, nothing beyond,
## not the scarecrow), its recharge and the morning refill; the models on the scarecrow; and the
## HUD's weapon panel.
const DT := 1.0 / 60.0
const AT := Vector2(0.0, 6.0) # open ground south-west of the pen
const W := ScarecrowCombat.Weapon
const THIEF := EnemySystem.TYPE_THIEF
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 = Vector3(AT.x, 0.0, AT.y)
var keep := sim.enemies.behavior
sim.enemies.behavior = null # enemies stand still
_start(r, sim, player)
_pitchfork(r, sim)
await _wall(r, sim, farm)
_unlocks(r, farm, sim)
_switching(r, sim)
_bombs(r, sim)
_hud(r, farm, sim)
sim.enemies.behavior = keep
farm.queue_free()
await r.process_frame
func _start(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.combat
r.check(c.weapon == W.PITCHFORK and c.owns(W.PITCHFORK) and not c.owns(W.CORN_SHOOTER) and not c.owns(W.PUMPKIN_BOMB),
"a new vacation: the pitchfork in hand, and nothing else")
var pivots := c.models._pivots
r.check(pivots.size() == 3 and pivots[0].visible and not pivots[1].visible and not pivots[2].visible, "only the pitchfork shows on the scarecrow")
var near := true
for p in pivots:
near = near and p.global_position.distance_to(player.global_position) < 3.0
r.check(near, "the models sit on the scarecrow (their exports were 1.8 km off the origin)")
func _pitchfork(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.combat
var cfg := sim.config
var es := sim.enemies
var front := es.spawn(THIEF, AT.x + 1.2, AT.y, Vector2.LEFT)
var front2 := es.spawn(THIEF, AT.x + 1.7, AT.y + 0.7, Vector2.LEFT)
var behind := es.spawn(THIEF, AT.x - 1.2, AT.y, Vector2.RIGHT)
var far := es.spawn(THIEF, AT.x + cfg.pitchfork_reach + 1.5, AT.y, Vector2.LEFT)
_step(sim, 1)
var full := es.t_hp[THIEF]
r.check(c.attack_toward(AT + Vector2(5.0, 0.0)) and c.stabs == 1, "a stab to the east")
r.check(_hp(es, front) == full - cfg.pitchfork_damage and _hp(es, front2) == full - cfg.pitchfork_damage,
"both thieves in front, in reach, take %d" % cfg.pitchfork_damage)
r.check(_hp(es, behind) == full and _hp(es, far) == full, "the one behind and the one out of reach don't")
r.check(not c.attack_toward(AT + Vector2(5.0, 0.0)), "one stab per %.1f s: not again at once" % cfg.pitchfork_interval)
_step(sim, c.stab_ticks())
r.check(c.attack_toward(AT + Vector2(5.0, 0.0)), "and again after it")
_step(sim, 1)
r.check(es.resolve_handle(front) < 0 and es.resolve_handle(front2) < 0, "two stabs stop a thief")
_clear(sim)
# The nearest few only, crows too.
var crowd: Array[int] = []
for k in 5:
crowd.append(es.spawn(THIEF, AT.x + 0.9 + k * 0.28, AT.y + (0.5 if k % 2 == 0 else -0.5), Vector2.LEFT))
_step(sim, 1)
_step(sim, c.stab_ticks())
c.attack_toward(AT + Vector2(5.0, 0.0))
var hit := crowd.filter(func(h: int) -> bool: return _hp(es, h) < full).size()
r.check(hit == cfg.pitchfork_targets, "a stab hits the nearest %d of a crowd (%d)" % [cfg.pitchfork_targets, hit])
_clear(sim)
var crow := es.spawn(EnemySystem.TYPE_CROW, AT.x + 1.5, AT.y, Vector2.LEFT)
_step(sim, c.stab_ticks())
c.attack_toward(AT + Vector2(5.0, 0.0))
_step(sim, 1)
r.check(es.resolve_handle(crow) < 0, "a crow in reach is stabbed out of the air")
# Held fire stabs again and again.
c.reset()
_step(sim, 1)
var before := c.stabs
Input.action_press("fire")
_step(sim, c.stab_ticks() * 2)
Input.action_release("fire")
_step(sim, 1)
r.check(c.stabs - before == 2, "holding fire stabs every %.1f s (%d in %.1f s)" % [cfg.pitchfork_interval, c.stabs - before, cfg.pitchfork_interval * 2.0])
func _wall(r: GameTestRunner, sim: FarmSim, farm: Node3D) -> void:
var c := sim.combat
var es := sim.enemies
var h := es.spawn(THIEF, AT.x + 1.5, AT.y, Vector2.LEFT)
var wall := StaticBody3D.new()
var shape := CollisionShape3D.new()
var box := BoxShape3D.new()
box.size = Vector3(0.2, 3.0, 2.0)
shape.shape = box
wall.add_child(shape)
farm.add_child(wall)
wall.global_position = Vector3(AT.x + 0.75, 1.5, AT.y)
await r.physics_frame # it joins the physics space on the next physics frame
_step(sim, c.stab_ticks())
c.attack_toward(AT + Vector2(5.0, 0.0))
r.check(_hp(es, h) == es.t_hp[THIEF], "no stab through a wall")
wall.queue_free()
await r.physics_frame
_clear(sim)
func _unlocks(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
var c := sim.campaign
var s := c.state
var combat := sim.combat
var st := sim.structures
c.begin_day()
s.resources.shed = {"wood": 99, "scrap": 99, "straw": 99}
r.check(not combat.equip(W.CORN_SHOOTER) and combat.weapon == W.PITCHFORK, "the corn shooter can't be taken up before it's bought")
r.check(Upgrades.blocker(c, "rapid_fire") == "Needs the corn shooter first" and Upgrades.buy(c, "heavy_seeds", st).contains("needs the corn shooter")
and not Upgrades.owned(s, "heavy_seeds"), "rapid fire and heavy seeds need the corn shooter first")
r.check(Upgrades.buy(c, "corn_shooter", st).contains("done:") and combat.owns(W.CORN_SHOOTER) and Upgrades.blocker(c, "rapid_fire") == "",
"the corn shooter is bought at the workbench; then rapid fire can be")
var panel := farm.get_node("Hud/UpgradePanel") as UpgradePanel
panel._buy("pumpkin_bomb")
r.check(combat.owns(W.PUMPKIN_BOMB) and combat.weapon == W.PUMPKIN_BOMB, "a weapon bought from the menu goes into the hand")
r.check(combat.models._pivots[2].visible and not combat.models._pivots[0].visible, "and shows on the scarecrow")
func _switching(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.combat
var s := sim.campaign.state
c.equip(W.PITCHFORK)
var seen: Array[int] = []
for k in 3:
_tap(sim, "weapon_next")
seen.append(c.weapon)
r.check(seen == [W.CORN_SHOOTER, W.PUMPKIN_BOMB, W.PITCHFORK], "Tab / d-pad down cycles through them: %s" % [seen])
_tap(sim, "weapon_3")
var third := c.weapon
_tap(sim, "weapon_1")
r.check(third == W.PUMPKIN_BOMB and c.weapon == W.PITCHFORK, "1-3 pick one")
var east := AT + Vector2(5.0, 0.0)
_step(sim, c.stab_ticks())
c.attack_toward(east)
c.equip(W.CORN_SHOOTER)
var shot := c.attack_toward(east)
c.equip(W.PITCHFORK)
r.check(shot and not c.attack_toward(east), "each weapon keeps its own wait: swapping doesn't skip the pitchfork's")
sim.build.set_active(true)
_tap(sim, "weapon_2")
_tap(sim, "weapon_next")
var building := c.weapon
sim.build.set_active(false)
r.check(building == W.PITCHFORK, "not in build mode (those keys pick structures there)")
s.upgrades.erase("pumpkin_bomb")
c.equip(W.CORN_SHOOTER)
_tap(sim, "weapon_next")
var skipped := c.weapon
_tap(sim, "weapon_3")
r.check(skipped == W.PITCHFORK and c.weapon == W.PITCHFORK, "only weapons owned: no pumpkin bombs without the upgrade")
c.equip(W.CORN_SHOOTER)
s.upgrades.erase("corn_shooter")
_step(sim, 1)
r.check(c.weapon == W.PITCHFORK, "one no longer owned (a retry from before it was bought) goes back to the pitchfork")
s.upgrades["corn_shooter"] = 1
s.upgrades["pumpkin_bomb"] = 1
func _bombs(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.combat
var cfg := sim.config
var es := sim.enemies
var kit := sim.scarecrow
c.equip(W.PUMPKIN_BOMB)
c.ready_for_morning()
var target := AT + Vector2(6.0, 0.0)
var on := es.spawn(THIEF, target.x, target.y, Vector2.LEFT)
var near := es.spawn(THIEF, target.x + cfg.bomb_radius - 0.5, target.y, Vector2.LEFT)
var crow := es.spawn(EnemySystem.TYPE_CROW, target.x, target.y + 1.5, Vector2.LEFT)
var out := es.spawn(THIEF, target.x + cfg.bomb_radius + 2.0, target.y, Vector2.LEFT)
_step(sim, 1)
var hp := kit.hp()
r.check(c.attack_toward(target) and sim.bombs.flying() == 1 and is_equal_approx(c.bomb_left, cfg.bomb_cooldown),
"a pumpkin bomb is thrown at the aim point")
r.check(not c.attack_toward(target), "only one every %.0f s" % cfg.bomb_cooldown)
r.check(c.models._pivots[2].scale.x < 0.05, "it's gone from the hand")
var ticks := 0
while sim.bombs.flying() > 0 and ticks < 200:
_step(sim, 1)
ticks += 1
_step(sim, 1)
r.check(ticks * DT >= PumpkinBombs.MIN_FLIGHT - DT and ticks * DT <= PumpkinBombs.MAX_FLIGHT + DT, "it flies %.2f s" % (ticks * DT))
r.check(es.resolve_handle(on) < 0 and es.resolve_handle(near) < 0 and es.resolve_handle(crow) < 0,
"its burst stops everything within %.0f m (%d damage), crows too" % [cfg.bomb_radius, cfg.bomb_damage])
r.check(_hp(es, out) == es.t_hp[THIEF] and kit.hp() == hp and sim.bombs.bursts == 1, "nothing beyond, and not the scarecrow")
_clear(sim)
c.device = ScarecrowCombat.Device.MOUSE
var me := Vector2(sim.player.global_position.x, sim.player.global_position.z)
c.ground_point = Vector3(me.x + 30.0, 0.0, me.y)
var long := Vector2(c.throw_target().x, c.throw_target().z).distance_to(me)
c.ground_point = Vector3(me.x + 0.5, 0.0, me.y)
var short := Vector2(c.throw_target().x, c.throw_target().z).distance_to(me)
r.check(is_equal_approx(long, cfg.bomb_range) and is_equal_approx(short, cfg.bomb_min_range),
"it lands %.0f .. %.0f m away (%.1f, %.1f)" % [cfg.bomb_min_range, cfg.bomb_range, short, long])
_step(sim, roundi(cfg.bomb_cooldown * 60.0) + 2)
r.check(c.bomb_left == 0.0 and c.models._pivots[2].scale.x > 0.99, "after %.0f s another one is in hand" % cfg.bomb_cooldown)
c.attack_toward(target)
c.ready_for_morning()
r.check(c.bomb_left == 0.0, "a new morning puts one in hand")
sim.bombs.clear()
func _hud(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
var hud := farm.get_node("Hud/ScarecrowHud") as ScarecrowHud
var c := sim.combat
var s := sim.campaign.state
s.upgrades.erase("corn_shooter")
c.equip(W.PUMPKIN_BOMB)
c.attack_toward(AT + Vector2(6.0, 0.0))
hud._process(0.0)
var rows := hud._weapon_rows.map(func(l: Label) -> String: return l.text)
r.check(rows[0] == "1 Pitchfork" and rows[1] == "2 Corn shooter (workbench)" and rows[2] == "3 Pumpkin bombs 4 s",
"the HUD lists the weapons: %s" % [rows])
r.check(hud._weapon_title.visible and hud._weapon_hint.text.contains("Tab"), "with how to switch")
s.upgrades.erase("pumpkin_bomb")
_step(sim, 1)
sim.bombs.clear()
_step(sim, 1)
func _tap(sim: FarmSim, action: String) -> void:
Input.action_press(action)
_step(sim, 1)
Input.action_release(action)
_step(sim, 1)
func _hp(es: EnemySystem, handle: int) -> int:
var d := es.resolve_handle(handle)
return es.health[d] if d >= 0 else 0
func _clear(sim: FarmSim) -> void:
for d in sim.enemies.active_count:
sim.enemies.apply_hit(d, 99)
_step(sim, 1)
func _step(sim: FarmSim, n: int) -> void:
for i in n:
sim.step(DT)

View file

@ -0,0 +1 @@
uid://bw3sedxvmb27f