Merge task #10: per-instance Turret/Tar Patch leveling (L1-L3)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-05 15:52:03 -04:00
commit 4b78004333
8 changed files with 472 additions and 35 deletions

View file

@ -42,8 +42,10 @@ signal ended(reason: String)
## Partner: the first full state arrived; the game is on.
signal welcomed
## The wire format: both machines must speak the same one (hello and welcome carry it).
const PROTOCOL := 2
## 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
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.
@ -446,8 +448,11 @@ static func _enemy_bytes(es: EnemySystem, d: int) -> PackedByteArray:
## A scarecrow in a snapshot: slot, position, facing, speed, alive and patching, health, its
## timers (invulnerable, fear, bomb recharge, patch, gather, repair), the weapon, the channel
## clip and what it is focused on and gathering (names), and the repair's target and progress.
## timers (invulnerable, fear, bomb recharge, patch, gather, repair, structure level-up), the
## weapon, the channel clip and what it is focused on and gathering (names), and the repair's and
## the level-up's target and progress (#10: a structure upgrade is driven the same way as a
## repair -- entirely host-side off the partner's held interact button, nothing in "req" -- so
## this is the only wire change it needs).
func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void:
var it := a.interactions
var k := a.kit
@ -457,7 +462,7 @@ func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void:
b.put_u8(clampi(roundi(a.body.move_strength() * 100.0), 0, 255))
b.put_u8((1 if k.alive else 0) | (2 if k.patching else 0))
b.put_u8(clampi(k.hp(), 0, 255))
for t: float in [k.invulnerable_left, k.fear_left, a.combat.bomb_left, k.patch_elapsed, it.gather_elapsed, it.repair_elapsed]:
for t: float in [k.invulnerable_left, k.fear_left, a.combat.bomb_left, k.patch_elapsed, it.gather_elapsed, it.repair_elapsed, it.upgrade_elapsed]:
CoopLink.put_time(b, t)
b.put_u8(int(a.combat.weapon))
CoopLink.put_text(b, String(a.body.channel_clip) if a.body.rooted else "")
@ -465,6 +470,8 @@ func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void:
CoopLink.put_text(b, String(it.gathering.name) if it.gathering != null else "")
b.put_32(it.repair_target)
b.put_32(it.repairing)
b.put_32(it.upgrade_target)
b.put_32(it.upgrading)
func _on_message(kind: String, data: Variant) -> void:
@ -730,7 +737,7 @@ func _read_avatar(b: StreamPeerBuffer) -> Dictionary:
var flags := b.get_u8()
rec["a"] = (flags & 1) != 0
rec["hp"] = b.get_u8()
for key: String in ["inv", "fl", "bl", "pt", "ge", "re"]:
for key: String in ["inv", "fl", "bl", "pt", "ge", "re", "ue"]:
rec[key] = CoopLink.get_time(b)
if (flags & 2) == 0:
rec["pt"] = -1.0 # not patching
@ -740,6 +747,8 @@ func _read_avatar(b: StreamPeerBuffer) -> Dictionary:
rec["ga"] = CoopLink.get_text(b)
rec["rt"] = b.get_32()
rec["rp"] = b.get_32()
rec["ut"] = b.get_32()
rec["up"] = b.get_32()
return rec
@ -783,6 +792,9 @@ func _apply_avatar(a: Avatar, rec: Dictionary) -> void:
it.repair_target = int(rec["rt"])
it.repairing = int(rec["rp"])
it.repair_elapsed = float(rec["re"])
it.upgrade_target = int(rec["ut"])
it.upgrading = int(rec["up"])
it.upgrade_elapsed = float(rec["ue"])
func _gather_node(node_name: String) -> Node3D:

View file

@ -8,14 +8,14 @@ extends RefCounted
## pouch live in resources). Gather points below full, bought upgrades, and the built structures
## are kept too.
const VERSION := 5
const VERSION := 6
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",
"shed_raided", "resources", "gather_charges", "upgrades", "structures", "next_structure_id",
"night_events", "night_log", "coop", "partner_max_hp", "partner_hp",
]
const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp"]
const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp", "level"]
## Events counted from the morning to the end of the dawn grace, copied into the night's log
## entry when it closes. Theft: supply events count material units, the others crop units or
## animals. Then enemies killed by type and those that escaped with loot; the scarecrow's damage
@ -106,7 +106,8 @@ var gather_charges: Dictionary = {}
## Bought upgrades (id -> level).
var upgrades: Dictionary = {}
## Built structures: {"id", "type", "x", "z" (world position, on the 0.5 m build grid), "rot"
## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow)}.
## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow), "level"
## (1-3; account-wide upgrades are tracked separately, above -- this is per placed instance, #10)}.
var structures: Array[Dictionary] = []
var next_structure_id: int = 1
@ -131,7 +132,7 @@ static func create(cfg: GameConfig) -> FarmState:
for e in cfg.start_structures:
var t := String(e["type"])
s.structures.append({"id": s.next_structure_id, "type": t, "x": float(e["x"]), "z": float(e["z"]),
"rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t)})
"rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t), "level": 1})
s.next_structure_id += 1
return s
@ -393,8 +394,9 @@ static func from_dict(d: Dictionary) -> FarmState:
e["z"] = float(raw["z"])
e["rot"] = int(raw["rot"])
e["hp"] = int(raw["hp"])
e["level"] = int(raw["level"])
if e["id"] < 1 or e["id"] >= s.next_structure_id or ids.has(e["id"]) or e["type"] == "" \
or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0:
or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0 or e["level"] < 1 or e["level"] > 3:
return null
ids[e["id"]] = true
s.structures.append(e)

View file

@ -207,6 +207,28 @@ extends Resource
## Cells finalized per tick while flow fields rebuild after a structure change.
@export_range(100, 100000) var flow_slice_cells: int = 2000
## Per-instance leveling (StructureSystem.LEVELABLE: automated_defense, slowing_trap; L1-L3), not
## account-wide like the workbench upgrades above. Holding interact at a specific placed structure
## (by day; it must be undamaged first) pays structure_level_costs[type][level - 1] to take it from
## level to level + 1 (index 0: L1->L2, index 1: L2->L3).
@export var structure_level_costs: Dictionary = {
"automated_defense": [{"scrap": 10, "wood": 4, "straw": 2}, {"scrap": 16, "wood": 6, "straw": 4}],
"slowing_trap": [{"scrap": 5, "wood": 2}, {"scrap": 8, "wood": 4}],
}
## Turret L2 fires this many times as often (mirrors the Rapid Fire upgrade's live multiplier,
## 3.0 in game_config.tres); L3 keeps the same rate.
@export var turret_level_fire_mult: float = 3.0
## Turret L3 fires this many shots at once in a fan around the aim direction, turret_l3_spread_deg
## apart (a triangle spread: the outer two off by the full spread from the center shot).
@export_range(1, 8) var turret_l3_projectiles: int = 3
@export var turret_l3_spread_deg: float = 10.0
## A tar patch's footprint (trigger area) and visual grow by this multiple of its L1 size, per
## level (index 0 = L1, so always 1.0).
@export var trap_level_size_mult: Array[float] = [1.0, 2.0, 3.0]
## Holding interact for structure_upgrade_time levels up a structure, paying structure_level_costs
## at the end (by day only; see Interactions).
@export var structure_upgrade_time: float = 2.0
@export_group("Combat")
## Height of the gun muzzle, the bullets, and enemy hit proxies (shots fly horizontally). It
## clears the sunflowers (1.67 m) and the pen fence (1.69 m), so thieves in the field stay

View file

@ -17,6 +17,12 @@ extends Node3D
## * Repair: a damaged structure within REPAIR_REACH comes first. Hold interact for
## repair_time (any phase) to repair it fully for StructureSystem.repair_cost (paid at the
## end); it is refused, once per press, without the materials.
## * Upgrade (#10): a levelable structure (turret, tar patch) within REPAIR_REACH, undamaged
## (repair takes priority while it isn't), comes next. Hold interact by day for
## structure_upgrade_time to level it up one, for StructureSystem.upgrade_cost (paid at the
## end); refused, once per press, without the materials, room (a bigger tar patch may not fit),
## or at Max level. Night-gated like the workbench, unlike repair, since it's a build-mode-style
## decision, not an emergency fix.
## * Deposit: walking into the Supply Shed zone empties the pouch into the shed (no interact,
## and not gated by the shed counter's reach or the shed shop being open).
## * Overnight (the end of the dawn grace) every used point regains regen_per_night charges.
@ -61,6 +67,10 @@ var gather_elapsed: float = 0.0
var repair_target: int = -1
var repairing: int = -1
var repair_elapsed: float = 0.0
## Levelable structure in reach, undamaged (-1 = none), and the one being upgraded (#10).
var upgrade_target: int = -1
var upgrading: int = -1
var upgrade_elapsed: float = 0.0
var _shed: FarmZone
var _interact_requested := false
@ -68,6 +78,7 @@ var _interact_was_held := false
var _denied := false
var _popups: Array[Label3D] = []
var _repair_label: Label3D
var _upgrade_label: Label3D
var _popup_left := PackedFloat32Array()
@ -99,6 +110,17 @@ func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerChar
_repair_label.top_level = true
_repair_label.visible = false
add_child(_repair_label)
_upgrade_label = Label3D.new()
_upgrade_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_upgrade_label.no_depth_test = true
_upgrade_label.shaded = false
_upgrade_label.font_size = 40
_upgrade_label.outline_size = 10
_upgrade_label.pixel_size = 0.0075
_upgrade_label.modulate = Color(0.75, 0.95, 1.0)
_upgrade_label.top_level = true
_upgrade_label.visible = false
add_child(_upgrade_label)
_popup_left.resize(POPUPS)
for i in POPUPS:
var l := Label3D.new()
@ -120,7 +142,7 @@ func charges(n: GatherNode) -> int:
func channeling() -> bool:
return gathering != null or repairing >= 0
return gathering != null or repairing >= 0 or upgrading >= 0
func can_shoot() -> bool:
@ -145,6 +167,7 @@ func step(dt: float) -> void:
shed_panel.close()
cancel()
repair_target = -1
upgrade_target = -1
focus = null
return
var p := Vector2(player.global_position.x, player.global_position.z)
@ -170,6 +193,18 @@ func step(dt: float) -> void:
if structures.repair(id):
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) != "":
cancel()
return
upgrade_elapsed += dt
if upgrade_elapsed >= config.structure_upgrade_time:
var id := upgrading
var cost := structures.upgrade_cost(id)
cancel()
if structures.upgrade(id):
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:
if not held or _blocker(gathering) != "":
cancel()
@ -194,6 +229,24 @@ func step(dt: float) -> void:
_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))
return
upgrade_target = structures.upgradeable_near(p, REPAIR_REACH) if structures != null else -1
if upgrade_target >= 0:
focus = null
if held and not kit.patching:
if not campaign.is_daytime():
if not _denied:
_denied = true
message.emit("Upgrading is for daytime", Color(1.0, 0.8, 0.5))
else:
var why := structures.upgrade_blocker(upgrade_target)
if why == "":
upgrading = upgrade_target
upgrade_elapsed = 0.0
player.start_channel(&"Hammering")
elif not _denied:
_denied = true
message.emit(why, Color(1.0, 0.8, 0.5))
return
focus = _nearest(p)
if focus is GatherNode and held and not kit.patching:
var why := _blocker(focus)
@ -241,12 +294,25 @@ func _blocker(n: GatherNode) -> String:
return ""
## The upgrade prompt for a levelable structure in reach: what it costs, "Max level", why it
## can't right now, or that upgrading (unlike repair) is for daytime.
func _upgrade_prompt(id: int) -> String:
if not campaign.is_daytime():
return "Upgrading is for daytime"
var why := structures.upgrade_blocker(id)
if why == "":
return "[E / X] Upgrade to L%d (%s)" % [structures.level_of(id) + 1, ResourceStore.describe(structures.upgrade_cost(id))]
return why
func cancel() -> void:
if gathering != null or repairing >= 0:
if gathering != null or repairing >= 0 or upgrading >= 0:
gathering = null
gather_elapsed = 0.0
repairing = -1
repair_elapsed = 0.0
upgrading = -1
upgrade_elapsed = 0.0
player.stop_channel()
@ -337,6 +403,14 @@ func _process(delta: float) -> void:
var cost := structures.repair_cost(shown)
_repair_label.text = "%s %d/%d\n%s" % [StructureSystem.NAMES[e["type"]], int(e["hp"]), structures.max_hp(e["type"]),
"Repairing..." if repairing >= 0 else "[E / X] Repair (%s)" % ResourceStore.describe(cost)]
var ushown := (upgrading if upgrading >= 0 else upgrade_target) if show_labels else -1
_upgrade_label.visible = ushown >= 0
if ushown >= 0:
var e := campaign.state.structure(ushown)
if not e.is_empty():
_upgrade_label.global_position = Vector3(e["x"], 3.3, e["z"])
_upgrade_label.text = "%s L%d\n%s" % [StructureSystem.NAMES[e["type"]], int(e.get("level", 1)),
"Upgrading..." if upgrading >= 0 else _upgrade_prompt(ushown)]
for i in POPUPS:
if _popup_left[i] <= 0.0:
continue

View file

@ -101,6 +101,12 @@ static func migrate(d: Dictionary) -> Dictionary:
penned.append(id)
out["penned_animals"] = penned
out["version"] = 5
5:
# Version 6 adds per-instance structure leveling (#10): older structures are level 1.
for entry: Variant in out.get("structures", []):
if entry is Dictionary and not (entry as Dictionary).has("level"):
entry["level"] = 1
out["version"] = 6
_:
return {}
return out

View file

@ -5,8 +5,8 @@ extends Node3D
## fence 2 m segment that ground enemies can't walk through.
## gate a fence segment the scarecrow walks through (it swings open as the
## scarecrow nears; it has no collision for the scarecrow) but enemies can't.
## slowing_trap 1.5 m patch: a ground enemy stepping on it moves at trap_slow_factor speed
## for trap_slow_time, using up one of its trap_triggers. Doesn't block.
## slowing_trap 1.5 m patch (at L1): a ground enemy stepping on it moves at trap_slow_factor
## speed for trap_slow_time, using up one of its trap_triggers. Doesn't block.
## automated_defense 1 m post that shoots the nearest enemy within turret_range with a clear
## line, from the shared shot pool, every turret_fire_interval (leading the
## target). Flying enemies are hit too (Step 9); fences, gates, and traps
@ -16,13 +16,23 @@ extends Node3D
## bar, a red tint, and wobble on each hit; a broken one leaves debris and emits destroyed
## ("breach"). Positions snap to a 0.5 m grid, rotations to 45 degree steps (fences run 2 m along
## the grid, 1.5 x 1.5 m on the diagonal, so chains line up either way).
##
## Leveling (#10): a turret or a tar patch (LEVELABLE) can be upgraded independently, L1-L3, from
## L1 (Interactions, holding interact at that specific structure; it must be undamaged and the
## cost affordable -- see upgrade_blocker). A turret at L2 fires turret_level_fire_mult times as
## often (3x, the same live multiplier as the player's Rapid Fire upgrade); L3 keeps that rate but
## fires turret_l3_projectiles shots at once in a fan. A tar patch's footprint and visual grow by
## trap_level_size_mult[level - 1] (L2 double, L3 triple its L1 size); upgrading refuses with a
## reason if the bigger footprint would overlap another structure or the world.
signal layout_changed
signal built(id: int, type: String)
signal destroyed(id: int, type: String, position: Vector3)
## Damaged but still standing; repaired fully; an automated defense shot; a trap slowed someone.
## Damaged but still standing; repaired fully; leveled up; an automated defense shot; a trap
## slowed someone.
signal hurt(id: int, position: Vector3)
signal repaired(id: int)
signal leveled_up(id: int, level: int)
signal turret_fired(position: Vector3)
signal trap_sprung(position: Vector3)
@ -34,6 +44,9 @@ const NAMES := {
"slowing_trap": "Tar patch",
"automated_defense": "Turret",
}
## Structure types with a per-instance level (#10); every other type is always level 1.
const LEVELABLE: Array[String] = ["automated_defense", "slowing_trap"]
const MAX_LEVEL := 3
const GRID := 0.5
const FENCE_LENGTH := 2.0
const DIAGONAL_FENCE_LENGTH := 2.1213 # 1.5 * sqrt(2)
@ -128,9 +141,10 @@ static func snap(p: Vector2) -> Vector2:
return Vector2(roundf(p.x / GRID) * GRID, roundf(p.y / GRID) * GRID)
## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z).
func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
var half := Vector2(0.75, 0.75) if type == "slowing_trap" else Vector2(0.5, 0.5)
## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z). level
## only matters for a slowing_trap (trap_level_size_mult); every other type ignores it.
func footprint(type: String, x: float, z: float, rot: int, level: int = 1) -> Dictionary:
var half := Vector2(0.75, 0.75) * trap_size_mult(level) if type == "slowing_trap" else Vector2(0.5, 0.5)
var angle := 0.0
if type == "fence" or type == "gate":
half = Vector2((DIAGONAL_FENCE_LENGTH if rot % 2 == 1 else FENCE_LENGTH) * 0.5, FENCE_THICKNESS * 0.5)
@ -138,6 +152,21 @@ func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
return {"center": Vector2(x, z), "half": half, "angle": angle}
## A slowing trap's footprint/visual size at level (1-3), relative to its L1 size.
func trap_size_mult(level: int) -> float:
var mults := config.trap_level_size_mult
return float(mults[clampi(level - 1, 0, mults.size() - 1)]) if not mults.is_empty() else 1.0
func is_levelable(type: String) -> bool:
return LEVELABLE.has(type)
func level_of(id: int) -> int:
var e := campaign.state.structure(id)
return int(e.get("level", 1)) if not e.is_empty() else 1
## Closed outline (5 points) of a footprint, optionally shrunk along its length / width.
static func corners(fp: Dictionary, shrink_long: float = 0.0, shrink_wide: float = 0.0) -> PackedVector2Array:
var c: Vector2 = fp["center"]
@ -167,7 +196,7 @@ func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) ->
return "Not on the crops"
var tight := corners(fp, 0.2, 0.02)
for e in campaign.state.structures:
if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"]), 0.2, 0.02)):
if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1))), 0.2, 0.02)):
return "Something is built here already"
if _world_blocked(fp):
return "Blocked"
@ -196,7 +225,7 @@ func place(type: String, x: float, z: float, rot: int) -> int:
return -1
var id := s.next_structure_id
s.next_structure_id += 1
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type)})
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type), "level": 1})
s.record_event("structures_built")
_add_view(s.structures[s.structures.size() - 1])
_update_nav()
@ -274,6 +303,65 @@ func repair(id: int) -> bool:
return true
## What upgrading this structure to its next level costs now (empty if it isn't levelable or is
## already at MAX_LEVEL, regardless of whether it's otherwise affordable or in reach).
func upgrade_cost(id: int) -> Dictionary:
var e := campaign.state.structure(id)
if e.is_empty() or not is_levelable(e["type"]):
return {}
var level := int(e.get("level", 1))
if level >= MAX_LEVEL:
return {}
var tiers: Array = config.structure_level_costs.get(e["type"], [])
var idx := level - 1 # 0: L1 -> L2, 1: L2 -> L3
return tiers[idx] if idx >= 0 and idx < tiers.size() else {}
## 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:
var e := campaign.state.structure(id)
if e.is_empty() or not is_levelable(e["type"]):
return "Can't be upgraded"
if int(e["hp"]) < max_hp(e["type"]):
return "Repair it first"
var level := int(e.get("level", 1))
var cost := upgrade_cost(id)
if level >= MAX_LEVEL or cost.is_empty():
return "Max level"
if e["type"] == "slowing_trap":
var fp := footprint(e["type"], e["x"], e["z"], e["rot"], level + 1)
var tight := corners(fp, 0.2, 0.02)
for other in campaign.state.structures:
if int(other["id"]) == id:
continue
var other_fp := footprint(other["type"], other["x"], other["z"], other["rot"], int(other.get("level", 1)))
if _overlap(tight, corners(other_fp, 0.2, 0.02)):
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))
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) != "":
return false
var cost := upgrade_cost(id)
if not campaign.state.pay(cost):
return false
var e := campaign.state.structure(id)
e["level"] = int(e.get("level", 1)) + 1
campaign.state.record_event("upgrades_bought")
_rebuild_view(id)
_update_nav()
leveled_up.emit(id, int(e["level"]))
return true
## The structure whose footprint is within reach of p, preferring damaged ones, or -1.
func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int:
var best := -1
@ -281,7 +369,22 @@ func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int
for e in campaign.state.structures:
if damaged_only and int(e["hp"]) >= max_hp(e["type"]):
continue
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"])))
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1)))))
if d <= reach and d < best_d:
best = int(e["id"])
best_d = d
return best
## The nearest levelable structure (turret, tar patch) whose footprint is within reach of p, or -1
## (whether or not it can actually be upgraded right now -- see upgrade_blocker).
func upgradeable_near(p: Vector2, reach: float) -> int:
var best := -1
var best_d := INF
for e in campaign.state.structures:
if not is_levelable(e["type"]):
continue
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1)))))
if d <= reach and d < best_d:
best = int(e["id"])
best_d = d
@ -294,7 +397,8 @@ func try_trap(x: float, z: float) -> bool:
for e in campaign.state.structures:
if e["type"] != "slowing_trap" or int(e["hp"]) <= 0:
continue
if absf(x - float(e["x"])) <= 0.75 and absf(z - float(e["z"])) <= 0.75:
var half := 0.75 * trap_size_mult(int(e.get("level", 1)))
if absf(x - float(e["x"])) <= half and absf(z - float(e["z"])) <= half:
e["hp"] = int(e["hp"]) - 1
trap_sprung.emit(Vector3(e["x"], 0.0, e["z"]))
return true
@ -329,9 +433,23 @@ func step(dt: float) -> void:
var aim := Vector2(enemies.pos_x[target] + enemies.vel_x[target] * lead, enemies.pos_z[target] + enemies.vel_z[target] * lead) - from
var dir := Vector3(aim.x, 0.0, aim.y).normalized()
var origin := Vector3(from.x, config.combat_height, from.y)
projectiles.fire(origin, origin + dir * 0.6, dir)
var level := int(e.get("level", 1))
if level >= 3:
# L3: turret_l3_projectiles shots at once, fanned turret_l3_spread_deg apart (a
# triangle spread: the center shot plus one off either side of dir).
var shots: int = config.turret_l3_projectiles
var spread := deg_to_rad(config.turret_l3_spread_deg)
for i in shots:
var offset := (float(i) - float(shots - 1) * 0.5) * spread
var shot_dir := dir.rotated(Vector3.UP, offset)
projectiles.fire(origin, origin + shot_dir * 0.6, shot_dir)
else:
projectiles.fire(origin, origin + dir * 0.6, dir)
turret_fired.emit(origin)
_turret_cd[id] = config.turret_fire_interval
var interval := config.turret_fire_interval
if level >= 2:
interval /= config.turret_level_fire_mult
_turret_cd[id] = interval
var head: Node3D = _heads.get(id)
if head != null:
head.rotation.y = atan2(-dir.x, -dir.z)
@ -414,18 +532,32 @@ func _remove(id: int) -> void:
_update_nav()
## Rebuilds a structure's view after a level change (its size or its gun may have changed), keeping
## its cooldown (a turret doesn't reset its reload on leveling up).
func _rebuild_view(id: int) -> void:
var e := campaign.state.structure(id)
if e.is_empty():
return
var view: Node3D = _views.get(id)
if view != null:
view.queue_free()
for d in [_views, _bars, _tints, _wobble, _heads]:
(d as Dictionary).erase(id)
_add_view(e)
func _update_nav() -> void:
var entries: Array = []
for e in campaign.state.structures:
if blocks(e["type"]):
entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"]))})
entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1))))})
nav.set_structures(entries)
layout_changed.emit()
func _add_view(e: Dictionary) -> void:
var id: int = e["id"]
var view := _build_view(e["type"], e["rot"])
var view := _build_view(e["type"], e["rot"], int(e.get("level", 1)))
view.name = "%s_%d" % [e["type"], id]
add_child(view)
_views[id] = view
@ -460,11 +592,11 @@ func _add_view(e: Dictionary) -> void:
## The visual (and, for barriers other than gates, collision) of a structure, centered on its
## footprint and rotated to it.
func _build_view(type: String, rot: int) -> Node3D:
## footprint and rotated to it. level only changes a slowing_trap's size (trap_size_mult).
func _build_view(type: String, rot: int, level: int = 1) -> Node3D:
var root := Node3D.new()
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
var fp := footprint(type, 0.0, 0.0, rot)
var fp := footprint(type, 0.0, 0.0, rot, level)
root.rotation.y = -float(fp["angle"])
match type:
"fence":
@ -484,10 +616,11 @@ func _build_view(type: String, rot: int) -> Node3D:
post.position = Vector3(end * 0.95, 0.0, 0.0)
root.add_child(post)
"slowing_trap":
var mult := trap_size_mult(level)
var tar := MeshInstance3D.new()
tar.name = "Tar"
var box := BoxMesh.new()
box.size = Vector3(1.4, 0.06, 1.4)
box.size = Vector3(1.4, 0.06, 1.4) * mult
var mat := StandardMaterial3D.new()
mat.albedo_color = Color(0.1, 0.07, 0.05)
mat.roughness = 0.2
@ -497,7 +630,7 @@ func _build_view(type: String, rot: int) -> Node3D:
tar.position.y = 0.04
root.add_child(tar)
var bucket := _instance("prop/bucket_001.tscn")
bucket.position = Vector3(0.55, 0.0, 0.55)
bucket.position = Vector3(0.55 * mult, 0.0, 0.55 * mult)
_strip_collision(bucket)
root.add_child(bucket)
"automated_defense":

View file

@ -43,9 +43,9 @@ static func busy_state(cfg: GameConfig) -> FarmState:
s.resources.pouch = {"wood": 0, "scrap": 3, "straw": 1}
s.gather_charges = {"DeadTree": 1, "Haystack": 0}
s.upgrades = {"rapid_fire": 1, "sticky_tar": 1}
s.structures.append({"id": s.next_structure_id, "type": "fence", "x": 30.5, "z": -18.5, "rot": 3, "hp": 11})
s.structures.append({"id": s.next_structure_id, "type": "fence", "x": 30.5, "z": -18.5, "rot": 3, "hp": 11, "level": 1})
s.next_structure_id += 1
s.structures.append({"id": s.next_structure_id, "type": "slowing_trap", "x": 12.0, "z": -7.25, "rot": 0, "hp": 2})
s.structures.append({"id": s.next_structure_id, "type": "slowing_trap", "x": 12.0, "z": -7.25, "rot": 0, "hp": 2, "level": 2})
s.next_structure_id += 1
for n in [1, 2]:
var e := {"night": n, "crops_lost": n, "animals_lost": n - 1}

View file

@ -5,7 +5,10 @@ extends RefCounted
## recording, the sliced flow-field rebuild, gates (the scarecrow passes, enemies can't), a walled-in thief breaking
## out through a fence (barrier routing), slowing traps (speed, triggers), the automated
## defense (range), damage and breaking (breach), repair (cost, any phase), dismantling (refund),
## persistence and retry, and an A/B night: the same attack on an open and on a fenced crop field.
## persistence and retry, an A/B night: the same attack on an open and on a fenced crop field, and
## per-instance leveling (#10): a turret's fire rate and L3 volley, a tar patch's footprint, paid
## independently per placed structure, the rules around it (repair first, room, afford), and that
## the level survives a save/retry round trip.
const P := CampaignController.Phase
const T := ThiefBehavior.State
@ -33,6 +36,7 @@ func run(r: GameTestRunner) -> void:
await _breakout(r, sim, player)
_trap(r, sim)
_turret(r, sim)
_leveling(r, sim)
_repair_and_dismantle(r, sim, player)
_persistence(r, sim)
_ab_night(r, sim, player)
@ -286,6 +290,190 @@ func _turret(r: GameTestRunner, sim: FarmSim) -> void:
_settle(sim)
## Task #10: per-instance leveling (L1-L3), independent per placed structure -- a turret's fire
## rate and L3 volley, a tar patch's footprint -- and the rules around it (undamaged, affordable,
## room for a bigger tar patch), proven for two separately-placed structures of the same type so a
## level-up only ever changes the one instance.
func _leveling(r: GameTestRunner, sim: FarmSim) -> void:
var st := sim.structures
var es := sim.enemies
_rich(sim.campaign)
var keep := es.behavior
es.behavior = null # drive enemies by hand: stay put in range, no AI movement
_level_turrets(r, sim, st, es)
_level_traps(r, sim, st)
_level_rules(r, sim, st)
es.behavior = keep
_settle(sim)
## Two separately-placed turrets: A is leveled up through L2 and L3 while B is left at L1, so every
## check also proves the other one didn't change.
func _level_turrets(r: GameTestRunner, sim: FarmSim, st: StructureSystem, es: EnemySystem) -> void:
var cfg := sim.config
var base := cfg.turret_fire_interval
var a := st.place("automated_defense", 8.0, -6.0, 0)
var b := st.place("automated_defense", 30.0, -17.5, 0) # far enough apart (> 2x turret_range) that neither's test enemy draws the other's fire
r.check(st.level_of(a) == 1 and st.level_of(b) == 1, "a freshly placed turret starts at L1")
var ha := es.spawn(EnemySystem.TYPE_THIEF, 9.3, -6.0, Vector2.UP)
var ev := _fire_events(sim, 400, 3)
r.check(ev.size() == 3 and ev.all(func(e: Array) -> bool: return int(e[1]) == 1), "L1: one projectile a shot (got %s)" % [ev])
r.check(absf(ev[1][0] - ev[0][0] - base) < 0.05 and absf(ev[2][0] - ev[1][0] - base) < 0.05,
"L1: the base interval between shots (%.3f s apart, expected %.3f)" % [ev[1][0] - ev[0][0], base])
es.apply_hit_handle(ha, 99)
_step(sim, 3)
var cost2: Dictionary = cfg.structure_level_costs["automated_defense"][0]
var shed0: Dictionary = sim.campaign.state.resources.shed.duplicate()
r.check(st.upgrade(a) and st.level_of(a) == 2 and st.level_of(b) == 1, "upgrading A to L2 pays and levels only A, not B")
for m in cost2:
r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost2[m]), "L2 costs %s" % [cost2])
var expect2 := base / cfg.turret_level_fire_mult
var ha2 := es.spawn(EnemySystem.TYPE_THIEF, 9.3, -6.0, Vector2.UP)
ev = _fire_events(sim, 400, 3)
r.check(ev.size() == 3 and ev.all(func(e: Array) -> bool: return int(e[1]) == 1), "L2: still one projectile a shot (got %s)" % [ev])
r.check(absf(ev[1][0] - ev[0][0] - expect2) < 0.05 and absf(ev[2][0] - ev[1][0] - expect2) < 0.05,
"L2: %.1fx the fire rate (%.3f s apart, expected %.3f)" % [cfg.turret_level_fire_mult, ev[1][0] - ev[0][0], expect2])
es.apply_hit_handle(ha2, 99)
_step(sim, 3)
var cost3: Dictionary = cfg.structure_level_costs["automated_defense"][1]
shed0 = sim.campaign.state.resources.shed.duplicate()
r.check(st.upgrade(a) and st.level_of(a) == 3, "upgrading A to L3")
for m in cost3:
r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost3[m]), "L3 costs %s" % [cost3])
r.check(st.upgrade_cost(a).is_empty() and st.upgrade_blocker(a) == "Max level", "L3 is the max: no further cost, 'Max level'")
var ha3 := es.spawn(EnemySystem.TYPE_THIEF, 9.3, -6.0, Vector2.UP)
es.health[es.resolve_handle(ha3)] = 999 # outlast a few L3 volleys (3 shots each) so a 2nd volley is there to measure
ev = _fire_events(sim, 400, 2)
r.check(ev.size() == 2 and int(ev[0][1]) == cfg.turret_l3_projectiles and int(ev[1][1]) == cfg.turret_l3_projectiles,
"L3: %d projectiles at once, in a fan (got %s)" % [cfg.turret_l3_projectiles, ev])
r.check(absf(ev[1][0] - ev[0][0] - expect2) < 0.05, "L3: keeps L2's rate (%.3f s apart, expected %.3f)" % [ev[1][0] - ev[0][0], expect2])
es.health[es.resolve_handle(ha3)] = 1 # undo the extra HP (above) before the usual kill-and-clean-up
es.apply_hit_handle(ha3, 99)
_step(sim, 3)
r.check(st.level_of(b) == 1, "B was never upgraded, through all of A's: still L1")
var hb := es.spawn(EnemySystem.TYPE_THIEF, 31.3, -17.5, Vector2.UP)
ev = _fire_events(sim, 400, 2)
r.check(ev.size() == 2 and ev.all(func(e: Array) -> bool: return int(e[1]) == 1) and absf(ev[1][0] - ev[0][0] - base) < 0.05,
"B still fires at the unleveled base rate, one projectile (got %s)" % [ev])
es.apply_hit_handle(hb, 99)
_step(sim, 3)
for dd in es.active_count:
if es.alive[dd] == 1:
es.apply_hit(dd, 99)
st.dismantle(a)
st.dismantle(b)
## Two separately-placed tar patches: A is leveled up through L2 and L3 (footprint doubling, then
## tripling, its L1 size) while B is left at L1.
func _level_traps(r: GameTestRunner, sim: FarmSim, st: StructureSystem) -> void:
var cfg := sim.config
r.check(is_equal_approx(st.trap_size_mult(1), 1.0) and is_equal_approx(st.trap_size_mult(2), 2.0) and is_equal_approx(st.trap_size_mult(3), 3.0),
"trap_level_size_mult: L1 1x, L2 2x, L3 3x")
var a := st.place("slowing_trap", 8.0, -12.0, 0)
var b := st.place("slowing_trap", 8.0, -8.0, 0)
r.check(st.level_of(a) == 1 and st.level_of(b) == 1, "a freshly placed tar patch starts at L1")
var e: Dictionary = sim.campaign.state.structure(a)
var half1 := 0.75 * st.trap_size_mult(1)
r.check(st.try_trap(8.0 + half1 - 0.02, -12.0) and int(e["hp"]) == cfg.trap_triggers - 1, "L1 (%.2f m half): triggers just inside its edge" % half1)
e["hp"] = cfg.trap_triggers
r.check(not st.try_trap(8.0 + half1 + 0.05, -12.0), "L1: not just past its edge")
var cost2: Dictionary = cfg.structure_level_costs["slowing_trap"][0]
var shed0: Dictionary = sim.campaign.state.resources.shed.duplicate()
r.check(st.upgrade(a) and st.level_of(a) == 2 and st.level_of(b) == 1, "upgrading A to L2 pays and levels only A, not B")
for m in cost2:
r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost2[m]), "L2 costs %s" % [cost2])
var half2 := 0.75 * st.trap_size_mult(2)
r.check(is_equal_approx(half2, half1 * 2.0), "L2 doubles the L1 footprint (%.2f vs %.2f m half)" % [half2, half1])
e["hp"] = cfg.trap_triggers
r.check(st.try_trap(8.0 + half1 + 0.05, -12.0), "L2: now triggers just past the old L1 edge (bigger footprint)")
e["hp"] = cfg.trap_triggers
r.check(not st.try_trap(8.0 + half2 + 0.05, -12.0), "L2: still not past its own (bigger) edge")
var cost3: Dictionary = cfg.structure_level_costs["slowing_trap"][1]
shed0 = sim.campaign.state.resources.shed.duplicate()
r.check(st.upgrade(a) and st.level_of(a) == 3, "upgrading A to L3")
for m in cost3:
r.check(int(sim.campaign.state.resources.shed[m]) == int(shed0[m]) - int(cost3[m]), "L3 costs %s" % [cost3])
var half3 := 0.75 * st.trap_size_mult(3)
r.check(is_equal_approx(half3, half1 * 3.0), "L3 triples the L1 footprint (%.2f vs %.2f m half)" % [half3, half1])
e["hp"] = cfg.trap_triggers
r.check(st.try_trap(8.0 + half2 + 0.05, -12.0), "L3: now triggers past L2's old edge too")
e["hp"] = cfg.trap_triggers
r.check(not st.try_trap(8.0 + half3 + 0.05, -12.0), "L3: still not past its own edge")
r.check(st.upgrade_cost(a).is_empty() and st.upgrade_blocker(a) == "Max level", "L3 is the max: no further cost, 'Max level'")
r.check(st.level_of(b) == 1, "B was never upgraded, through all of A's: still L1")
var eb: Dictionary = sim.campaign.state.structure(b)
r.check(st.try_trap(8.0 + half1 - 0.02, -8.0) and int(eb["hp"]) == cfg.trap_triggers - 1
and not st.try_trap(8.0 + half1 + 0.05, -8.0), "B still triggers at its L1 size, not past it")
st.dismantle(a)
st.dismantle(b)
## The rules around leveling: a damaged structure must be repaired first (repair takes priority),
## a bigger tar patch refuses to overlap a neighbor, an unaffordable upgrade is refused, and the
## level survives a to_dict()/from_dict() round trip (save) and sync_from_state() (retry).
func _level_rules(r: GameTestRunner, sim: FarmSim, st: StructureSystem) -> void:
var s := sim.campaign.state
var dmg := st.place("automated_defense", 8.0, -6.0, 0)
st.damage(dmg, 1)
r.check(st.upgrade_blocker(dmg) == "Repair it first" and not st.upgrade(dmg) and st.level_of(dmg) == 1,
"a damaged turret must be repaired before it can be upgraded")
st.repair(dmg)
st.dismantle(dmg)
var near_a := st.place("slowing_trap", 8.0, -12.0, 0)
var near_b := st.place("slowing_trap", 9.3, -12.0, 0) # 1.3 m away: clear at L1, overlaps once doubled
var why := st.upgrade_blocker(near_a)
r.check(why == "Not enough room to upgrade" and not st.upgrade(near_a) and st.level_of(near_a) == 1,
"a tar patch refuses to upgrade into a neighbor (got '%s')" % why)
st.dismantle(near_a)
st.dismantle(near_b)
var poor := st.place("automated_defense", 8.0, -6.0, 0)
var shed0: Dictionary = s.resources.shed.duplicate()
s.resources.shed = {"wood": 0, "scrap": 0, "straw": 0}
why = st.upgrade_blocker(poor)
r.check(why.begins_with("Not enough:") and not st.upgrade(poor), "an unaffordable upgrade is refused (got '%s')" % why)
s.resources.shed = shed0
st.dismantle(poor)
var lvl := st.place("automated_defense", 8.0, -6.0, 0)
st.upgrade(lvl)
st.upgrade(lvl)
r.check(st.level_of(lvl) == 3, "set up an L3 turret to round-trip")
var d := s.to_dict()
var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d, "", true, true)))
r.check(back != null and int(back.structure(lvl)["level"]) == 3, "the level survives a save/load round trip")
st.sync_from_state() # as a retry would: rebuild every view from the (unchanged) live state
r.check(st.level_of(lvl) == 3, "and sync_from_state() (retry) keeps it")
st.dismantle(lvl)
## [time_since_the_first_call, projectiles_fired_at_once] for up to `want` shots (sim.projectiles
## may fire more than one projectile in a single tick, at L3).
func _fire_events(sim: FarmSim, max_ticks: int, want: int) -> Array:
var events: Array = []
var last := sim.projectiles.fired
var t := 0.0
var ticks := 0
while events.size() < want and ticks < max_ticks:
sim.step(DT)
t += DT
ticks += 1
var now := sim.projectiles.fired
if now > last:
events.append([t, now - last])
last = now
return events
func _repair_and_dismantle(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
var st := sim.structures
var s := sim.campaign.state