Task #16: per-player pouch in co-op

Each scarecrow carries its own pouch (ResourceStore.pouches by avatar
slot; slot 0 is the solo player / host, `pouch` stays slot 0's), with one
shared pouch_capacity so a Bigger pouch grows both. The shed stays shared.

- Gathering, the shed drop-off, repair, upgrade-in-place, patching,
  building and buying all act on the acting avatar's slot. The host pays
  the partner's "place" and "buy" requests from P2's pouch and the shed.
- The partner's build mode, build hotbar, shop menus and materials HUD
  check affordability against P2's pouch (FarmSim.set_local).
- Alien Goop goes to the killer's pouch: FarmSim sets
  EnemySystem.attacker around each avatar's combat step and shots carry
  their shooter's slot; bomb/turret kills go to the nearest scarecrow.
  The replica no longer rolls goop locally.
- When the partner leaves, their pouch goes into the shed (and is named
  in the toast); a co-op save continued alone banks P2's pouch at morning.
- FarmState.VERSION 7 (resources.partner_pouch) with a v6 migration;
  CoopSession.PROTOCOL 4.
- Tests: per-slot store rules, v6 save migration, and test_coop cases for
  separate gathering, no cross-banking in the shed, own-pouch paying,
  shared capacity, goop credit and leaving. test_coop's crowd case now
  resets the loopback's drop counter so earlier traffic can't change
  which messages it loses.
- Docs: COOP.md and RULES.md no longer say the pouch is shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-06 13:06:25 -04:00
parent 26b735d3e6
commit fa7f67fe04
23 changed files with 535 additions and 138 deletions

View file

@ -1,8 +1,8 @@
class_name BuildHud
extends Control
## The build hotbar, shown in build mode: one slot per buildable with its key, name, and cost
## (red when it can't be afforded), the selected one highlighted, the controls, and how many
## structures stand on the farm.
## (red when the builder can't afford it from their own pouch and the shed), the selected one
## highlighted, the controls, and how many structures stand on the farm.
const SLOT := Vector2(230.0, 76.0)
const GAP := 12.0
@ -34,6 +34,7 @@ func _process(_delta: float) -> void:
if not visible:
return
var r := campaign.state.resources
var slot := build.kit.slot if build.kit != null else 0
var origin := _origin()
for i in StructureSystem.ORDER.size():
var t: String = StructureSystem.ORDER[i]
@ -43,7 +44,7 @@ func _process(_delta: float) -> void:
_names[i].position = pos + Vector2(12.0, 8.0)
_costs[i].text = ResourceStore.describe(cost)
_costs[i].position = pos + Vector2(12.0, 42.0)
_costs[i].add_theme_color_override("font_color", Color(0.9, 0.95, 0.9) if r.can_afford(cost) else Color(1.0, 0.45, 0.4))
_costs[i].add_theme_color_override("font_color", Color(0.9, 0.95, 0.9) if r.can_afford(cost, slot) else Color(1.0, 0.45, 0.4))
_help.text = "Build mode · LMB / RT build · Z C / d-pad rotate · 1-4 / Tab pick · RMB / B dismantle or leave · %d built" % \
build.structures.count()
_help.position = origin + Vector2(0.0, -34.0)

View file

@ -12,6 +12,7 @@ extends Node3D
## The scarecrow doesn't shoot, gather, or repair while building (FarmSim, Interactions).
## Co-op, on the partner's machine: placing and dismantling are sent to the host (place_request,
## dismantle_request), which checks them again and does them; the result comes back as a message.
## The cost is checked against (and paid from) the builder's own pouch and the shed (kit.slot).
signal message(text: String, color: Color)
signal toggled(on: bool)
@ -127,12 +128,12 @@ func step(_dt: float) -> void:
(": %s back in the shed" % ResourceStore.describe(back)) if not back.is_empty() else ""], Color(0.85, 0.95, 1.0))
hover = -1
return
reason = structures.validate(type(), cursor.x, cursor.y, rot, me)
reason = structures.validate(type(), cursor.x, cursor.y, rot, me, kit.slot)
if p[&"fire"]:
if reason == "" and place_request.is_valid():
place_request.call(type(), cursor.x, cursor.y, rot)
elif reason == "":
structures.place(type(), cursor.x, cursor.y, rot)
structures.place(type(), cursor.x, cursor.y, rot, kit.slot)
message.emit("Built a %s" % StructureSystem.NAMES[type()].to_lower(), Color(0.6, 1.0, 0.55))
else:
message.emit(reason, Color(1.0, 0.8, 0.5))

View file

@ -44,8 +44,9 @@ signal welcomed
## The wire format: both machines must speak the same one (hello and welcome carry it). 3: #10
## added a time field and two int32s (the upgrade target/progress) to _put_avatar/_read_avatar's
## per-avatar snapshot record.
const PROTOCOL := 3
## per-avatar snapshot record. 4: #16 gave each scarecrow its own pouch (the farm state's
## resources.partner_pouch, FarmState.VERSION 7).
const PROTOCOL := 4
const SNAP_EVERY := 4 # physics ticks: 15 Hz
const INPUT_EVERY := 3 # 20 Hz, when it changed
## Seconds: the partner's input goes out at least this often, changed or not.
@ -241,11 +242,14 @@ func stop(reason: String = "") -> void:
sim.audio.forward = Callable()
if was == Role.HOST:
var gone_name := partner_name
sim.remove_partner()
var left_behind := sim.remove_partner() # their pouch, now in the shed
sim.avatars[0].player_name = ""
sim.player.set_tag("", Color.WHITE)
if sim.toasts != null:
sim.toasts.push("%s left: you're on your own" % _display(gone_name, "Player 2"), Color(1.0, 0.8, 0.5))
var text := "%s left: you're on your own" % _display(gone_name, "Player 2")
if not left_behind.is_empty():
text += " (%s from their pouch is in the shed)" % ResourceStore.describe(left_behind)
sim.toasts.push(text, Color(1.0, 0.8, 0.5))
partner_left.emit(gone_name)
else:
ended.emit(reason)
@ -532,9 +536,9 @@ func _do_request(r: Array) -> void:
var rot := int(r[4])
if not StructureSystem.ORDER.has(type):
return
var why := sim.structures.validate(type, x, z, rot, a.position())
var why := sim.structures.validate(type, x, z, rot, a.position(), a.slot)
if why == "":
sim.structures.place(type, x, z, rot)
sim.structures.place(type, x, z, rot, a.slot) # paid from P2's pouch, then the shed
_events.append(["toast", "Built a %s" % StructureSystem.NAMES[type].to_lower(), Color(0.6, 1.0, 0.55)])
else:
_events.append(["toast", why, Color(1.0, 0.8, 0.5)])
@ -551,7 +555,7 @@ func _do_request(r: Array) -> void:
if Upgrades.shop_of(c.config, id) == "workbench" and (sim.structures == null or not sim.structures.workbench_available()):
_events.append(["toast", "The work area isn't available", Color(1.0, 0.8, 0.5)])
return
var text := Upgrades.buy(c, id, sim.structures)
var text := Upgrades.buy(c, id, sim.structures, a.slot) # paid from P2's pouch, then the shed
_events.append(["toast", text, Color(0.85, 0.75, 1.0) if text.contains("done:") else Color(1.0, 0.8, 0.5)])

View file

@ -112,6 +112,11 @@ var _free_ids := PackedInt32Array()
var _free_top: int = 0
var _pending := PackedInt32Array()
var _pending_count: int = 0
## Co-op goop credit: the avatar slot whose attack is being resolved right now (FarmSim sets it
## around each scarecrow's combat step; -1 otherwise: turrets, bombs going off, tests), and the
## slot that landed each enemy's killing hit, by stable id (read through killer_of()).
var attacker: int = -1
var _killer := PackedInt32Array()
# Diagnostics.
var spawn_skipped: int = 0
@ -134,7 +139,7 @@ func setup(cfg: GameConfig, p_nav: FarmNavigation, p_behavior: ThiefBehavior, me
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a.resize(capacity)
a.fill(0.0)
for a: PackedInt32Array in [health, target, carry, barrier, dense_id, id_dense, id_generation, _free_ids, _pending]:
for a: PackedInt32Array in [health, target, carry, barrier, dense_id, id_dense, id_generation, _free_ids, _pending, _killer]:
a.resize(capacity)
a.fill(0)
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
@ -222,6 +227,7 @@ func spawn(enemy_type: int, x: float, z: float, heading: Vector2, p_want: int =
spawn_skipped += 1
return -1
_free_top -= 1
_killer[id] = -1
var d := active_count
active_count += 1
var h := heading.normalized() if heading.length_squared() > 1e-6 else Vector2(0.0, -1.0)
@ -287,8 +293,9 @@ func visual_position(d: int) -> Vector2:
return Vector2(lerpf(prev_x[d], pos_x[d], f), lerpf(prev_z[d], pos_z[d], f))
## Applies one hit. Returns false for dead or pending slots (no double kills).
func apply_hit(d: int, damage: int = 1) -> bool:
## Applies one hit. Returns false for dead or pending slots (no double kills). by: the avatar
## slot that landed it (a shot's shooter), or -1 for whoever is attacking now (attacker).
func apply_hit(d: int, damage: int = 1, by: int = -1) -> bool:
if not is_alive_slot(d):
return false
health[d] -= damage
@ -297,14 +304,22 @@ func apply_hit(d: int, damage: int = 1) -> bool:
characters.hit(dense_id[d])
if health[d] <= 0:
kills += 1
_killer[dense_id[d]] = by if by >= 0 else attacker
queue_removal(d, Removal.KILLED)
elif behavior != null:
behavior.on_hit(self, d)
return true
func apply_hit_handle(handle: int, damage: int = 1) -> bool:
return apply_hit(resolve_handle(handle), damage)
func apply_hit_handle(handle: int, damage: int = 1, by: int = -1) -> bool:
return apply_hit(resolve_handle(handle), damage, by)
## The avatar slot whose hit killed this enemy (while enemy_removed is emitted for it), or -1:
## killed by a turret or a bomb, not killed, or a stale handle.
func killer_of(handle: int) -> int:
var d := resolve_handle(handle)
return _killer[dense_id[d]] if d >= 0 else -1
## Takes a living enemy out of the simulation now; its slot is released (and enemy_removed

View file

@ -34,6 +34,9 @@ var _life := PackedFloat32Array()
## Cannon, Shurikens, and Alien Ray fly at their own speeds).
var _speed := PackedFloat32Array()
var _damage := PackedInt32Array()
## The avatar slot that fired each shot (EnemySystem.attacker when it was fired; -1 for the
## automated defenses'), credited with what it kills (co-op Alien Goop).
var _owner := PackedInt32Array()
var _cfg: GameConfig
var _enemies: EnemySystem
var _bounds: Rect2
@ -50,6 +53,7 @@ func setup(cfg: GameConfig, enemies: EnemySystem, bounds: Rect2, shooter: RID) -
a.resize(capacity)
a.fill(0.0)
_damage.resize(capacity)
_owner.resize(capacity)
_ray.collision_mask = WORLD_LAYER
_ray.collide_with_areas = false
_ray.collide_with_bodies = true
@ -84,7 +88,8 @@ func fire(origin: Vector3, muzzle: Vector3, dir: Vector3, damage: int = 1, speed
exhausted += 1
return false
fired += 1
if _resolve_segment(origin.x, origin.z, muzzle.x, muzzle.z, false, damage):
var by := _enemies.attacker
if _resolve_segment(origin.x, origin.z, muzzle.x, muzzle.z, false, damage, by):
blocked_at_muzzle += 1
return false
var d := active_count
@ -95,6 +100,7 @@ func fire(origin: Vector3, muzzle: Vector3, dir: Vector3, damage: int = 1, speed
_dz[d] = dir.z
_life[d] = lifetime if lifetime > 0.0 else _cfg.projectile_lifetime
_damage[d] = damage
_owner[d] = by
_speed[d] = speed if speed > 0.0 else _cfg.projectile_speed
_renderer.write_new(d, muzzle.x, muzzle.z, dir.x, dir.z, 0.0)
return true
@ -108,7 +114,7 @@ func step(dt: float) -> void:
var z0 := _pz[i]
var x1 := x0 + _dx[i] * step_len
var z1 := z0 + _dz[i] * step_len
if _resolve_segment(x0, z0, x1, z1, true, _damage[i]):
if _resolve_segment(x0, z0, x1, z1, true, _damage[i], _owner[i]):
_release(i)
continue
_px[i] = x1
@ -152,8 +158,9 @@ func commit_render() -> void:
## Resolves the nearest world/enemy hit along a segment. Returns true if something was hit
## (damage is applied for enemy hits). use_motion selects the relative-motion enemy test.
func _resolve_segment(x0: float, z0: float, x1: float, z1: float, use_motion: bool, damage: int) -> bool:
## (damage is applied for enemy hits, credited to the shooter's avatar slot by). use_motion
## selects the relative-motion enemy test.
func _resolve_segment(x0: float, z0: float, x1: float, z1: float, use_motion: bool, damage: int, by: int) -> bool:
var h := _cfg.combat_height
var world_t := 2.0
_ray.from = Vector3(x0, h, z0)
@ -166,7 +173,7 @@ func _resolve_segment(x0: float, z0: float, x1: float, z1: float, use_motion: bo
var e := _enemies.sweep_hit(x0, z0, x1, z1, use_motion)
if e >= 0 and _enemies.hit_t <= world_t:
var t := _enemies.type[e]
_enemies.apply_hit(e, damage)
_enemies.apply_hit(e, damage, by)
hits_enemy += 1
hit.emit(Vector3(lerpf(x0, x1, _enemies.hit_t), h, lerpf(z0, z1, _enemies.hit_t)), t)
return true
@ -187,5 +194,6 @@ func _release(i: int) -> void:
_life[i] = _life[last]
_damage[i] = _damage[last]
_speed[i] = _speed[last]
_owner[i] = _owner[last]
_renderer.move_slot(last, i)
active_count -= 1

View file

@ -368,7 +368,9 @@ func step(dt: float) -> void:
for a in avatars:
var building := build.active if a.is_local else (a.remote != null and a.remote.build_active)
if a.kit.can_shoot() and a.interactions.can_shoot() and not building:
enemies.attacker = a.slot # its kills (and its shots') are its own (Alien Goop)
a.combat.step(dt)
enemies.attacker = -1
enemies.step(dt, p, SCARECROW_RADIUS)
for a in avatars:
if a.kit.alive:
@ -497,10 +499,14 @@ func add_partner(local: bool, name_text: String = "") -> Avatar:
## Co-op: player 2 left. Their scarecrow goes; if player 1's is down, that's the end of the night.
func remove_partner() -> void:
## What they carried goes into the shed (on the host). Returns what moved (material -> amount).
func remove_partner() -> Dictionary:
if partner == null:
return
return {}
var a := partner
var moved := {} if replica else campaign.state.resources.deposit(a.slot)
if not moved.is_empty():
shed_stock.refresh()
partner = null
avatars.erase(a)
if camera is FollowCamera and (camera as FollowCamera).target == a.body:
@ -515,10 +521,12 @@ func remove_partner() -> void:
campaign.state.coop = false
behavior.scarecrow2 = Vector2(INF, INF)
enemies.scarecrow2 = Vector2(INF, INF)
return moved
## Makes another scarecrow this machine's own (the partner's machine plays player 2): the HUD,
## the camera, build mode, the upgrade menu, sounds, and tips follow it.
## the camera, build mode, the upgrade menu, the materials readout (its own pouch), sounds, and
## tips follow it.
func set_local(a: Avatar) -> void:
for other in avatars:
other.is_local = other == a
@ -538,8 +546,12 @@ func set_local(a: Avatar) -> void:
build.kit = a.kit
if upgrade_panel != null:
upgrade_panel.player = a.body
upgrade_panel.slot = a.slot
if shed_panel != null:
shed_panel.player = a.body
shed_panel.slot = a.slot
if resource_hud != null:
resource_hud.slot = a.slot
if camera is FollowCamera:
(camera as FollowCamera).target = a.body
(camera as FollowCamera).snap_to_target()
@ -625,19 +637,37 @@ func _count_removal(handle: int, reason: EnemySystem.Removal, _x: float, _z: flo
## Alien Goop (Decision 11): a killed Alien (the thief type, display-named "Alien") has a
## config-tunable chance to drop goop, credited like a gathered material straight into the
## pouch (respecting its capacity; a full pouch simply loses the drop, same as any overflow).
func _drop_alien_goop(handle: int, reason: EnemySystem.Removal, _x: float, _z: float, _carry: int, _target: int) -> void:
if reason != EnemySystem.Removal.KILLED:
## Co-op: into the killer's pouch (EnemySystem.killer_of); a turret's or a bomb's kill goes to the
## scarecrow nearest to it (goop_slot). Only the host rolls it: the partner's farm state follows.
func _drop_alien_goop(handle: int, reason: EnemySystem.Removal, x: float, z: float, _carry: int, _target: int) -> void:
if reason != EnemySystem.Removal.KILLED or replica:
return
var d := enemies.resolve_handle(handle)
if d < 0 or enemies.type[d] != EnemySystem.TYPE_THIEF:
return
if _goop_rng.randf() >= config.alien_goop_drop_chance:
return
var added := campaign.state.resources.add_to_pouch("alien_goop", config.alien_goop_drop_qty)
var slot := goop_slot(enemies.killer_of(handle), Vector2(x, z))
var added := campaign.state.resources.add_to_pouch("alien_goop", config.alien_goop_drop_qty, slot)
if added > 0:
campaign.state.record_event("gathered_alien_goop", added)
## Whose pouch a kill's goop goes to: the killer's (an avatar slot still on the farm), else the
## scarecrow nearest to where it fell, a standing one before a downed one (solo: always slot 0).
func goop_slot(killer: int, at: Vector2) -> int:
var best := -1
var best_d := INF
for a in avatars:
if a.slot == killer:
return killer
var d := a.position().distance_squared_to(at) + (0.0 if a.kit.alive else 1e12)
if d < best_d:
best_d = d
best = a.slot
return maxi(best, 0)
## Keeps the field toward the scarecrow fresh while anything is fighting it.
func _update_hunt(dt: float) -> void:
_hunt_wait = maxf(_hunt_wait - dt, 0.0)
@ -745,6 +775,7 @@ func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignContr
CampaignController.Phase.MORNING:
if partner == null and not replica:
campaign.state.coop = false # a co-op save continued alone: solo rules
campaign.state.resources.deposit(1) # and player 2's pouch, saved that morning, is in the shed
enemies.clear()
projectiles.clear()
bombs.clear()

View file

@ -4,11 +4,12 @@ extends RefCounted
## scarecrow health, campaign progress, and the nightly records. Scene nodes only display it.
## to_dict() / from_dict() round-trip every field, also through JSON (the morning retry
## snapshot and the save game, SaveGame). Crops and animals are per-unit records (lost ids, 1..total);
## supplies are the supply shed's stock of construction materials (the shed and the scarecrow's
## supplies are the supply shed's stock of construction materials (the shed and each scarecrow's
## pouch live in resources). Gather points below full, bought upgrades, and the built structures
## are kept too.
const VERSION := 6
## 7: a pouch per scarecrow (resources.partner_pouch, #16).
const VERSION := 7
const KEYS: Array[String] = [
"night", "nights_survived", "phase", "phase_time_left", "scarecrow_max_hp", "scarecrow_hp",
"crops_total", "lost_crops", "animals_total", "lost_animals", "penned_animals", "supplies_total",
@ -98,7 +99,7 @@ var supplies: int:
set(_value):
push_error("FarmState.supplies is derived from the shed's stock")
## Wood, scrap, and straw in the supply shed and in the scarecrow's pouch.
## The materials in the supply shed and in each scarecrow's pouch (by avatar slot).
var resources := ResourceStore.new()
## Charges of the gather points that are below full (GatherNode name -> charges left); a point
## missing here is full.
@ -217,10 +218,11 @@ func record_event(key: String, amount: int = 1) -> void:
night_events[key] = int(night_events.get(key, 0)) + amount
## Pays a cost from the pouch and shed (ResourceStore.pay) and counts what was spent. Every
## purchase (building, repairs, patching, upgrades) goes through here.
func pay(cost: Dictionary) -> bool:
if not resources.pay(cost):
## Pays a cost from the payer's pouch (its avatar slot; 0 solo) and the shed (ResourceStore.pay)
## and counts what was spent. Every purchase (building, repairs, patching, upgrades) goes through
## here.
func pay(cost: Dictionary, slot: int = 0) -> bool:
if not resources.pay(cost, slot):
return false
for m in cost:
if int(cost[m]) > 0:

View file

@ -31,7 +31,8 @@ extends Node3D
## In co-op each scarecrow has its own Interactions. The partner's, on the host, reads its
## RemoteControls (remote), asks the partner's game to open its own upgrade menu
## (workbench_requested / shed_requested), and leaves the gather labels to the local player's
## (show_labels).
## (show_labels). Each one gathers into, deposits, and pays from its own scarecrow's pouch
## (kit.slot, ResourceStore): a partner standing in the shed banks only their own pouch.
signal gathered(material: String, amount: int, node: GatherNode)
signal deposited(moved: Dictionary)
@ -179,8 +180,8 @@ func step(dt: float) -> void:
if shed_panel != null and shed_panel.is_open:
_step_menu(shed_panel, shed_counter, p, pressed)
return
if _shed != null and _shed.contains(player.global_position) and campaign.state.resources.pouch_total() > 0:
var moved := campaign.state.resources.deposit()
if _shed != null and _shed.contains(player.global_position) and campaign.state.resources.pouch_total(kit.slot) > 0:
var moved := campaign.state.resources.deposit(kit.slot)
deposited.emit(moved)
message.emit("Stored %s in the shed" % ResourceStore.describe(moved), Color(0.85, 0.95, 1.0))
if repairing >= 0:
@ -192,11 +193,11 @@ func step(dt: float) -> void:
var id := repairing
var cost := structures.repair_cost(id)
cancel()
if structures.repair(id):
if structures.repair(id, kit.slot):
message.emit("Repaired (%s)" % ResourceStore.describe(cost), Color(0.6, 1.0, 0.55))
return
if upgrading >= 0:
if not held or not campaign.is_daytime() or structures.upgrade_blocker(upgrading) != "":
if not held or not campaign.is_daytime() or structures.upgrade_blocker(upgrading, kit.slot) != "":
cancel()
return
upgrade_elapsed += dt
@ -204,7 +205,7 @@ func step(dt: float) -> void:
var id := upgrading
var cost := structures.upgrade_cost(id)
cancel()
if structures.upgrade(id):
if structures.upgrade(id, kit.slot):
message.emit("Upgraded to L%d (%s)" % [structures.level_of(id), ResourceStore.describe(cost)], Color(0.6, 1.0, 0.55))
return
if gathering != null:
@ -223,13 +224,13 @@ func step(dt: float) -> void:
focus = null
if held and not kit.patching:
var cost := structures.repair_cost(repair_target)
if campaign.state.resources.can_afford(cost):
if campaign.state.resources.can_afford(cost, kit.slot):
repairing = repair_target
repair_elapsed = 0.0
player.start_channel(&"Hammering")
elif not _denied:
_denied = true
message.emit("Not enough to repair: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost)), Color(1.0, 0.8, 0.5))
message.emit("Not enough to repair: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost, kit.slot)), Color(1.0, 0.8, 0.5))
return
upgrade_target = structures.upgradeable_near(p, REPAIR_REACH) if structures != null else -1
if upgrade_target >= 0:
@ -240,7 +241,7 @@ func step(dt: float) -> void:
_denied = true
message.emit("Upgrading is for daytime", Color(1.0, 0.8, 0.5))
else:
var why := structures.upgrade_blocker(upgrade_target)
var why := structures.upgrade_blocker(upgrade_target, kit.slot)
if why == "":
upgrading = upgrade_target
upgrade_elapsed = 0.0
@ -293,7 +294,7 @@ func _blocker(n: GatherNode) -> String:
return "Gathering is for daytime"
if charges(n) <= 0:
return "Nothing left here; it grows back overnight"
if campaign.state.resources.pouch_room() < n.yield_amount:
if campaign.state.resources.pouch_room(kit.slot) < n.yield_amount:
return "Pouch full: drop it off at the supply shed"
return ""
@ -303,7 +304,7 @@ func _blocker(n: GatherNode) -> String:
func _upgrade_prompt(id: int) -> String:
if not campaign.is_daytime():
return "Upgrading is for daytime"
var why := structures.upgrade_blocker(id)
var why := structures.upgrade_blocker(id, kit.slot)
if why == "":
return "[E / X] Upgrade to L%d (%s)" % [structures.level_of(id) + 1, ResourceStore.describe(structures.upgrade_cost(id))]
return why
@ -336,7 +337,7 @@ func regen_overnight() -> void:
func _finish_gather() -> void:
var n := gathering
var s := campaign.state
var added := s.resources.add_to_pouch(n.material, n.yield_amount)
var added := s.resources.add_to_pouch(n.material, n.yield_amount, kit.slot)
var left := charges(n) - 1
s.gather_charges[String(n.name)] = left
cancel()

View file

@ -1,9 +1,11 @@
class_name ResourceHud
extends Control
## Top-right materials readout: what the supply shed holds, and what the scarecrow carries in
## its pouch (with its capacity). A line flashes when its numbers change.
## Top-right materials readout: what the supply shed holds, and what this machine's scarecrow
## carries in its own pouch (with its capacity). A line flashes when its numbers change.
var campaign: CampaignController
## The avatar slot whose pouch is shown (FarmSim.set_local: the partner's machine shows P2's).
var slot: int = 0
## Set by FarmSim: shows how many structures stand.
var structures: StructureSystem
@ -34,7 +36,8 @@ func _process(delta: float) -> void:
return
var r := campaign.state.resources
var shed := "Shed %s" % _amounts(r.shed)
var pouch := "Pouch %d/%d %s" % [r.pouch_total(), r.pouch_capacity, _amounts(r.pouch) if r.pouch_total() > 0 else "empty"]
var total := r.pouch_total(slot)
var pouch := "Pouch %d/%d %s" % [total, r.pouch_capacity, _amounts(r.pouch_of(slot)) if total > 0 else "empty"]
if shed != _last_shed:
_last_shed = shed
_shed.text = shed

View file

@ -1,24 +1,48 @@
class_name ResourceStore
extends RefCounted
## The farm's construction materials (wood, scrap, straw, alien goop): stock stored in the supply
## shed, and what the scarecrow carries in its pouch (pouch_capacity units across all materials).
## The pouch empties into the shed when the scarecrow walks in. Costs are paid all-or-nothing,
## from the pouch first and then the shed. Only shed stock can be stolen.
## shed, and what each scarecrow carries in its own pouch (pouch_capacity units across all
## materials; one capacity shared by every pouch). A pouch empties into the shed when its
## scarecrow walks in. Costs are paid all-or-nothing, from the payer's pouch first and then the
## shed. Only shed stock can be stolen.
## Pouches go by avatar slot (Avatar.slot): 0 is player 1 (the solo player, or the host in
## co-op), 1 is player 2 (the partner). Every pouch method takes the slot and defaults to 0, so
## solo callers never name one; `pouch` is slot 0's.
## Methods that sum across MATERIALS read with get(m, 0): a shed/pouch dict built or replaced
## elsewhere (tests, old saves) without every material present is treated as 0 for the rest,
## rather than erroring.
const MATERIALS: Array[String] = ["wood", "scrap", "straw", "alien_goop"]
## How many pouches there are (one per avatar slot), and their keys in to_dict(), by slot.
const SLOTS := 2
const POUCH_KEYS: Array[String] = ["pouch", "partner_pouch"]
var shed := {"wood": 0, "scrap": 0, "straw": 0, "alien_goop": 0}
var pouch := {"wood": 0, "scrap": 0, "straw": 0, "alien_goop": 0}
## Each scarecrow's pouch, by avatar slot.
var pouches: Array[Dictionary] = [
{"wood": 0, "scrap": 0, "straw": 0, "alien_goop": 0},
{"wood": 0, "scrap": 0, "straw": 0, "alien_goop": 0},
]
## Player 1's pouch (slot 0): the solo player's, or the host's.
var pouch: Dictionary:
get:
return pouches[0]
set(value):
pouches[0] = value
## Shared by every pouch: one Bigger pouch upgrade grows them all.
var pouch_capacity: int = 15
func pouch_total() -> int:
## The pouch of an avatar slot (an out-of-range slot reads as the nearest valid one).
func pouch_of(slot: int = 0) -> Dictionary:
return pouches[clampi(slot, 0, SLOTS - 1)]
func pouch_total(slot: int = 0) -> int:
var p := pouch_of(slot)
var n := 0
for m in MATERIALS:
n += int(pouch.get(m, 0))
n += int(p.get(m, 0))
return n
@ -40,61 +64,71 @@ func most_stocked() -> String:
return best
func pouch_room() -> int:
return maxi(pouch_capacity - pouch_total(), 0)
func pouch_room(slot: int = 0) -> int:
return maxi(pouch_capacity - pouch_total(slot), 0)
## Puts up to amount into the pouch, as much as fits. Returns how much went in.
func add_to_pouch(material: String, amount: int) -> int:
var added := mini(maxi(amount, 0), pouch_room())
pouch[material] = int(pouch.get(material, 0)) + added
## Puts up to amount into a slot's pouch, as much as fits. Returns how much went in.
func add_to_pouch(material: String, amount: int, slot: int = 0) -> int:
var p := pouch_of(slot)
var added := mini(maxi(amount, 0), pouch_room(slot))
p[material] = int(p.get(material, 0)) + added
return added
## Moves the whole pouch into the shed. Returns what moved (material -> amount, only non-zero).
func deposit() -> Dictionary:
## Moves a slot's whole pouch into the shed. Returns what moved (material -> amount, only
## non-zero).
func deposit(slot: int = 0) -> Dictionary:
var p := pouch_of(slot)
var moved := {}
for m in MATERIALS:
var n := int(pouch.get(m, 0))
var n := int(p.get(m, 0))
if n > 0:
shed[m] = int(shed.get(m, 0)) + n
pouch[m] = 0
p[m] = 0
moved[m] = n
return moved
func available(material: String) -> int:
return int(shed.get(material, 0)) + int(pouch.get(material, 0))
## What a slot's scarecrow can spend of a material: the shed's stock plus its own pouch.
func available(material: String, slot: int = 0) -> int:
return int(shed.get(material, 0)) + int(pouch_of(slot).get(material, 0))
## What a cost still lacks (material -> amount short; empty when affordable).
func missing(cost: Dictionary) -> Dictionary:
## What a cost still lacks for a slot's scarecrow (material -> amount short; empty when
## affordable).
func missing(cost: Dictionary, slot: int = 0) -> Dictionary:
var short := {}
for m in cost:
var need := int(cost[m]) - available(String(m))
var need := int(cost[m]) - available(String(m), slot)
if need > 0:
short[m] = need
return short
func can_afford(cost: Dictionary) -> bool:
return missing(cost).is_empty()
func can_afford(cost: Dictionary, slot: int = 0) -> bool:
return missing(cost, slot).is_empty()
## Pays a cost from the pouch first, then the shed. Pays nothing and returns false if short.
func pay(cost: Dictionary) -> bool:
if not can_afford(cost):
## Pays a cost from a slot's pouch first, then the shed (never another scarecrow's pouch). Pays
## nothing and returns false if short.
func pay(cost: Dictionary, slot: int = 0) -> bool:
if not can_afford(cost, slot):
return false
var p := pouch_of(slot)
for m in cost:
var need := int(cost[m])
var from_pouch := mini(need, int(pouch[m]))
pouch[m] = int(pouch[m]) - from_pouch
shed[m] = int(shed[m]) - (need - from_pouch)
var from_pouch := mini(need, int(p.get(m, 0)))
p[m] = int(p.get(m, 0)) - from_pouch
shed[m] = int(shed.get(m, 0)) - (need - from_pouch)
return true
func to_dict() -> Dictionary:
return {"shed": _filled(shed), "pouch": _filled(pouch), "pouch_capacity": pouch_capacity}
var d := {"shed": _filled(shed), "pouch_capacity": pouch_capacity}
for slot in SLOTS:
d[POUCH_KEYS[slot]] = _filled(pouches[slot])
return d
## A copy with every material present (one missing from shed/pouch, e.g. because it was replaced
@ -108,23 +142,29 @@ static func _filled(d: Dictionary) -> Dictionary:
return out
## Returns null for unknown materials, negative amounts, or an overfull pouch. A material missing
## from shed/pouch (an older save from before it existed, e.g. Alien Goop) is treated as 0, not
## rejected, so new materials stay load-compatible with old saves.
## Returns null for a missing part (the shed, either pouch, the capacity), unknown materials,
## negative amounts, or an overfull pouch. A material missing from the shed or a pouch (an older
## save from before it existed, e.g. Alien Goop) is treated as 0, not rejected, so new materials
## stay load-compatible with old saves.
static func from_dict(d: Variant) -> ResourceStore:
if not d is Dictionary:
return null
var dd := d as Dictionary
if not (dd.get("shed") is Dictionary and dd.get("pouch") is Dictionary and dd.has("pouch_capacity")):
if not (dd.get("shed") is Dictionary and dd.has("pouch_capacity")):
return null
for key in POUCH_KEYS:
if not dd.get(key) is Dictionary:
return null
var r := ResourceStore.new()
r.pouch_capacity = int(dd["pouch_capacity"])
for part in ["shed", "pouch"]:
var parts: Array[String] = ["shed"]
parts.append_array(POUCH_KEYS)
for part in parts:
var src: Dictionary = dd[part]
for key in src:
if not MATERIALS.has(String(key)):
return null # unknown material
var into: Dictionary = r.shed if part == "shed" else r.pouch
var into: Dictionary = r.shed if part == "shed" else r.pouches[POUCH_KEYS.find(part)]
for m in MATERIALS:
if src.has(m):
if int(src[m]) < 0:
@ -132,7 +172,12 @@ static func from_dict(d: Variant) -> ResourceStore:
into[m] = int(src[m])
else:
into[m] = 0
return r if r.pouch_capacity >= 1 and r.pouch_total() <= r.pouch_capacity else null
if r.pouch_capacity < 1:
return null
for slot in SLOTS:
if r.pouch_total(slot) > r.pouch_capacity:
return null
return r
## "6 wood, 2 straw" for a material -> amount dictionary (in MATERIALS order).

View file

@ -128,7 +128,11 @@ func refresh() -> void:
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.")
var r := s.resources
lines.append("In the shed: %s. In the pouch: %s." % [_or_none(ResourceStore.describe(r.shed)), _or_none(ResourceStore.describe(r.pouch))])
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)),
Avatar.NAMES[0], _or_none(ResourceStore.describe(r.pouch_of(0))), Avatar.NAMES[1], _or_none(ResourceStore.describe(r.pouch_of(1)))])
else:
lines.append("In the shed: %s. In the pouch: %s." % [_or_none(ResourceStore.describe(r.shed)), _or_none(ResourceStore.describe(r.pouch))])
var plan := waves.tonight() if waves != null else null
if plan != null and plan.title != "":
if structures != null and structures.has_workbench():

View file

@ -107,6 +107,16 @@ static func migrate(d: Dictionary) -> Dictionary:
if entry is Dictionary and not (entry as Dictionary).has("level"):
entry["level"] = 1
out["version"] = 6
6:
# Version 7 gives each scarecrow its own pouch (#16): the old shared one becomes player
# 1's (resources.pouch, unchanged), and player 2's starts empty.
var res: Variant = out.get("resources")
if res is Dictionary and not (res as Dictionary).has("partner_pouch"):
var empty := {}
for m in ResourceStore.MATERIALS:
empty[m] = 0
res["partner_pouch"] = empty
out["version"] = 7
_:
return {}
return out

View file

@ -16,8 +16,8 @@ extends Node3D
## into Game Over on the same tick (in co-op only once both have fallen: until then it's out
## until the morning). Every new morning, also after a retry, revives it with fear ready.
## In co-op there are two kits: slot 0 (player 1) uses FarmState.scarecrow_hp, slot 1 (player 2)
## partner_hp. A kit whose remote is set (the partner's, on the host) reads RemoteControls
## instead of the local input.
## partner_hp, and each patches with straw from its own pouch (and the shed). A kit whose remote
## is set (the partner's, on the host) reads RemoteControls instead of the local input.
signal damaged(hp: int)
signal fear_used(position: Vector3, scared: int)
@ -145,10 +145,10 @@ func step_patch(dt: float, held: bool) -> void:
if not patching:
if hp() >= max_hp() or (interactions != null and interactions.channeling()):
return
if not s.resources.can_afford(cost):
if not s.resources.can_afford(cost, slot):
if not _patch_denied: # once per press
_patch_denied = true
patch_denied.emit(s.resources.missing(cost))
patch_denied.emit(s.resources.missing(cost, slot))
return
patching = true
patch_elapsed = 0.0
@ -156,7 +156,7 @@ func step_patch(dt: float, held: bool) -> void:
patch_elapsed += dt
if patch_elapsed >= config.patch_time:
_end_patch()
if s.pay(cost):
if s.pay(cost, slot):
_set_hp(hp() + config.patch_heal)
s.record_event("patches")
patched.emit(hp())

View file

@ -197,8 +197,9 @@ static func corners(fp: Dictionary, shrink_long: float = 0.0, shrink_wide: float
return pts
## Why a structure can't go here ("" if it can). Space first, then daytime, then the cost.
func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) -> String:
## Why a structure can't go here ("" if it can). Space first, then daytime, then the cost (from
## the builder's pouch, its avatar slot, and the shed).
func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2, slot: int = 0) -> String:
var fp := footprint(type, x, z, rot)
var outline := corners(fp)
var inside := zones.playable.grow(-0.3)
@ -232,15 +233,16 @@ func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) ->
if not campaign.is_daytime():
return "Building is for daytime"
var cost: Dictionary = config.costs.get(type, {})
if not campaign.state.resources.can_afford(cost):
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost))
if not campaign.state.resources.can_afford(cost, slot):
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost, slot))
return ""
## Builds after validate() passed: pays, records, shows, and updates navigation. Returns the id.
func place(type: String, x: float, z: float, rot: int) -> int:
## Builds after validate() passed: pays (from the builder's pouch, its avatar slot, and the shed),
## records, shows, and updates navigation. Returns the id.
func place(type: String, x: float, z: float, rot: int, slot: int = 0) -> int:
var s := campaign.state
if not s.pay(config.costs.get(type, {})):
if not s.pay(config.costs.get(type, {}), slot):
return -1
var id := s.next_structure_id
s.next_structure_id += 1
@ -365,10 +367,11 @@ func repair_cost(id: int) -> Dictionary:
return out
## Pays and repairs fully. Returns false if there was nothing to repair or it couldn't be paid.
func repair(id: int) -> bool:
## Pays (from the repairer's pouch, its avatar slot, and the shed) and repairs fully. Returns
## false if there was nothing to repair or it couldn't be paid.
func repair(id: int, slot: int = 0) -> bool:
var cost := repair_cost(id)
if cost.is_empty() or not campaign.state.pay(cost):
if cost.is_empty() or not campaign.state.pay(cost, slot):
return false
var e := campaign.state.structure(id)
e["hp"] = max_hp(e["type"])
@ -393,8 +396,9 @@ func upgrade_cost(id: int) -> Dictionary:
## Why id can't be upgraded right now ("" if it can): levelable, undamaged (repair takes
## priority), under MAX_LEVEL, a bigger tar patch footprint clear of neighbors and the world, and
## the cost affordable. Doesn't check the time of day (Interactions, like the build-mode rules).
func upgrade_blocker(id: int) -> String:
## the cost affordable (from the upgrader's pouch, its avatar slot, and the shed). Doesn't check
## the time of day (Interactions, like the build-mode rules).
func upgrade_blocker(id: int, slot: int = 0) -> String:
var e := campaign.state.structure(id)
if e.is_empty() or not is_levelable(e["type"]):
return "Can't be upgraded"
@ -415,17 +419,17 @@ func upgrade_blocker(id: int) -> String:
return "Not enough room to upgrade"
if _world_blocked(fp):
return "Not enough room to upgrade"
if not campaign.state.resources.can_afford(cost):
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost))
if not campaign.state.resources.can_afford(cost, slot):
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost, slot))
return ""
## Pays and levels a structure up by one (see upgrade_blocker). Returns false if it couldn't be.
func upgrade(id: int) -> bool:
if upgrade_blocker(id) != "":
func upgrade(id: int, slot: int = 0) -> bool:
if upgrade_blocker(id, slot) != "":
return false
var cost := upgrade_cost(id)
if not campaign.state.pay(cost):
if not campaign.state.pay(cost, slot):
return false
var e := campaign.state.structure(id)
e["level"] = int(e.get("level", 1)) + 1

View file

@ -119,7 +119,7 @@ func _wanted(id: String) -> bool:
"gather":
return day and done.has("move")
"store":
return day and c.state.resources.pouch_total() > 0
return day and c.state.resources.pouch_total(sim.local_avatar.slot) > 0
"build":
return day and (done.has("store") or c.state.phase_time_left < c.phase_length(CampaignController.Phase.DAY) * 0.5
or phase == CampaignController.Phase.DUSK)

View file

@ -20,6 +20,9 @@ var is_open := false
var shop := "workbench"
## Co-op partner: ask the host to buy (upgrade id); the result comes back as a message.
var buy_request: Callable
## The avatar slot of this machine's scarecrow (FarmSim.set_local): what's affordable is its own
## pouch plus the shed.
var slot: int = 0
var _rows := {} # upgrade id -> Button
var _title: Label
@ -115,7 +118,7 @@ func refresh() -> void:
for id: String in _rows:
var u: Dictionary = cfg.upgrades[id]
var b := _rows[id] as Button
var why := Upgrades.blocker(campaign, id)
var why := Upgrades.blocker(campaign, id, slot)
if Upgrades.owned(s, id):
done += 1
if not Upgrades.revealed(s, cfg, id):
@ -137,7 +140,7 @@ func _buy(id: String) -> void:
buy_request.call(id)
return
var was := Upgrades.owned(campaign.state, id)
var text := Upgrades.buy(campaign, id, structures)
var text := Upgrades.buy(campaign, id, structures, slot)
if not was and Upgrades.owned(campaign.state, id):
bought.emit(id)
message.emit(text, Color(0.85, 0.75, 1.0) if text.contains("done:") else Color(1.0, 0.8, 0.5))

View file

@ -9,7 +9,8 @@ extends RefCounted
## of reading GameConfig directly: the corn shooter's fire rate and shot damage, fear's radius and
## cooldown, fences' and gates' health (barrier_hp), the automated defense's range, and the traps'
## slow time. Straw stuffing raises the scarecrow's max health (FarmState) when bought, and the
## Bigger pouch upgrade raises pouch_capacity (ResourceStore) the same way. Sprint, the corn
## Bigger pouch upgrade raises pouch_capacity (ResourceStore, shared: every scarecrow's pouch
## grows) the same way. The buyer pays from their own pouch and the shed (slot). Sprint, the corn
## shooter, and pumpkin bombs change no stat: owning them unlocks sprinting (PlayerCharacter) and
## the two weapons (ScarecrowCombat). Rapid fire and heavy seeds (bought at the workbench) need
## the corn shooter (bought at the shed) first ("requires" crosses shops freely).
@ -73,8 +74,9 @@ static func value(cfg: GameConfig, state: FarmState, stat: String) -> float:
return v
## Why an upgrade can't be bought right now ("" if it can).
static func blocker(campaign: CampaignController, id: String) -> String:
## Why an upgrade can't be bought right now ("" if it can), by the scarecrow in this avatar slot
## (its pouch and the shed pay).
static func blocker(campaign: CampaignController, id: String, slot: int = 0) -> String:
var cfg := campaign.config
var s := campaign.state
if not cfg.upgrades.has(id):
@ -88,21 +90,22 @@ static func blocker(campaign: CampaignController, id: String) -> String:
return "Needs the %s first" % String(cfg.upgrades.get(needs, {}).get("name", needs)).to_lower()
if not campaign.is_daytime():
return "The work area is for daytime"
if not s.resources.can_afford(cost(cfg, id)):
return "Need %s more" % ResourceStore.describe(s.resources.missing(cost(cfg, id)))
if not s.resources.can_afford(cost(cfg, id), slot):
return "Need %s more" % ResourceStore.describe(s.resources.missing(cost(cfg, id), slot))
return ""
## Buys an upgrade if it can be bought. Returns the message for the player.
static func buy(campaign: CampaignController, id: String, structures: StructureSystem = null) -> String:
## Buys an upgrade if it can be bought, paid by the scarecrow in this avatar slot (its pouch,
## then the shed). Returns the message for the player.
static func buy(campaign: CampaignController, id: String, structures: StructureSystem = null, slot: int = 0) -> String:
var cfg := campaign.config
var s := campaign.state
var u: Dictionary = cfg.upgrades.get(id, {})
var why := blocker(campaign, id)
var why := blocker(campaign, id, slot)
if why != "":
return "%s: %s" % [u.get("name", id), why.to_lower() if why != "Done" else "already done"]
var barrier_before := value(cfg, s, "barrier_hp")
s.pay(cost(cfg, id))
s.pay(cost(cfg, id), slot)
s.upgrades[id] = 1
s.record_event("upgrades_bought")
match String(u.get("stat", "")):
@ -117,6 +120,6 @@ static func buy(campaign: CampaignController, id: String, structures: StructureS
for e in s.structures:
if e["type"] == "fence" or e["type"] == "gate":
e["hp"] = mini(roundi(int(e["hp"]) * k), structures.max_hp(e["type"]) if structures != null else 1 << 20)
"pouch_capacity": # the live value lives in ResourceStore, not read from cfg each time
"pouch_capacity": # the live value lives in ResourceStore (one for every pouch), not read from cfg each time
s.resources.pouch_capacity += int(u.get("add", 0))
return "%s done: %s" % [u.get("name", id), String(u.get("text", "")).to_lower()]