Merge task #21: animals roam the whole farm, never lost on their own

Loose animals roam the playable map day and night; dropped, leash-broken
and open-pen animals become LOOSE instead of running for the edge. Only
an Alien carrying one off the map loses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-06 13:15:24 -04:00
commit 9d26f29299
8 changed files with 379 additions and 226 deletions

View file

@ -91,7 +91,7 @@ the night, but only when `allow_early_night` is on. It is **off by default**.
Three kinds of asset can be stolen, and all three are in play from the start: Three kinds of asset can be stolen, and all three are in play from the start:
- **crops**: the crop field's 30 units; - **crops**: the crop field's 30 units;
- **animals**: the 8 in the pen; - **animals**: the 8 animals (they start loose, outside the pen: see **Animals and the pen**);
- **supplies**: the construction materials stored in the supply shed (the pouch can't be stolen). - **supplies**: the construction materials stored in the supply shed (the pouch can't be stolen).
A kind with nothing in it at the start is not in play. The asset HUD (top center) shows what's A kind with nothing in it at the start is not in play. The asset HUD (top center) shows what's
@ -104,7 +104,7 @@ left of each, and a count flashes red when it drops and green when it rises.
| Targeted | An enemy is heading for the asset | Marker over it; arrow at the screen edge if off screen | | Targeted | An enemy is heading for the asset | Marker over it; arrow at the screen edge if off screen |
| Being stolen | The enemy is taking it, which takes visible time (crops 2.5 s, animals 2 s, a sack of supplies 3 s). Damage resets the timer. | Progress ring | | Being stolen | The enemy is taking it, which takes visible time (crops 2.5 s, animals 2 s, a sack of supplies 3 s). Damage resets the timer. | Progress ring |
| Carried | The enemy is heading for the nearest escape point, slower than usual | The asset shown on the enemy, outlined in its category's color (crops gold, animals pink, supplies blue), with a badge | | Carried | The enemy is heading for the nearest escape point, slower than usual | The asset shown on the enemy, outlined in its category's color (crops gold, animals pink, supplies blue), with a badge |
| Dropped | The carrier was stopped | A crop or sack lies on the ground, glowing; an animal runs loose (below) | | Dropped | The carrier was stopped | A crop or sack lies on the ground, glowing; an animal is loose where it fell (below) |
| Recovered | The scarecrow got it back | It returns home (an animal follows the scarecrow home) | | Recovered | The scarecrow got it back | It returns home (an animal follows the scarecrow home) |
| Lost | The carrier escaped off the farm | Permanently gone | | Lost | The carrier escaped off the farm | Permanently gone |
@ -115,8 +115,9 @@ left of each, and a count flashes red when it drops and green when it rises.
the pen. the pen.
- Another thief can pick up a dropped item. - Another thief can pick up a dropped item.
- Anything still on the ground when the dawn grace ends returns home automatically - Anything still on the ground when the dawn grace ends returns home automatically
(`loot_returns_at_dawn`). (`loot_returns_at_dawn`). Loose animals stay loose.
- Animals can also escape through a breach in the pen. An animal that leaves the farm is lost. - Nothing leaves the farm on its own: an animal that gets out of a breached pen is only loose, and
an item is lost only when its carrier escapes off the farm.
Implemented for all three (Steps 3 and 8). The arrows at the screen edge are filled by state Implemented for all three (Steps 3 and 8). The arrows at the screen edge are filled by state
(orange targeted, red carried, yellow dropped) and ringed in the category's color. (orange targeted, red carried, yellow dropped) and ringed in the category's color.
@ -132,8 +133,8 @@ How enemies steal (the enemy types are in **The enemies**, below):
- **Crops.** A crow claims a random unit still in its plot and flies straight to it, over - **Crops.** A crow claims a random unit still in its plot and flies straight to it, over
anything in the way. It lands on it, takes it (2 s), and flies straight off the farm with it, out its anything in the way. It lands on it, takes it (2 s), and flies straight off the farm with it, out its
nearest side. Only one enemy claims an item at a time. nearest side. Only one enemy claims an item at a time.
- **Animals.** A thief claims a random animal in the pen. The pen's gate keeps it out, so it - **Animals.** A thief claims a random animal, penned or loose. A shut pen keeps it out, so it
breaks the gate (30 HP: about 18 s). Then it walks in and catches the animal, which freezes, in breaks its way in (a gate's 30 HP take about 18 s). It catches the animal, which freezes, in
2 s. It carries the animal off, held under it, at 70 % speed to the **nearest** point of the farm's edge. 2 s. It carries the animal off, held under it, at 70 % speed to the **nearest** point of the farm's edge.
- **Supplies.** A thief goes to the shed pile of the material the shed holds most of (logs, - **Supplies.** A thief goes to the shed pile of the material the shed holds most of (logs,
crates, or hay bales; each pile has a spot in front). crates, or hay bales; each pile has a spot in front).
@ -170,7 +171,7 @@ Implemented in Step 9. The type table is `GameConfig.enemy_types`.
- Each arrow is labeled ("3 crows — Crop Field", "Thief escaping with an animal!", "Breach! — - Each arrow is labeled ("3 crows — Crop Field", "Thief escaping with an animal!", "Breach! —
Animal Pen"), filled by kind, and ringed in the loot's category color. Animal Pen"), filled by kind, and ringed in the loot's category color.
- **Kinds, in priority order:** escapes; breaches (a barrier being smashed, or just broken); - **Kinds, in priority order:** escapes; breaches (a barrier being smashed, or just broken);
thefts; loose animals and dropped loot. thefts; dropped loot (#21: loose animals roam freely and get no arrow).
- Alerts of the same kind, type, and loot in the same zone are grouped. - Alerts of the same kind, type, and loot in the same zone are grouped.
- An escape escalates as its carrier nears the exit: the arrow grows, pulses faster, and turns - An escape escalates as its carrier nears the exit: the arrow grows, pulses faster, and turns
red. red.
@ -178,29 +179,41 @@ Implemented in Step 9. The type table is `GameConfig.enemy_types`.
## Animals and the pen ## Animals and the pen
Implemented in Step 8. Implemented in Step 8. Since #12 the animals start loose and the pen is player-built; since #21
they roam the whole farm and are never lost on their own.
- **In the pen.** The 8 animals (4 chickens, 2 pigs, 2 sheep) wander inside the pen and stop to - **Loose animals.** The 8 animals (4 chickens, 2 pigs, 2 sheep) start loose, each at its own spot
graze. The pen's gate on its east side is a normal gate structure, standing from the start: the outside the pen (`animal_loose_spots`).
scarecrow (and animals following it) walk through, but wandering animals and enemies can't. - They roam the whole farm, day and night. Each walk goes to a spot 4–8 m away that the animal
- **The pen is open** when there's a way out that crosses no structure: its gate is broken or taken can reach in a straight line, inside the farm (at least 2 m in from its edge) and outside the
down. pen; then it stops to graze.
- A toast says so when it happens, and so does the morning review.
- At night (night and dawn), one calm animal walks out of an open pen every 10 s.
- By day they stay in.
- Building a gate (or a fence) back in the opening shuts the pen.
- **Loose animals** (dropped by a thief, or wandered out) walk toward the farm's nearest edge at
1.1 m/s, stopping to graze now and then.
- Structures stop them, so a fence line can hold them. - Structures stop them, so a fence line can hold them.
- One that reaches the edge is lost. - They never leave the farm on their own, and never walk into the pen by themselves.
- One that gets back inside the pen is home. - Each morning, every loose animal is back at its own spot.
- Any thief can grab a loose animal it sees. - Any thief can claim a loose animal (penned or loose, it picks one at random).
- **The only way to lose an animal is a thief carrying it off the farm.**
- **Dropped animals.** When a thief carrying an animal is stopped (killed or scared), the animal
is loose where it fell and roams from there. If that's inside the pen, it's home again.
- **Leading animals home (D6).** - **Leading animals home (D6).**
- Walk up to a loose animal and it follows the scarecrow, walking its trail in line, gates - Walk up to a loose animal and it follows the scarecrow, walking its trail in line, gates
included. At most 3 follow at once; a toast says so when the line is full. included. At most 3 follow at once; a toast says so when the line is full.
- Inside the pen it's home and stays calm for 30 s (it won't wander out of an open pen). - Inside the pen it's home (penned) and stays calm for 30 s (it won't get out of an open pen).
- A follower whose scarecrow gets more than 20 m away is loose where it stands.
- Thieves can't take an animal that's following the scarecrow. - Thieves can't take an animal that's following the scarecrow.
- At the end of the dawn grace, loose and following animals are back in the pen. - **In the pen.** Penned animals wander inside the pen and stop to graze, and each morning they're
back in the pen. The pen's fences and gate are player-built: the scarecrow (and animals
following it) walk through the gate, but wandering animals and enemies can't.
- **The pen is open** when there's a way out that crosses no structure: nothing built yet, or a
gate or fence broken or taken down.
- A toast says so when it happens, and so does the morning review.
- At night (night and dawn), one calm penned animal gets out of an open pen every 10 s. It's
loose at once (no longer penned): it walks out through the opening at 1.1 m/s, then roams like
any loose animal. The night's record counts it as strayed.
- By day they stay in.
- Building a gate (or a fence) back in the opening shuts the pen. An animal still on its way out
when the pen shuts stays home.
- At the end of the dawn grace, animals still following the scarecrow are back in the pen. Loose
animals stay loose; the next morning puts them back at their spots.
## Supplies ## Supplies
@ -432,7 +445,7 @@ Implemented in Step 6. The numbers are in `GameConfig`.
Counted from each morning to the end of its dawn grace, and recorded when the dawn ends Counted from each morning to the end of its dawn grace, and recorded when the dawn ends
(`FarmState.night_log`): (`FarmState.night_log`):
- crops and animals lost, supply units carried off; - crops and animals lost, supply units carried off;
- what was taken, recovered, and wandered out, per category; - what was taken, recovered, and strayed (animals that got out of an open pen), per category;
- enemies killed per type, and those that got away with loot; - enemies killed per type, and those that got away with loot;
- the scarecrow's damage taken and patches; - the scarecrow's damage taken and patches;
- structures built, damage dealt to them, structures broken, and repairs; - structures built, damage dealt to them, structures broken, and repairs;
@ -441,9 +454,9 @@ Counted from each morning to the end of its dawn grace, and recorded when the da
material. material.
The morning screen opens with the last night's record. Its table shows taken, recovered, and The morning screen opens with the last night's record. Its table shows taken, recovered, and
lost per category; animals taken include those that wandered out of an open pen. Under the lost per category; animals taken include those that got out of an open pen (loose, not lost).
table come the enemies, the damage, and the materials. The final assessment adds up all the Under the table come the enemies, the damage, and the materials. The final assessment adds up
nights. all the nights.
Decided in Step 8: a farm whose supplies were *spent* rather than stolen is not stripped. The Decided in Step 8: a farm whose supplies were *spent* rather than stolen is not stripped. The
shed counts as raided when a thief takes the last of its stock, and storing anything clears that shed counts as raided when a thief takes the last of its stock, and storing anything clears that

View file

@ -1,25 +1,30 @@
class_name AnimalSystem class_name AnimalSystem
extends Node3D extends Node3D
## The pen's animals as moving entities. Their theft state lives in LootSystem; this moves and ## The farm's animals as moving entities. Their theft state lives in LootSystem; this moves and
## shows them: ## shows them:
## loose (LOOSE) #12, #21: where every animal starts, at its own GameConfig.animal_loose_spots
## spot outside the pen, and where a loose one is back every morning. It roams
## the whole farm, day and night: each walk goes to a spot ROAM_MIN..ROAM_MAX
## meters away that it can reach in a straight line, inside the playable map
## (ROAM_MARGIN in from its edge) and outside the pen, and then it stops to
## graze. Structures stop it. It never leaves the farm on its own and never
## walks into the pen by itself. A thief may claim and carry it off; a stopped
## carrier drops it loose where it fell (inside the pen, it's home again). The
## scarecrow walking up to it starts it following.
## in the pen (HOME) wander between random spots in the pen, pausing to graze; one a thief is ## in the pen (HOME) wander between random spots in the pen, pausing to graze; one a thief is
## catching stands still. At night (night and dawn), while the pen is open (a ## catching stands still. At night (night and dawn), while the pen is open (a
## way out that crosses no structure: its gate broken or taken down), one calm ## way out that crosses no structure: nothing built yet, or its gate broken or
## animal wanders out every animal_wander_interval and is loose (DROPPED). ## taken down), one calm animal gets out every animal_wander_interval: it's
## grazing (LOOSE) #12: where every animal starts, scattered at its own GameConfig. ## loose at once (and no longer penned), walks out of the pen along the escape
## animal_loose_spots spot outside the pen. Same calm wander as a penned ## field at stray_speed, and then roams like any loose animal. If the pen shuts
## animal, but anchored to that spot instead of the pen, and never walks the ## before it's out, it stays home.
## escape field on its own. A thief may still claim and carry it off (then
## it's DROPPED, below); the scarecrow walking up to it starts it following,
## same as a dropped one.
## loose (DROPPED) dropped by its thief, or wandered out of an open pen: walks toward the
## farm's nearest edge along the escape field at stray_speed, stopping to
## graze now and then, and can't pass structures. At the edge it is lost;
## inside the pen it is home again.
## following walks the scarecrow's trail (so it goes wherever the scarecrow went, gates ## following walks the scarecrow's trail (so it goes wherever the scarecrow went, gates
## included), in line behind it. Inside the pen it is home (returned) and calm ## included), in line behind it. Inside the pen it is home (returned) and calm
## for animal_calm_time. ## for animal_calm_time. A follower whose scarecrow got FOLLOW_LEASH away is
## loose where it stands.
## carried held under its thief, wriggling. ## carried held under its thief, wriggling.
## An animal is never left DROPPED (that's for crops and sacks), and the only way to lose one is a
## thief carrying it off the farm (LootSystem.escape).
## The farm pack's animals are static meshes, so walking is procedural: chickens hop, pigs and ## The farm pack's animals are static meshes, so walking is procedural: chickens hop, pigs and
## sheep waddle. Each scene animal (a farm-pack prefab under the pen zone) is reparented under a ## sheep waddle. Each scene animal (a farm-pack prefab under the pen zone) is reparented under a
## pivot at the middle of its body. ## pivot at the middle of its body.
@ -31,8 +36,15 @@ const FOLLOW_GAP := 1.0
const FOLLOW_FIRST := 1.5 const FOLLOW_FIRST := 1.5
## A follower whose scarecrow got this far away (a retry, a fall) is loose again. ## A follower whose scarecrow got this far away (a retry, a fall) is loose again.
const FOLLOW_LEASH := 20.0 const FOLLOW_LEASH := 20.0
## A grazing (LOOSE) animal's wander goals stay within this many meters of its loose spot. ## #21: a loose (LOOSE) animal's next wander goal is this many meters from where it stands...
const LOOSE_WANDER_RADIUS := 0.8 const ROAM_MIN := 4.0
const ROAM_MAX := 8.0
## ...and at least this far inside the playable map's edge.
const ROAM_MARGIN := 2.0
## Loose animals keep this far out of the pen's rectangle (goals), and never cut across it.
const PEN_KEEP_OUT := 1.0
## Seconds an animal walking out of an open pen keeps at it before it settles back in.
const LEAVE_TIME := 30.0
## The pen opened (its gate broken or taken down) or was shut again. ## The pen opened (its gate broken or taken down) or was shut again.
signal pen_changed(open: bool) signal pen_changed(open: bool)
@ -44,7 +56,10 @@ var loot: LootSystem
var enemies: EnemySystem var enemies: EnemySystem
var player: Node3D var player: Node3D
var pen: Rect2 var pen: Rect2
## Set by FarmSim: the field loose animals walk along, toward the farm's nearest edge. ## The playable map (FarmZones.playable): loose animals roam inside it.
var farm_rect := Rect2()
## Set by FarmSim: the field toward the farm's nearest edge. An animal getting out of an open pen
## walks down it until it's out of the pen (and no further).
var escape_field := PackedInt32Array() var escape_field := PackedInt32Array()
var count: int = 0 var count: int = 0
## There's a way out of the pen that crosses no structure. ## There's a way out of the pen that crosses no structure.
@ -61,14 +76,14 @@ var calm := PackedFloat32Array()
var phase := PackedFloat32Array() var phase := PackedFloat32Array()
## Order in the line behind the scarecrow (0 = first), -1 when not following. ## Order in the line behind the scarecrow (0 = first), -1 when not following.
var slot := PackedInt32Array() var slot := PackedInt32Array()
## Wandering out of the open pen and not out yet (so being inside doesn't count as home). ## Loose and walking out of the open pen, not out yet (so being inside doesn't make it home).
var leaving := PackedByteArray() var leaving := PackedByteArray()
var kinds: Array[String] = [] var kinds: Array[String] = []
var _start := PackedVector2Array() var _start := PackedVector2Array()
var _start_yaw := PackedFloat32Array() var _start_yaw := PackedFloat32Array()
## #12: each animal's grazing spot outside the pen, where it starts (GameConfig.animal_loose_spots, ## #12: each animal's spot outside the pen (GameConfig.animal_loose_spots, cycled if there are
## cycled if there are more animals than spots) and wanders around while LOOSE. ## more animals than spots), where it starts and where it's back every morning while LOOSE.
var _loose_spot := PackedVector2Array() var _loose_spot := PackedVector2Array()
var _pivots: Array[Node3D] = [] var _pivots: Array[Node3D] = []
var _meshes: Array = [] # per animal: Array[MeshInstance3D] var _meshes: Array = [] # per animal: Array[MeshInstance3D]
@ -92,8 +107,10 @@ static func find_animals(pen_zone: Node3D) -> Array[Node3D]:
return out return out
## p_farm_rect: the playable map (FarmZones.playable), where loose animals roam; empty means the
## whole navigation grid.
func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNavigation, p_loot: LootSystem, func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNavigation, p_loot: LootSystem,
p_enemies: EnemySystem, p_player: Node3D) -> void: p_enemies: EnemySystem, p_player: Node3D, p_farm_rect: Rect2 = Rect2()) -> void:
campaign = p_campaign campaign = p_campaign
config = p_campaign.config config = p_campaign.config
nav = p_nav nav = p_nav
@ -102,6 +119,8 @@ func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNaviga
player = p_player player = p_player
leaders = [p_player] leaders = [p_player]
pen = pen_zone.rect() pen = pen_zone.rect()
farm_rect = p_farm_rect if p_farm_rect.has_area() \
else Rect2(nav.origin_x, nav.origin_z, nav.width * nav.cell_size, nav.height * nav.cell_size).grow(-nav.cell_size)
_rng.seed = 8061 _rng.seed = 8061
var found := find_animals(pen_zone) var found := find_animals(pen_zone)
count = found.size() count = found.size()
@ -142,8 +161,8 @@ func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNaviga
sync_from_state() sync_from_state()
## Every animal back at its spot -- in the pen if penned, or its loose spot outside it otherwise ## Every animal back at its spot -- in the pen if penned, or its loose spot outside it otherwise,
## (or hidden if lost) -- nobody following (new morning, retry). ## wherever it roamed (or hidden if lost) -- nobody following (new morning, retry).
func sync_from_state() -> void: func sync_from_state() -> void:
for k in _trails.size(): for k in _trails.size():
_trails[k] = PackedVector2Array() _trails[k] = PackedVector2Array()
@ -200,7 +219,8 @@ func place(id: int, p: Vector2) -> void:
pos[id] = p pos[id] = p
prev[id] = p prev[id] = p
speed[id] = 0.0 speed[id] = 0.0
timer[id] = _rng.randf_range(0.6, 1.2) # a moment's shock before it bolts leaving[id] = 0
timer[id] = _rng.randf_range(0.6, 1.2) # a moment's shock before it wanders off
func start_following(id: int) -> void: func start_following(id: int) -> void:
@ -266,18 +286,17 @@ func step(dt: float) -> void:
LootSystem.Status.HOME: LootSystem.Status.HOME:
slot[id] = -1 slot[id] = -1
_wander(id, item, dt) _wander(id, item, dt)
LootSystem.Status.LOOSE: LootSystem.Status.LOOSE, LootSystem.Status.DROPPED:
slot[id] = -1 slot[id] = -1
_wander(id, item, dt) if loot.status[item] == LootSystem.Status.DROPPED:
LootSystem.Status.DROPPED: loot.animal_loose(item, pos[id]) # #21: an animal is never left lying dropped
slot[id] = -1 if leaving[id] == 1:
if not in_pen(pos[id]): _leave_pen(id, item, dt)
leaving[id] = 0 elif pen.has_point(pos[id]):
if in_pen(pos[id]) and leaving[id] == 0: loot.animal_home(item) # dropped inside the pen: it's home again
loot.animal_home(item)
_rest(id) _rest(id)
else: else:
_stray(id, item, dt) _wander(id, item, dt)
LootSystem.Status.FOLLOWING: LootSystem.Status.FOLLOWING:
var k := clampi(leader[id], 0, at.size() - 1) var k := clampi(leader[id], 0, at.size() - 1)
_follow(id, item, at[k], dt) _follow(id, item, at[k], dt)
@ -311,6 +330,8 @@ func _wander(id: int, item: int, dt: float) -> void:
goal[id] = _wander_goal(id, item) goal[id] = _wander_goal(id, item)
speed[id] = float(WANDER_SPEED.get(kinds[id], 0.7)) speed[id] = float(WANDER_SPEED.get(kinds[id], 0.7))
timer[id] = 8.0 # give up on a goal it can't reach timer[id] = 8.0 # give up on a goal it can't reach
if loot.status[item] == LootSystem.Status.LOOSE:
timer[id] = maxf(timer[id], pos[id].distance_to(goal[id]) / speed[id] + 2.0) # a longer walk
return return
var to := goal[id] - pos[id] var to := goal[id] - pos[id]
if to.length() < 0.2 or timer[id] <= 0.0: if to.length() < 0.2 or timer[id] <= 0.0:
@ -319,21 +340,21 @@ func _wander(id: int, item: int, dt: float) -> void:
_move(id, to.normalized(), speed[id], dt) _move(id, to.normalized(), speed[id], dt)
func _stray(id: int, item: int, dt: float) -> void: ## A loose animal that got out of the open pen walks down the escape field until it's out of the
if escape_field.size() > 0 and escape_field[nav.cell_of(pos[id].x, pos[id].y)] == 0: ## pen (then it roams like any loose animal). If the pen shuts first, or it can't get out in
loot.animal_escaped(item) ## LEAVE_TIME, it settles: back home if it's still inside the pen.
speed[id] = 0.0 func _leave_pen(id: int, item: int, dt: float) -> void:
return var out := not pen.grow(0.75).has_point(pos[id])
timer[id] -= dt timer[id] -= dt
if timer[id] <= 0.0: if not out and pen_open and timer[id] > 0.0 and escape_field.size() > 0 \
if speed[id] > 0.0: and nav.flow_direction(escape_field, pos[id].x, pos[id].y, _dir):
speed[id] = 0.0 # graze a moment
timer[id] = _rng.randf_range(0.8, 1.8)
else:
speed[id] = config.stray_speed speed[id] = config.stray_speed
timer[id] = _rng.randf_range(3.0, 5.0)
if speed[id] > 0.0 and escape_field.size() > 0 and nav.flow_direction(escape_field, pos[id].x, pos[id].y, _dir):
_move(id, Vector2(_dir[0], _dir[1]), speed[id], dt) _move(id, Vector2(_dir[0], _dir[1]), speed[id], dt)
return
leaving[id] = 0
if pen.has_point(pos[id]):
loot.animal_home(item)
_rest(id)
func _follow(id: int, item: int, sc: Vector2, dt: float) -> void: func _follow(id: int, item: int, sc: Vector2, dt: float) -> void:
@ -344,8 +365,7 @@ func _follow(id: int, item: int, sc: Vector2, dt: float) -> void:
_rest(id) _rest(id)
return return
if pos[id].distance_to(sc) > FOLLOW_LEASH: if pos[id].distance_to(sc) > FOLLOW_LEASH:
loot.status[item] = LootSystem.Status.DROPPED loot.animal_loose(item, pos[id])
loot.ground[item] = pos[id]
slot[id] = -1 slot[id] = -1
_rest(id) _rest(id)
return return
@ -384,8 +404,10 @@ func _rest(id: int) -> void:
timer[id] = _rng.randf_range(1.5, 4.0) timer[id] = _rng.randf_range(1.5, 4.0)
## A HOME animal wanders inside the pen; a LOOSE one grazes within LOOSE_WANDER_RADIUS of its own ## A HOME animal wanders inside the pen. A LOOSE one (#21) roams the farm: its next goal is
## loose spot instead. ## ROAM_MIN..ROAM_MAX meters away, inside the playable map (ROAM_MARGIN in from the edge),
## walkable, in a clear straight line (no obstacle or structure in the way), and neither inside the
## pen (PEN_KEEP_OUT around it) nor across it. With no such goal it stays put a while.
func _wander_goal(id: int, item: int) -> Vector2: func _wander_goal(id: int, item: int) -> Vector2:
if loot.status[item] == LootSystem.Status.HOME: if loot.status[item] == LootSystem.Status.HOME:
var area := pen.grow(-1.2) var area := pen.grow(-1.2)
@ -394,16 +416,35 @@ func _wander_goal(id: int, item: int) -> Vector2:
if nav.is_walkable(nav.cell_of(p.x, p.y)): if nav.is_walkable(nav.cell_of(p.x, p.y)):
return p return p
return area.get_center() return area.get_center()
var center := _loose_spot[id] var from := pos[id]
for attempt in 12: var area := farm_rect.grow(-ROAM_MARGIN)
var p := center + Vector2(_rng.randf_range(-LOOSE_WANDER_RADIUS, LOOSE_WANDER_RADIUS), var keep_out := pen.grow(PEN_KEEP_OUT)
_rng.randf_range(-LOOSE_WANDER_RADIUS, LOOSE_WANDER_RADIUS)) # Dropped off the map by a carrier: reach far enough to get back on.
if nav.is_walkable(nav.cell_of(p.x, p.y)): var reach := ROAM_MAX + from.distance_to(Vector2(clampf(from.x, area.position.x, area.end.x),
clampf(from.y, area.position.y, area.end.y)))
for attempt in 16:
var p := from + Vector2.from_angle(_rng.randf() * TAU) * _rng.randf_range(ROAM_MIN, reach)
if not area.has_point(p) or keep_out.has_point(p) or not nav.is_walkable(nav.cell_of(p.x, p.y)):
continue
if _crosses(pen, from, p) or not nav.line_clear(from.x, from.y, p.x, p.y):
continue
return p return p
return center return from
## At night, while the pen is open, a calm animal walks out now and then. ## Whether the segment a..b touches the rectangle.
static func _crosses(r: Rect2, a: Vector2, b: Vector2) -> bool:
if r.has_point(a) or r.has_point(b):
return true
var corners := [r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y)]
for k in 4:
if Geometry2D.segment_intersects_segment(a, b, corners[k], corners[(k + 1) % 4]) != null:
return true
return false
## At night, while the pen is open, a calm animal gets out now and then: it's loose (LootSystem.
## animal_strays) and walks out of the pen (_leave_pen).
func _wander_out(dt: float) -> void: func _wander_out(dt: float) -> void:
var ph := campaign.state.phase var ph := campaign.state.phase
if not pen_open or (ph != CampaignController.Phase.NIGHT and ph != CampaignController.Phase.DAWN): if not pen_open or (ph != CampaignController.Phase.NIGHT and ph != CampaignController.Phase.DAWN):
@ -422,7 +463,7 @@ func _wander_out(dt: float) -> void:
loot.animal_strays(loot.animal_item(id)) loot.animal_strays(loot.animal_item(id))
leaving[id] = 1 leaving[id] = 1
speed[id] = config.stray_speed speed[id] = config.stray_speed
timer[id] = 4.0 timer[id] = LEAVE_TIME
func _record_trail(k: int, sc: Vector2) -> void: func _record_trail(k: int, sc: Vector2) -> void:

View file

@ -6,7 +6,7 @@ extends Node
## repair, shed drop-off) -> weapons (recharge, switching) -> aim and attack (pitchfork, corn ## repair, shed drop-off) -> weapons (recharge, switching) -> aim and attack (pitchfork, corn
## shooter, pumpkin bombs) -> enemies (behavior, steering, motion, collision, traps) -> enemy ## shooter, pumpkin bombs) -> enemies (behavior, steering, motion, collision, traps) -> enemy
## melee -> automated defenses -> shots -> pumpkin bombs -> recovery by touch -> animals ## melee -> automated defenses -> shots -> pumpkin bombs -> recovery by touch -> animals
## (wander, stray, follow) -> night arrivals (WaveDirector) -> deferred enemy removals -> ## (wander, roam, follow) -> night arrivals (WaveDirector) -> deferred enemy removals ->
## flow-field rebuild slice -> render upload -> campaign phase timers and outcome. ## flow-field rebuild slice -> render upload -> campaign phase timers and outcome.
## Whenever the structures change (built, broken, dismantled), the flow fields are rebuilt as ## Whenever the structures change (built, broken, dismantled), the flow fields are rebuilt as
## FieldJobs in slices of flow_slice_cells per tick; thieves keep using the old fields until the ## FieldJobs in slices of flow_slice_cells per tick; thieves keep using the old fields until the
@ -16,8 +16,8 @@ extends Node
## escape: WaveDirector.ground_spawns are the edge cells with a route in), owns the combat and theft systems, ## escape: WaveDirector.ground_spawns are the edge cells with a route in), owns the combat and theft systems,
## and applies the phase rules: thieves arrive only at night (the night's NightPlan, run by ## and applies the phase rules: thieves arrive only at night (the night's NightPlan, run by
## WaveDirector), sunrise makes them retreat (carriers keep running), the end of the dawn grace ## WaveDirector), sunrise makes them retreat (carriers keep running), the end of the dawn grace
## sends the rest off the farm with whatever they carry, returns dropped loot (and loose animals) ## sends the rest off the farm with whatever they carry, returns dropped loot (and the animals
## home, and regrows the gather points, and every new morning (also after a retry) resets the ## still following the scarecrow) home, and regrows the gather points, and every new morning (also after a retry) resets the
## theft state from the farm state. DayNight lights the phases; PhaseHud, AssetHud, ReviewPanel, ## theft state from the farm state. DayNight lights the phases; PhaseHud, AssetHud, ReviewPanel,
## and the other HUD parts show them. Co-op (CoopSession): a second scarecrow (add_partner) is ## and the other HUD parts show them. Co-op (CoopSession): a second scarecrow (add_partner) is
## simulated alongside the first, and on the partner's machine the farm is a replica: nothing is ## simulated alongside the first, and on the partner's machine the farm is a replica: nothing is
@ -185,7 +185,7 @@ func _ready() -> void:
loot.animals = animals loot.animals = animals
loot.shed_stock = shed_stock loot.shed_stock = shed_stock
loot.setup(campaign, zones.crop_units(), enemies, AnimalSystem.find_animals(pen_zone).size()) loot.setup(campaign, zones.crop_units(), enemies, AnimalSystem.find_animals(pen_zone).size())
animals.setup(campaign, pen_zone, nav, loot, enemies, player) animals.setup(campaign, pen_zone, nav, loot, enemies, player, zones.playable)
if animals.count != config.start_animals: if animals.count != config.start_animals:
push_warning("The pen holds %d animals but GameConfig.start_animals is %d" % [animals.count, config.start_animals]) push_warning("The pen holds %d animals but GameConfig.start_animals is %d" % [animals.count, config.start_animals])
enemies.enemy_removed.connect(loot.on_enemy_removed) enemies.enemy_removed.connect(loot.on_enemy_removed)
@ -337,7 +337,7 @@ func _ready() -> void:
toasts.push("Breach! A %s was broken" % StructureSystem.NAMES[type].to_lower(), Color(1.0, 0.35, 0.3))) toasts.push("Breach! A %s was broken" % StructureSystem.NAMES[type].to_lower(), Color(1.0, 0.35, 0.3)))
animals.pen_changed.connect(func(open: bool) -> void: animals.pen_changed.connect(func(open: bool) -> void:
if open and campaign.state.phase != CampaignController.Phase.MORNING: if open and campaign.state.phase != CampaignController.Phase.MORNING:
toasts.push("The pen is open: animals will wander out at night", Color(1.0, 0.55, 0.35))) toasts.push("The pen is open: at night the animals in it will get out and roam loose", Color(1.0, 0.55, 0.35)))
scarecrow.patch_denied.connect(func(missing: Dictionary) -> void: scarecrow.patch_denied.connect(func(missing: Dictionary) -> void:
toasts.push("Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5))) toasts.push("Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5)))
if alerts != null: if alerts != null:
@ -802,8 +802,8 @@ func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignContr
## End of the dawn grace: whoever is still on the farm leaves (carrying their loot off), and ## End of the dawn grace: whoever is still on the farm leaves (carrying their loot off), and
## loot still lying on the ground goes home (crops to their plots, sacks to the shed, loose ## loot still lying on the ground goes home (crops to their plots, sacks to the shed, animals
## animals to the pen). #13: grows crops_total for any field that just sprouted (state.night is ## still following the scarecrow to the pen; #21: loose animals stay loose). #13: grows crops_total for any field that just sprouted (state.night is
## the night that just finished; nights_survived isn't set to it until right after this signal), ## the night that just finished; nights_survived isn't set to it until right after this signal),
## so the morning snapshot (retry, the save file) already has it right. The new field's units ## so the morning snapshot (retry, the save file) already has it right. The new field's units
## themselves flip from DORMANT to HOME in loot.sync_from_state(), at the morning that follows. ## themselves flip from DORMANT to HOME in loot.sync_from_state(), at the morning that follows.

View file

@ -76,22 +76,24 @@ extends Resource
## A supply thief takes this many units of the material the shed holds most of (never more than ## A supply thief takes this many units of the material the shed holds most of (never more than
## there is). ## there is).
@export_range(1, 100) var supply_bundle: int = 5 @export_range(1, 100) var supply_bundle: int = 5
## Loose animals (dropped, or wandered out of an open pen) walk toward the farm's nearest edge at ## An animal getting out of an open pen walks out at this speed; once it's out it's loose and
## this speed, stopping to graze now and then; one that gets off the farm is lost. ## roams the farm like any other (AnimalSystem). Animals never leave the farm on their own.
@export var stray_speed: float = 1.1 @export var stray_speed: float = 1.1
## At night, while the pen is open (its gate broken or removed), one animal wanders out every ## At night, while the pen is open (nothing built yet, or its gate broken or removed), one calm
## this many seconds. An animal brought back stays calm (won't wander out) for animal_calm_time. ## penned animal gets out every this many seconds and is loose. An animal brought back stays calm
## (won't get out again) for animal_calm_time.
@export var animal_wander_interval: float = 10.0 @export var animal_wander_interval: float = 10.0
@export var animal_calm_time: float = 30.0 @export var animal_calm_time: float = 30.0
## Animals following the scarecrow walk its trail at up to this speed. ## Animals following the scarecrow walk its trail at up to this speed.
@export var follow_speed: float = 6.0 @export var follow_speed: float = 6.0
## Where loose animals start (#12): scattered open-farmyard spots outside FarmZone.Kind.ANIMAL_PEN ## Where loose animals start (#12), and where a loose one is back every morning (#21: in between
## (x -10..4, z -11..-1), walkable, and clear of the future crop fields (x -11..-1 z 2..12 and ## it roams the whole farm): a row of open-farmyard spots south and south-east of
## x 2..12 z 2..12 -- see LAYOUT.md). Each is grazed around (AnimalSystem.LOOSE_WANDER_RADIUS) ## FarmZone.Kind.ANIMAL_PEN (x -10..4, z -11..-1), walkable, clear of the crop fields (x -11..-1
## until the player leads that animal into a built pen. Cycles if there are more animals than spots. ## z 2..12, x 2..12 z 2..12, and the sunflowers from x 14 -- see LAYOUT.md), and well in from the
## farm's edge. Cycles if there are more animals than spots.
@export var animal_loose_spots: Array[Vector2] = [ @export var animal_loose_spots: Array[Vector2] = [
Vector2(-9.0, 0.5), Vector2(-6.0, 0.5), Vector2(-3.0, 0.5), Vector2(0.0, 0.5), Vector2(3.0, 0.5), Vector2(-9.0, 0.5), Vector2(-6.0, 0.5), Vector2(-3.0, 0.5), Vector2(0.0, 0.5), Vector2(3.0, 0.5),
Vector2(-12.0, -3.0), Vector2(-12.0, -6.0), Vector2(-12.0, -9.0), Vector2(6.0, 0.5), Vector2(9.0, 0.5), Vector2(12.0, 0.5),
] ]
## What a thief with no set target goes for ("any" in a night plan), and where a thief whose target ## What a thief with no set target goes for ("any" in a night plan), and where a thief whose target
## is gone goes next: relative weights per category. ## is gone goes next: relative weights per category.

View file

@ -12,18 +12,20 @@ extends Node3D
## HOME in its plot, the pen, or the shed. One thief at a time may claim it: it is then ## HOME in its plot, the pen, or the shed. One thief at a time may claim it: it is then
## targeted ("!" marker) and, while being taken, shows a filling progress ring. ## targeted ("!" marker) and, while being taken, shows a filling progress ring.
## CARRIED on a thief, outlined in its category's color, with a badge over it. ## CARRIED on a thief, outlined in its category's color, with a badge over it.
## DROPPED its carrier was stopped. A crop or a sack lies on the ground, glowing; an animal is ## DROPPED crops and sacks: its carrier was stopped, and it lies on the ground, glowing. The
## loose and makes for the farm's edge (AnimalSystem). The scarecrow walks up to it to ## scarecrow walks up to it to recover it, and another thief may claim it. (An animal
## recover it (a loose animal then follows it, at most max_following_animals at once), ## whose carrier was stopped is LOOSE where it fell instead, #21.)
## and another thief may claim it. ## FOLLOWING animals only: following the scarecrow (at most max_following_animals at once);
## FOLLOWING animals only: following the scarecrow; back inside the pen it is home. ## back inside the pen it is home.
## LOOSE animals only (#12): starts here, scattered outside the pen, grazing calmly in place ## LOOSE animals only (#12, #21): out of the pen, roaming the whole farm (AnimalSystem),
## (AnimalSystem) instead of making for the edge. A thief may still claim and carry one ## never off it on its own. Every animal starts here; one also gets here when its
## off (then it's DROPPED, same as any theft: it runs for the edge). The scarecrow ## carrier is stopped (animal_loose; inside the pen it's home again), when it gets out
## walking up to it starts it following, same as a dropped animal; entering the pen ## of an open pen at night (animal_strays), or when its scarecrow got too far ahead.
## makes it HOME, and FarmState records it as penned so sync_from_state() keeps it ## FarmState stops counting it as penned, so the next morning puts it back at its
## home each morning instead of resetting it loose. ## loose spot. A thief may claim and carry one off. The scarecrow walking up to it
## LOST carried (or, for an animal, wandered) off the farm. Crops and animals are recorded ## starts it following; entering the pen makes it HOME, and FarmState records it as
## penned so sync_from_state() keeps it home each morning.
## LOST carried off the farm, the only way to lose an item. Crops and animals are recorded
## in FarmState and gone for the rest of the run; a sack's contents are gone and the ## in FarmState and gone for the rest of the run; a sack's contents are gone and the
## sack is free for the next theft. ## sack is free for the next theft.
## DORMANT crops only (#13): a unit of one of the later fields (lettuce/cabbage, corn) that ## DORMANT crops only (#13): a unit of one of the later fields (lettuce/cabbage, corn) that
@ -67,8 +69,8 @@ const THREAT_COLORS := {
## kind: &"targeted", &"stolen", &"dropped", &"recovered", &"returned" (back home without the ## kind: &"targeted", &"stolen", &"dropped", &"recovered", &"returned" (back home without the
## scarecrow's help: auto at dawn, or an animal dropped inside the pen), &"lost", &"following", ## scarecrow's help: auto at dawn, or an animal dropped inside the pen), &"lost", &"following",
## &"follow_full" (the scarecrow already leads the most animals it can), &"strayed" (an animal ## &"follow_full" (the scarecrow already leads the most animals it can), &"strayed" (an animal got
## wandered out of an open pen). ## out of an open pen: it's loose now).
signal loot_event(kind: StringName, id: int, position: Vector3) signal loot_event(kind: StringName, id: int, position: Vector3)
var campaign: CampaignController var campaign: CampaignController
@ -390,14 +392,17 @@ func pick_up(id: int, handle: int) -> bool:
return true return true
## The carrier was stopped at (x, z). ## The carrier was stopped at (x, z). A crop or sack lies there DROPPED; an animal is loose there
## (#21), and AnimalSystem makes it home again if that's inside the pen.
func drop(id: int, handle: int, x: float, z: float) -> void: func drop(id: int, handle: int, x: float, z: float) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle: if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return return
status[id] = Status.DROPPED status[id] = Status.DROPPED
holder[id] = -1 holder[id] = -1
ground[id] = Vector2(x, z) ground[id] = Vector2(x, z)
if category[id] == Category.ANIMAL and animals != null: if category[id] == Category.ANIMAL:
animal_loose(id, ground[id])
if animals != null:
animals.place(animal_index(id), ground[id]) animals.place(animal_index(id), ground[id])
loot_event.emit(&"dropped", id, _world(ground[id])) loot_event.emit(&"dropped", id, _world(ground[id]))
@ -409,9 +414,9 @@ func escape(id: int, handle: int) -> void:
_lose(id) _lose(id)
## The scarecrow got a dropped (or loose, #12) item back: a crop returns to its plot, a sack to ## The scarecrow got a dropped item (or a loose animal, #12) back: a crop returns to its plot, a
## the shed, and an animal starts following (if the scarecrow has room for another) -- a dropped ## sack to the shed, and a loose animal starts following (if the scarecrow has room for another),
## one recovered from a thief exactly as before, and a loose one led in for the first time. ## whether a thief dropped it, it got out of the pen, or it was never led in.
func recover(id: int) -> bool: func recover(id: int) -> bool:
if not is_valid_unit(id): if not is_valid_unit(id):
return false return false
@ -441,11 +446,12 @@ func recover(id: int) -> bool:
return true return true
## An animal (loose, or following the scarecrow) is back inside the pen. ## An animal (following the scarecrow, or loose: dropped inside the pen, or shut in before it got
## out) is back inside the pen.
func animal_home(id: int) -> void: func animal_home(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL: if not is_valid_unit(id) or category[id] != Category.ANIMAL:
return return
if status[id] != Status.FOLLOWING and status[id] != Status.DROPPED: if status[id] != Status.FOLLOWING and status[id] != Status.DROPPED and status[id] != Status.LOOSE:
return return
var led := status[id] == Status.FOLLOWING var led := status[id] == Status.FOLLOWING
status[id] = Status.HOME status[id] = Status.HOME
@ -457,29 +463,37 @@ func animal_home(id: int) -> void:
loot_event.emit(&"recovered" if led else &"returned", id, _world(position_of(id))) loot_event.emit(&"recovered" if led else &"returned", id, _world(position_of(id)))
## An animal at home walks out of the open pen: it is loose now. ## An animal at home gets out of the open pen: it is loose now (and roams; it isn't lost).
func animal_strays(id: int) -> void: func animal_strays(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.HOME or holder[id] != -1: if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.HOME or holder[id] != -1:
return return
status[id] = Status.DROPPED animal_loose(id, position_of(id))
ground[id] = position_of(id)
campaign.state.record_event("animals_strayed") campaign.state.record_event("animals_strayed")
loot_event.emit(&"strayed", id, _world(ground[id])) loot_event.emit(&"strayed", id, _world(ground[id]))
## A loose animal got off the farm on its own. ## #21: an animal is loose at `at` -- its carrier was stopped there, it got out of the open pen, or
func animal_escaped(id: int) -> void: ## its scarecrow got too far ahead -- and no longer penned in FarmState, so the next morning puts it
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.DROPPED: ## back at its loose spot. Animals are never lost on their own; only a carrier leaving the farm
## loses one (escape).
func animal_loose(id: int, at: Vector2) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] == Status.LOST:
return return
_lose(id) status[id] = Status.LOOSE
holder[id] = -1
progress[id] = 0.0
ground[id] = at
campaign.state.unpen_animal(animal_index(id))
## End of the dawn grace (D6): dropped items still on the ground go home (crops to their plots, ## End of the dawn grace (D6): dropped items still on the ground go home (crops to their plots,
## sacks to the shed); loose and following animals are back in the pen. ## sacks to the shed), and animals still following the scarecrow are back in the pen. Loose
## animals stay loose (#21): the next morning puts them back at their loose spots.
func return_dropped() -> void: func return_dropped() -> void:
for id in range(1, item_count + 1): for id in range(1, item_count + 1):
var st := status[id] var st := status[id]
if st == Status.DROPPED or (st == Status.FOLLOWING and category[id] == Category.ANIMAL): var animal := category[id] == Category.ANIMAL
if (st == Status.DROPPED and not animal) or (st == Status.FOLLOWING and animal):
var at := _world(position_of(id)) var at := _world(position_of(id))
if category[id] == Category.SUPPLY: if category[id] == Category.SUPPLY:
_empty_sack(id, true) _empty_sack(id, true)

View file

@ -114,7 +114,7 @@ func refresh() -> void:
_title.text = "The farmers are away" _title.text = "The farmers are away"
lines.append("Keep the farm safe for %d nights until they come home: the crops, the animals in the pen, and the supplies in the shed." % nights) lines.append("Keep the farm safe for %d nights until they come home: the crops, the animals in the pen, and the supplies in the shed." % nights)
lines.append("By day, gather wood, scrap, and straw (hold E), store them at the barn, and build defenses (B). There's more to gather off the farm, to the north, east, and south.") lines.append("By day, gather wood, scrap, and straw (hold E), store them at the barn, and build defenses (B). There's more to gather off the farm, to the north, east, and south.")
lines.append("At night, stab aliens with your pitchfork (left mouse), scare them off (Q), and pick up anything they drop. A dropped animal runs off: walk up to it and lead it back to the pen. The supply shed sells a corn shooter (switch weapons with Tab or 1-2) and pumpkin bombs (throw them with right mouse).") lines.append("At night, stab aliens with your pitchfork (left mouse), scare them off (Q), and pick up anything they drop. Animals roam loose until you lead them into the pen: walk up to one and it follows you. The supply shed sells a corn shooter (switch weapons with Tab or 1-2) and pumpkin bombs (throw them with right mouse).")
else: else:
var e: Dictionary = s.night_log[s.night_log.size() - 1] var e: Dictionary = s.night_log[s.night_log.size() - 1]
_title.text = "Morning of day %d of %d" % [s.night, nights] _title.text = "Morning of day %d of %d" % [s.night, nights]
@ -126,7 +126,7 @@ func refresh() -> void:
s.animals, s.animals_total, s.supplies, s.scarecrow_hp, s.scarecrow_max_hp]) s.animals, s.animals_total, s.supplies, s.scarecrow_hp, s.scarecrow_max_hp])
lines.append(_damage_line()) lines.append(_damage_line())
if animals != null and animals.pen_open and s.animals > 0: if animals != null and animals.pen_open and s.animals > 0:
lines.append("The pen is open: put a gate in its opening (B) before nightfall, or animals will wander out.") lines.append("The pen is open: put a gate in its opening (B) before nightfall, or the animals in it will get out and roam loose.")
var r := s.resources var r := s.resources
if s.coop: # each scarecrow carries its own if s.coop: # each scarecrow carries its own
lines.append("In the shed: %s. %s's pouch: %s. %s's pouch: %s." % [_or_none(ResourceStore.describe(r.shed)), lines.append("In the shed: %s. %s's pouch: %s. %s's pouch: %s." % [_or_none(ResourceStore.describe(r.shed)),
@ -152,7 +152,7 @@ func grid_text() -> String:
## Per category: (taken, recovered, lost) in a night's log entry. Animals taken include those ## Per category: (taken, recovered, lost) in a night's log entry. Animals taken include those
## that wandered out of an open pen. ## that got out of an open pen (loose, not lost).
static func category_counts(e: Dictionary) -> Dictionary: static func category_counts(e: Dictionary) -> Dictionary:
return { return {
"Crops": [int(e["crops_stolen"]), int(e["crops_recovered"]), int(e["crops_lost"])], "Crops": [int(e["crops_stolen"]), int(e["crops_recovered"]), int(e["crops_lost"])],

View file

@ -11,7 +11,7 @@ const SLOTS := 5
## Loot events per category (LootSystem.Category): the text ("%s" is the item's noun) and color. ## Loot events per category (LootSystem.Category): the text ("%s" is the item's noun) and color.
const MESSAGES := { const MESSAGES := {
&"stolen": [["A crop was snatched!", "A %s was grabbed!", "Aliens took %s from the shed!"], Color(1.0, 0.6, 0.15)], &"stolen": [["A crop was snatched!", "A %s was grabbed!", "Aliens took %s from the shed!"], Color(1.0, 0.6, 0.15)],
&"dropped": [["The alien dropped the crop. Grab it!", "The alien dropped the %s. Catch it before it runs off!", &"dropped": [["The alien dropped the crop. Grab it!", "The alien dropped the %s. Lead it back to the pen!",
"The alien dropped %s. Grab it!"], Color(1.0, 0.9, 0.3)], "The alien dropped %s. Grab it!"], Color(1.0, 0.9, 0.3)],
&"recovered": [["Crop recovered", "The %s is back in the pen", "%s back in the shed"], Color(0.5, 1.0, 0.45)], &"recovered": [["Crop recovered", "The %s is back in the pen", "%s back in the shed"], Color(0.5, 1.0, 0.45)],
&"returned": [["A dropped crop went back to its plot", "The %s went back to the pen", "%s went back to the shed"], &"returned": [["A dropped crop went back to its plot", "The %s went back to the pen", "%s went back to the shed"],

View file

@ -1,20 +1,25 @@
extends RefCounted extends RefCounted
## All three farm targets on the real farm, with FarmSim stepped by hand at 60 Hz: task #12's ## All three farm targets on the real farm, with FarmSim stepped by hand at 60 Hz: tasks #12 and
## loose start (animals scattered outside the pen, grazing in place, claimable by thieves, and led ## #21's loose animals (scattered outside the pen at the start, roaming the whole farm day and
## in with the follow-trail mechanic); then, with every animal penned up front the old way, the ## night without ever leaving it, wandering into the pen, or getting lost on their own, back at
## animals in the pen (wandering, kept in by the pen's gate), an animal thief breaking in, catching ## their spots each morning, claimable by thieves, loose again where a killed carrier drops them,
## and carrying one off, a dropped animal running for the farm's edge, leading animals back (at most ## and led in with the follow-trail mechanic); then, with every animal penned up front the old
## three, through a gate), a pen breach letting animals wander out at night (and not by day), supply ## way, the animals in the pen (wandering, kept in by the pen's gate), an animal thief breaking in,
## thieves taking bundles from the shed's piles (never more than there is), dropping, recovering, ## catching and carrying one off, a dropped animal loose where it fell, leading animals back (at
## and losing them, the piles growing and shrinking with the stock, thieves falling back to another ## most three, through a gate), a pen breach letting animals out at night as loose animals (and
## target, the asset HUD, the end of the dawn grace, retry, and a farm stripped of all three. ## not by day; none lost), an unopposed thief carrying one off the farm, 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 P := CampaignController.Phase
const S := LootSystem.Status const S := LootSystem.Status
const C := LootSystem.Category const C := LootSystem.Category
const T := ThiefBehavior.State const T := ThiefBehavior.State
const DT := 1.0 / 60.0 const DT := 1.0 / 60.0
const AWAY := Vector3(-11.0, 0.0, 13.0) ## Where the scarecrow waits when it isn't needed: off the playable map, so loose animals (#21: they
## roam the whole map) never come within reach and start following it.
const AWAY := Vector3(-20.0, 0.0, 13.0)
var _events: Array = [] # [kind, id] var _events: Array = [] # [kind, id]
@ -55,11 +60,15 @@ func run(r: GameTestRunner) -> void:
await r.process_frame await r.process_frame
## Task #12: animals start loose, scattered outside the pen, grazing in place; a thief can still ## Tasks #12 and #21: animals start loose, scattered outside the pen. A thief can still claim and
## claim and steal one (raising the same theft alert as for a penned one, and same rule as any ## steal a loose animal (raising the same theft alert as for a penned one); killed, it drops the
## theft once it's dropped); the player leads one in with the follow-trail mechanic, entering the ## animal loose where it fell, not lost. Over a long day and night (no thieves) loose animals roam
## pen makes it home, and FarmState records it as penned so a morning resync keeps it home (and the ## the whole farm, well away from where they started, but never off the playable map, never into
## rest loose) instead of resetting the herd into the pen. ## the (unbuilt) pen, and never lost on their own; each morning they're back at their spots. The
## player leads one in with the follow-trail mechanic: entering the pen makes it home, and
## FarmState records it as penned so a morning resync keeps it home (and the rest loose) instead of
## resetting the herd into the pen. Last, an unopposed thief carries one off the farm: the only way
## to lose an animal.
func _loose_start(r: GameTestRunner) -> void: func _loose_start(r: GameTestRunner) -> void:
var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
r.root.add_child(farm) r.root.add_child(farm)
@ -72,29 +81,20 @@ func _loose_start(r: GameTestRunner) -> void:
player.global_position = AWAY player.global_position = AWAY
var loot := sim.loot var loot := sim.loot
var animals := sim.animals var animals := sim.animals
sim.campaign.begin_day() var c := sim.campaign
var s := c.state
c.begin_day()
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect() var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect()
var playable := sim.zones.playable
var all_loose := true var all_loose := true
var all_outside := true var all_outside := true
for id in range(1, animals.count + 1): for id in range(1, animals.count + 1):
all_loose = all_loose and loot.status[loot.animal_item(id)] == S.LOOSE all_loose = all_loose and loot.status[loot.animal_item(id)] == S.LOOSE
all_outside = all_outside and not pen.has_point(animals.position(id)) all_outside = all_outside and not pen.has_point(animals.position(id))
r.check(all_loose and all_outside and sim.campaign.state.penned_animals.is_empty(), r.check(all_loose and all_outside and s.penned_animals.is_empty(),
"%d animals start loose, scattered outside the (unbuilt) pen" % animals.count) "%d animals start loose, scattered outside the (unbuilt) pen" % animals.count)
# They graze in place near their own spot, not down the escape field toward the edge. # A thief can still claim and steal a loose animal; killed, it drops the animal loose where it
var start := animals.pos.duplicate() # fell (#21: not DROPPED, and it doesn't run for the edge).
_step(sim, 600)
var moved := 0
var strayed := false
for id in range(1, animals.count + 1):
var d := animals.position(id).distance_to(start[id])
if d > 0.2:
moved += 1
if d > 4.0:
strayed = true
r.check(moved > 0 and not strayed, "loose animals graze in place (%d of %d moved a little, none wandered off)" % [moved, animals.count])
# A thief can still claim and steal a loose animal; killed, it drops the animal, which still
# runs for the edge (unchanged DROPPED rule).
var h := sim.spawn_thief(C.ANIMAL, animals.position(1) + Vector2(1.5, 0.0)) var h := sim.spawn_thief(C.ANIMAL, animals.position(1) + Vector2(1.5, 0.0))
_step(sim, 1) _step(sim, 1)
var item1 := sim.enemies.target[sim.enemies.resolve_handle(h)] var item1 := sim.enemies.target[sim.enemies.resolve_handle(h)]
@ -106,22 +106,72 @@ func _loose_start(r: GameTestRunner) -> void:
var caught := _until(sim, func() -> bool: return loot.status[item1] == S.CARRIED, 60.0) var caught := _until(sim, func() -> bool: return loot.status[item1] == S.CARRIED, 60.0)
r.check(caught < 60.0, "and catches it (%.1f s)" % caught) r.check(caught < 60.0, "and catches it (%.1f s)" % caught)
var dh := sim.enemies.resolve_handle(h) var dh := sim.enemies.resolve_handle(h)
var fell := Vector2(sim.enemies.pos_x[dh], sim.enemies.pos_z[dh])
sim.enemies.apply_hit(dh, 99) sim.enemies.apply_hit(dh, 99)
_step(sim, 1) _step(sim, 1)
r.check(loot.status[item1] == S.DROPPED, "killed, it drops the animal loose again (same rule as any theft)")
var stolen_index := loot.animal_index(item1) var stolen_index := loot.animal_index(item1)
# Build the pen and lead a different (still-loose) animal in. r.check(loot.status[item1] == S.LOOSE and animals.position(stolen_index).distance_to(fell) < 0.2,
"killed, it drops the animal loose where it fell (not lost)")
# A long day and night with no thieves: they roam the whole farm, and stay on it.
var farthest := {"day": PackedFloat32Array(), "night": PackedFloat32Array()}
var off_map := 0
var into_pen := 0
for part: String in ["day", "night"]:
if part == "night":
_to_night(sim)
var start := animals.pos.duplicate()
var far := PackedFloat32Array()
far.resize(animals.count + 1)
for i in 90 * 60:
sim.step(DT)
if i % 10 != 0:
continue
for id in range(1, animals.count + 1):
var at := animals.position(id)
far[id] = maxf(far[id], at.distance_to(start[id]))
if not playable.has_point(at):
off_map += 1
if pen.has_point(at):
into_pen += 1
farthest[part] = far
for part: String in ["day", "night"]:
var far: PackedFloat32Array = farthest[part]
var roamed := 0
var least := INF
var most := 0.0
for id in range(1, animals.count + 1):
if far[id] > 4.0:
roamed += 1
least = minf(least, far[id])
most = maxf(most, far[id])
r.info("loose animals over 90 s of %s: %.1f..%.1f m from where they started" % [part, least, most])
r.check(roamed == animals.count, "over 90 s of %s, all %d loose animals roam more than 4 m (the least %.1f m, the most %.1f m)"
% [part, animals.count, least, most])
r.check(off_map == 0 and into_pen == 0 and s.phase == P.NIGHT,
"and they stay on the farm: never off the playable map, never into the pen")
r.check(loot.count(S.LOOSE, C.ANIMAL) == animals.count and s.lost_animals.is_empty(), "none of them is lost without a thief")
# The next morning puts every loose animal back at its spot.
c.advance_phase()
c.advance_phase()
r.check(s.phase == P.MORNING and loot.count(S.LOOSE, C.ANIMAL) == animals.count and _at_loose_spots(sim),
"the next morning every loose animal is back at its spot")
c.begin_day()
# Build the pen and lead a different (still-loose) animal in through its gate. The others are
# put back at their spots, south of the pen, so the walk (from east of the gate, straight in
# along its line) passes no other animal.
PenRing.build_full(sim) PenRing.build_full(sim)
_settle(sim) _settle(sim)
var lead_id := 1 animals.sync_from_state()
var lead_id := animals.count
while lead_id == stolen_index: while lead_id == stolen_index:
lead_id += 1 lead_id -= 1
var item := loot.animal_item(lead_id) var item := loot.animal_item(lead_id)
var p := animals.position(lead_id) var p := Vector2(PenRing.EAST_X + 10.0, PenRing.GATE_Z)
animals.place(lead_id, p)
player.global_position = Vector3(p.x + 0.8, 0.0, p.y) player.global_position = Vector3(p.x + 0.8, 0.0, p.y)
_step(sim, 1) _step(sim, 1)
r.check(loot.status[item] == S.FOLLOWING, "walking up to a loose animal starts it following, same as a dropped one") r.check(loot.status[item] == S.FOLLOWING, "walking up to a loose animal starts it following, same as a dropped one")
var path: Array[Vector2] = [Vector2(p.x, -2.0), Vector2(7.5, -2.0), Vector2(7.5, -6.0), Vector2(0.0, -6.0), Vector2(-3.0, -6.0)] var path: Array[Vector2] = [Vector2(0.0, PenRing.GATE_Z), Vector2(-3.0, PenRing.GATE_Z)]
var from := Vector2(player.global_position.x, player.global_position.z) var from := Vector2(player.global_position.x, player.global_position.z)
for target in path: for target in path:
while from.distance_to(target) > 0.05: while from.distance_to(target) > 0.05:
@ -129,19 +179,23 @@ func _loose_start(r: GameTestRunner) -> void:
player.global_position = Vector3(from.x, 0.0, from.y) player.global_position = Vector3(from.x, 0.0, from.y)
sim.step(DT) sim.step(DT)
_step(sim, 60) _step(sim, 60)
r.check(loot.status[item] == S.HOME and sim.campaign.state.is_animal_penned(lead_id), r.check(loot.status[item] == S.HOME and s.is_animal_penned(lead_id) and loot.followers() == 0,
"led through the gate into the pen: it's home, and FarmState records it as penned") "led through the gate into the pen: it's home, and FarmState records it as penned")
player.global_position = AWAY player.global_position = AWAY
_step(sim, 600) _step(sim, 600)
r.check(pen.has_point(animals.position(lead_id)), "once penned, it stays in the pen by day like any other") r.check(pen.has_point(animals.position(lead_id)), "once penned, it stays in the pen by day like any other")
# A new morning keeps the penned one home and the rest loose, not reset into the pen. # A new morning keeps the penned one home and the rest loose (at their spots), not reset into
# the pen.
loot.sync_from_state() loot.sync_from_state()
animals.sync_from_state() animals.sync_from_state()
var other_id := 1 r.check(loot.status[item] == S.HOME and s.is_animal_penned(lead_id) and s.penned_animals.size() == 1, "a new morning keeps the penned one home")
while other_id == stolen_index or other_id == lead_id: r.check(loot.count(S.LOOSE, C.ANIMAL) == animals.count - 1 and _at_loose_spots(sim), "and every never-led animal loose at its spot, not reset into the pen")
other_id += 1 # The one way to lose an animal: a thief carrying it off the farm. (Sent in amid the loose
r.check(loot.status[item] == S.HOME and sim.campaign.state.is_animal_penned(lead_id), "a new morning keeps the penned one home") # spots, so every loose animal is in plain view.)
r.check(loot.status[loot.animal_item(other_id)] == S.LOOSE, "and a never-led animal loose, not reset into the pen") var h2 := sim.spawn_thief(C.ANIMAL, Vector2(1.5, 0.5))
var gone := _until(sim, func() -> bool: return sim.enemies.resolve_handle(h2) == -1, 90.0)
r.check(gone < 90.0 and s.lost_animals.size() == 1 and loot.count(S.LOST, C.ANIMAL) == 1,
"an unopposed thief carries an animal off the farm: that one, and only that one, is lost (%.1f s)" % gone)
farm.queue_free() farm.queue_free()
await r.process_frame await r.process_frame
@ -189,7 +243,8 @@ func _pen_by_day(r: GameTestRunner, sim: FarmSim) -> void:
## An animal thief breaks the pen's gate, catches an animal, and carries it; killed, it drops the ## 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. ## animal loose where it fell (#21: no longer penned, but it stays on the farm instead of running
## for the edge); touched, the animal follows the scarecrow.
func _animal_theft(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: func _animal_theft(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var es := sim.enemies var es := sim.enemies
var loot := sim.loot var loot := sim.loot
@ -221,23 +276,23 @@ func _animal_theft(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) ->
var at := Vector2(es.pos_x[d], es.pos_z[d]) var at := Vector2(es.pos_x[d], es.pos_z[d])
es.apply_hit(d, 99) es.apply_hit(d, 99)
_step(sim, 1) _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") r.check(loot.status[item] == S.LOOSE and sim.animals.position(index).distance_to(at) < 0.2 and not s.is_animal_penned(index),
var near_edge := _edge_distance(sim, sim.animals.position(index)) "killing the carrier drops the animal where it fell: loose (no longer penned), not lost")
_step(sim, 300) _step(sim, 1200)
var later := _edge_distance(sim, sim.animals.position(index)) r.check(loot.status[item] == S.LOOSE and not s.is_animal_lost(index) and sim.zones.playable.has_point(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]) "20 s later it's still loose on the farm (it doesn't run for the edge)")
var p := sim.animals.position(index) var p := sim.animals.position(index)
player.global_position = Vector3(p.x + 0.8, 0.0, p.y) player.global_position = Vector3(p.x + 0.8, 0.0, p.y)
_step(sim, 1) _step(sim, 1)
r.check(loot.status[item] == S.FOLLOWING and _has(&"following", item), "walking up to it: it follows the scarecrow") 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 _make_loose(sim, index, p) # loose again for the next part
sim.animals.place(index, p)
player.global_position = AWAY player.global_position = AWAY
_step(sim, 1) _step(sim, 1)
## Lead loose animals back: at most three follow at once; they pass through a gate behind the ## 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. ## scarecrow, and inside the pen they are home. An animal dropped inside the pen (its carrier
## stopped there) is home again.
func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var loot := sim.loot var loot := sim.loot
var st := sim.structures var st := sim.structures
@ -248,7 +303,7 @@ func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
r.check(not sim.animals.pen_open, "the pen is shut again") r.check(not sim.animals.pen_open, "the pen is shut again")
var loose: Array[int] = [] var loose: Array[int] = []
for id in range(1, sim.animals.count + 1): for id in range(1, sim.animals.count + 1):
if loot.status[loot.animal_item(id)] == S.DROPPED: if loot.status[loot.animal_item(id)] == S.LOOSE:
loose.append(id) loose.append(id)
for id in range(1, sim.animals.count + 1): for id in range(1, sim.animals.count + 1):
if loose.size() < 4 and loot.status[loot.animal_item(id)] == S.HOME: if loose.size() < 4 and loot.status[loot.animal_item(id)] == S.HOME:
@ -259,7 +314,7 @@ func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
for k in loose.size(): for k in loose.size():
player.global_position = Vector3(9.0 + k * 3.0 + 0.6, 0.0, -2.0) player.global_position = Vector3(9.0 + k * 3.0 + 0.6, 0.0, -2.0)
_step(sim, 1) _step(sim, 1)
r.check(loot.followers() == sim.config.max_following_animals and loot.status[loot.animal_item(loose[3])] == S.DROPPED r.check(loot.followers() == sim.config.max_following_animals and loot.status[loot.animal_item(loose[3])] == S.LOOSE
and _has(&"follow_full", loot.animal_item(loose[3])), "three animals follow; the fourth waits (and the scarecrow is told why)") 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. # 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 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)]
@ -276,20 +331,28 @@ func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
home += 1 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(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") 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 # #21: loose animals never wander into the pen by themselves, but one dropped inside it (its
# carrier stopped there) is home again, and penned.
_events.clear()
_make_loose(sim, loose[3], Vector2(-1.0, -2.5))
_step(sim, 1) _step(sim, 1)
r.check(loot.status[loot.animal_item(loose[3])] == S.HOME, "a loose animal inside the pen is home again") r.check(loot.status[loot.animal_item(loose[3])] == S.HOME and s.is_animal_penned(loose[3]) and _has(&"returned", loot.animal_item(loose[3])),
"an animal dropped inside the pen is home again")
player.global_position = AWAY player.global_position = AWAY
_step(sim, 1) _step(sim, 1)
## With the gate down at night, animals wander out of the pen one at a time; a loose one that ## With the gate down at night, penned animals get out of the pen one at a time: each is loose at
## reaches the farm's edge is lost. By day an open pen keeps its animals. The end of the dawn grace brings ## once (#21: no longer penned), walks out through the opening, and roams the farm; none is lost
## loose ones back; retry restores the morning. ## without a thief. By day an open pen keeps its animals. The next morning the ones that got out
## are back at their loose spots (not in the pen) and the rest in the pen. An unopposed thief still
## carries one off the farm; retry restores the morning.
func _breach(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void: func _breach(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign var c := sim.campaign
var loot := sim.loot var loot := sim.loot
var st := sim.structures var st := sim.structures
var s := c.state
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect()
var gate := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)] var gate := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)]
st.damage(gate, 999) st.damage(gate, 999)
_settle(sim) _settle(sim)
@ -299,39 +362,55 @@ func _breach(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
r.check(not _has(&"strayed", -1) and loot.count(S.HOME, C.ANIMAL) == loot.animal_count - loot.count(S.LOST, C.ANIMAL), 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") "by day the animals stay in an open pen")
_to_night(sim) _to_night(sim)
var morning_lost := c.state.lost_animals.duplicate() var morning_lost := s.lost_animals.duplicate()
var first := _until(sim, func() -> bool: return _has(&"strayed", -1), sim.config.animal_wander_interval + 1.0) 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) r.check(first <= sim.config.animal_wander_interval * 0.3 + 0.1, "at night an animal soon gets out of the open pen (%.1f s)" % first)
var out_item: int = _events.filter(func(e: Array) -> bool: return e[0] == &"strayed")[0][1]
var out_id := loot.animal_index(out_item)
r.check(loot.status[out_item] == S.LOOSE and not s.is_animal_penned(out_id), "it's loose at once (no longer penned), not dropped or lost")
var strays := _until(sim, func() -> bool: return _count(&"strayed") >= 2, sim.config.animal_wander_interval + 1.0) 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) 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) var walked := _until(sim, func() -> bool: return not pen.grow(0.75).has_point(sim.animals.position(out_id)), 30.0)
r.check(lost < 90.0, "a wandering animal that reaches the farm's edge is lost (%.1f s later)" % lost) r.check(walked < 30.0 and loot.status[out_item] == S.LOOSE, "the first walks out of the pen through the opening")
var loose_at_dawn := loot.count(S.DROPPED, C.ANIMAL) _step(sim, 80 * 60)
r.check(loose_at_dawn > 0, "some are still loose on the farm (%d)" % loose_at_dawn) var roaming := 0
var still_lost := c.state.lost_animals.duplicate() var on_farm := true
for id in range(1, sim.animals.count + 1):
if loot.status[loot.animal_item(id)] == S.LOOSE:
roaming += 1
var at := sim.animals.position(id)
on_farm = on_farm and sim.zones.playable.has_point(at) and not pen.has_point(at)
r.check(s.phase == P.NIGHT and roaming >= 2 and on_farm and s.lost_animals == morning_lost and loot.count(S.LOST, C.ANIMAL) == morning_lost.size(),
"late in the night %d animals that got out roam the farm outside the pen, and none is lost" % roaming)
c.advance_phase() c.advance_phase()
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 var penned := s.penned_animals.size()
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") r.check(s.phase == P.MORNING and s.lost_animals == morning_lost and loot.count(S.HOME, C.ANIMAL) == penned
var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect() and loot.count(S.LOOSE, C.ANIMAL) == loot.animal_count - morning_lost.size() - penned and penned < loot.animal_count - morning_lost.size(),
"the next morning the ones that got out are still loose (not put back in the pen), the rest penned")
var inside := true var inside := true
for id in range(1, sim.animals.count + 1): for id in range(1, sim.animals.count + 1):
if loot.status[loot.animal_item(id)] == S.HOME: if loot.status[loot.animal_item(id)] == S.HOME:
inside = inside and pen.has_point(sim.animals.position(id)) 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(inside and _at_loose_spots(sim) and sim.animals.pen_open,
"every penned animal is in the pen and every loose one at its spot (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") 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] var e: Dictionary = s.night_log[s.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]) r.check(e["animals_lost"] == 0 and e["animals_strayed"] >= 2, "the night's record: %s" % [e])
# Retry: lose another one tonight, fall, and the morning comes back. # Retry: lose one to a thief tonight (the only way to lose an animal), fall, and the morning
var morning := c.state.to_dict() # comes back. The thief is sent in amid the loose spots: it takes a loose animal in plain view,
# or breaks into the pen (right behind it) for a penned one. (A thief after a loose animal it
# can't see heads for the pen meanwhile and gives up on it after a while.)
var still_lost := s.lost_animals.duplicate()
var morning := s.to_dict()
c.begin_day() c.begin_day()
c.state.resources.shed = {"wood": 50, "scrap": 50, "straw": 50} s.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
st.place("gate", 4.0, -6.0, 2) st.place("gate", 4.0, -6.0, 2)
_to_night(sim) _to_night(sim)
var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["west"]) var h := sim.spawn_thief(C.ANIMAL, Vector2(1.5, 0.5))
_until(sim, func() -> bool: return sim.enemies.resolve_handle(h) == -1, 90.0) _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") r.check(s.lost_animals.size() >= still_lost.size() + 1, "an unopposed animal thief carries one off the farm")
c.state.scarecrow_hp = 0 s.scarecrow_hp = 0
_step(sim, 1) _step(sim, 1)
c.retry_night() c.retry_night()
_step(sim, 1) _step(sim, 1)
@ -503,15 +582,23 @@ func _stripped(r: GameTestRunner, sim: FarmSim) -> void:
"carried off with nothing else left: the farm is stripped (D2)") "carried off with nothing else left: the farm is stripped (D2)")
## Puts an animal loose at p (as if dropped there). ## Puts an animal loose at p, as if its carrier was stopped there (#21: LOOSE and no longer penned;
## inside the pen it's home again on the next tick).
func _make_loose(sim: FarmSim, id: int, p: Vector2) -> void: func _make_loose(sim: FarmSim, id: int, p: Vector2) -> void:
var item := sim.loot.animal_item(id) sim.loot.animal_loose(sim.loot.animal_item(id), p)
sim.loot.status[item] = S.DROPPED
sim.loot.holder[item] = -1
sim.loot.ground[item] = p
sim.animals.place(id, p) sim.animals.place(id, p)
## Every loose animal stands at its own GameConfig.animal_loose_spots spot.
func _at_loose_spots(sim: FarmSim) -> bool:
var spots := sim.config.animal_loose_spots
for id in range(1, sim.animals.count + 1):
if sim.loot.status[sim.loot.animal_item(id)] == S.LOOSE \
and sim.animals.position(id).distance_to(spots[(id - 1) % spots.size()]) > 0.01:
return false
return true
func _to_night(sim: FarmSim) -> void: func _to_night(sim: FarmSim) -> void:
var c := sim.campaign var c := sim.campaign
while c.state.phase != P.NIGHT: while c.state.phase != P.NIGHT:
@ -536,10 +623,6 @@ func _count(kind: StringName) -> int:
return n 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: func _edge_cell(sim: FarmSim, side: String) -> int:
var p: Vector2 = GameTestRunner.EDGE[side] var p: Vector2 = GameTestRunner.EDGE[side]
return sim.nav.nearest_free(sim.nav.cell_of(p.x, p.y)) return sim.nav.nearest_free(sim.nav.cell_of(p.x, p.y))