harvest/game/tests/test_theft.gd
Forrest 62edb8e04c Task #13: two new crop fields with staged growth (Night 2 / Night 4)
Adds a Lettuce/Cabbage field (ids 31-40, x -11..-1 z 2..12) and a Corn field
(ids 41-50, x 2..12 z 2..12), each 2 plots of 5 units, placeholder plants
reusing plant_007/plant_008. CropUnit gains crop (cosmetic) and sprout_night
(0/2/4) fields. LootSystem gains a DORMANT status: a unit whose field hasn't
sprouted (FarmState.nights_survived < sprout_night) is hidden and never
claimable/recoverable, and is excluded from crops_total so it can't affect
scoring or the "farm stripped" check. sync_from_state() derives DORMANT vs.
HOME from nights_survived every morning (and after a retry/load), and
self-heals crops_total to the sprouted count; FarmSim.grow_crops_total() also
grows it right at night_ending so the morning snapshot (retry, the save file)
already has it right. FarmZones.crop_units() now gathers CropUnits from every
CROP_FIELD zone (there are three now), not just the first found; the same fix
applies to FarmSim's crop-area rect and the fence breakers' guarded areas.

Reworks test_farm_layout's zone-count and crop checks for the extra fields,
and test_theft's start-of-run and FarmState-consistency checks, which assumed
every crop unit was always in play; adds test_theft cases for both fields
sprouting on schedule, dormant units being unclaimable, and a sprouted unit
being stealable and scored, including a save/JSON round trip. Nudges
test_coop's co-op build spot into the 3 m walkway between the two new fields,
since its old spot now sits on the corn field's rows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 15:52:38 -04:00

419 lines
19 KiB
GDScript

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 == 50 and sim.loot.count(S.HOME, LootSystem.Category.CROP) == 30 and sim.campaign.state.crops == 30
and sim.loot.count(S.DORMANT, LootSystem.Category.CROP) == 20,
"30 crop units start at home, 20 more dormant in the two later fields (#13)")
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)
_staged_fields(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
## #13: the two later fields (lettuce/cabbage, ids 31-40; corn, 41-50) start dormant -- hidden,
## not claimable, not scored -- and sprout on schedule: field A the morning after night 2, field B
## the morning after night 4. Once sprouted a unit is a crop like any other: visible, stealable by
## a crow, and counted in crops_total and the score.
func _staged_fields(r: GameTestRunner, sim: FarmSim) -> void:
var c := sim.campaign
var loot := sim.loot
var es := sim.enemies
while c.state.nights_survived < 2:
_play_to_next_morning(sim)
r.check(c.state.phase == P.MORNING and c.state.nights_survived == 2, "played to the morning after night 2")
var a_ok := true
for id in range(31, 41):
a_ok = a_ok and loot.status[id] == S.HOME and loot._units[id].visible
r.check(a_ok, "field A (lettuce/cabbage, 31..40) sprouted after night 2: visible and home")
var b_dormant := true
for id in range(41, 51):
b_dormant = b_dormant and loot.status[id] == S.DORMANT and not loot._units[id].visible
r.check(b_dormant, "field B (corn, 41..50) is still dormant: hidden, not home")
r.check(c.state.crops_total == 30 + 10, "crops_total grew by field A's 10 units")
r.check(not loot.recover(41) and not loot.is_claimed_by(41, -1), "a dormant unit can't be recovered or claimed")
# A crow can claim (by hand, as other tests here do), steal, and carry off a field-A crop: it
# counts exactly like any other crop.
var before := c.state.crops
var h := es.spawn(EnemySystem.TYPE_CROW, -20.0, 0.0, Vector2.RIGHT)
var d := es.resolve_handle(h)
loot.holder[31] = h
r.check(loot.pick_up(31, h), "field A crop 31 can be claimed and picked up")
es.carry[d] = 31
loot.escape(31, h)
r.check(c.state.is_crop_lost(31) and loot.status[31] == S.LOST and c.state.crops == before - 1,
"a stolen field-A crop is lost and scored like any other")
es.apply_hit(d, 99)
_step(sim, 1)
_consistent(r, sim)
while c.state.nights_survived < 4:
_play_to_next_morning(sim)
r.check(c.state.phase == P.MORNING and c.state.nights_survived == 4, "played to the morning after night 4")
var b_ok := true
for id in range(41, 51):
b_ok = b_ok and loot.status[id] == S.HOME and loot._units[id].visible
r.check(b_ok, "field B (corn, 41..50) sprouted after night 4: visible and home")
r.check(c.state.crops_total == 30 + 10 + 10, "crops_total grew by field B's 10 units too")
var before2 := c.state.crops
var h2 := es.spawn(EnemySystem.TYPE_CROW, -20.0, 0.0, Vector2.RIGHT)
var d2 := es.resolve_handle(h2)
loot.holder[41] = h2
r.check(loot.pick_up(41, h2), "field B crop 41 can be claimed and picked up")
es.carry[d2] = 41
loot.escape(41, h2)
r.check(c.state.is_crop_lost(41) and loot.status[41] == S.LOST and c.state.crops == before2 - 1,
"a stolen field-B crop is lost and scored like any other")
es.apply_hit(d2, 99)
_step(sim, 1)
_consistent(r, sim)
# Save/load and retry round trips agree on crops_total and every unit's status.
var dict := c.state.to_dict()
var json := JSON.stringify(dict)
var restored := FarmState.from_dict(JSON.parse_string(json))
r.check(restored.crops_total == c.state.crops_total and restored.nights_survived == c.state.nights_survived,
"crops_total and nights_survived survive a save/JSON round trip")
loot.sync_from_state() # as a real load or retry would trigger
r.check(c.state.crops_total == 50, "sync_from_state() repairs crops_total to the same, fully-sprouted total")
## Advances from wherever the campaign is now to the next morning (one full day/night/dawn cycle),
## through the normal transition path (same as the debug keys / UI would).
func _play_to_next_morning(sim: FarmSim) -> void:
var c := sim.campaign
c.advance_phase()
while c.state.phase != P.MORNING and not c.is_over():
c.advance_phase()
## FarmState's lost crops and the loot system's LOST units are the same set, and crops is the
## sprouted units (#13: everything but DORMANT, i.e. the later fields before they sprout) minus
## what's lost -- not plain unit_count, now that not every unit is in play from the start.
func _consistent(r: GameTestRunner, sim: FarmSim) -> void:
var lost := PackedInt32Array()
var sprouted := 0
for id in range(1, sim.loot.unit_count + 1):
if sim.loot.status[id] == S.LOST:
lost.append(id)
if sim.loot.status[id] != S.DORMANT:
sprouted += 1
r.check(lost == sim.campaign.state.lost_crops and sim.campaign.state.crops == sprouted - 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