Task #28: thirty-night soak, pool sizes, and a balance report

docs/thirty-night-soak.md: the whole vacation for 3 seeds with the scripted
scarecrow (per-night arrivals planned / arrived / waited / dropped, peak alive
per type, losses, HP at dawn, levels, materials banked, sim tick), character
pools measured on nights 20 and 30 (48/20, 64/28, 48/40), density experiments,
and three things to tune next. Nothing in the game broke; no numbers changed.

soak_night.gd (cycle mode): per-night report as a table and ROW json lines;
the carry-over check counts the Workbench granted after night 1; a lost night
is retried, then (--shield=after) carried on with the scarecrow shielded; the
scripted player buys the corn shooter first, repairs, rebuilds broken
build-plan pieces, and patches at half its real max health; measuring options
--start, --load, --save-at/--save-dir, --stock, --gather=0, --pool, --frame,
--count-scale, --plan-scale.

test_nights _back_to_back: planned-vs-arrived becomes an accounting check
(arrived, or dropped at sunrise with every character of the type in use;
drops match WaveDirector.dropped; spawn_skipped unchanged), still reporting
the planned / arrived / dropped numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-06 17:55:58 -04:00
parent 3f32596034
commit e26e343436
3 changed files with 1022 additions and 65 deletions

View file

@ -6,8 +6,9 @@ extends RefCounted
## the upgrades apply to the systems they change and persist (next morning, JSON, retry), the plans
## load by count with each night's enemy speed and HP scales, the debug F3 jump moves the morning,
## and a sample of the nights (1-5, a siege, the last) plays back to back to the farmers' return,
## the rest skipped by the F3 morning path, each with its own plan and morning snapshot,
## everything carrying over.
## the rest skipped by the F3 morning path, each with its own plan and morning snapshot, every
## planned arrival accounted for (arrived, or dropped at sunrise with its pool full), everything
## carrying over.
const P := CampaignController.Phase
const T := ThiefBehavior.State
@ -420,9 +421,11 @@ func _night_jump(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
## The vacation back to back to the farmers' return: the PLAYED nights (1-5, a siege, the last),
## each with its own plan and morning snapshot and its arrivals as planned; the nights between are
## skipped on F3's morning path (CampaignDebug.jump_morning: the next morning, the farm as it is).
## The farm is defended, and the scarecrow kept out of harm.
## each with its own plan and morning snapshot; the nights between are skipped on F3's morning path
## (CampaignDebug.jump_morning: the next morning, the farm as it is). The farm is defended, and the
## scarecrow kept out of harm. Every planned arrival arrives, or waits for a free character and is
## dropped at sunrise (#25), and nothing vanishes: here no scarecrow fights and few breakers die or
## leave, so the breakers past their pool's 20 wait all night.
func _back_to_back(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: PlayerCharacter) -> void:
var c := sim.campaign
var hud := farm.get_node("Hud/PhaseHud") as PhaseHud
@ -439,6 +442,19 @@ func _back_to_back(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: Player
sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void:
var t: int = sim.enemies.type[sim.enemies.resolve_handle(h)]
arrivals[t] = int(arrivals.get(t, 0)) + 1)
# Each ground type's character pool as the night ends (#25: arrivals still waiting for a free
# character are dropped then): full, or full at the end of the night's last tick before it
# (a character can come free in the very tick the night ends, after the arrivals were looked at).
var full_at_end := {}
var full_last_tick := {}
var ground: Array[int] = []
for t in EnemySystem.TYPE_NAMES.size():
if sim.enemies.t_flying[t] == 0:
ground.append(t)
sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, previous: CampaignController.Phase) -> void:
if previous == P.NIGHT and phase != P.NIGHT:
for t in ground:
full_at_end[t] = not sim.characters.has_free(t))
var broken: Array[int] = []
sim.structures.destroyed.connect(func(id: int, _t: String, _at: Vector3) -> void: broken.append(id))
var all_good := true
@ -465,16 +481,44 @@ func _back_to_back(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: Player
var plan := sim.waves.plan_for(night)
var title_ok := hud._banner.text == "Night %d: %s" % [night, plan.title]
arrivals.clear()
full_at_end.clear()
full_last_tick.clear()
var skipped0 := sim.enemies.spawn_skipped
var structures_at_night := c.state.structures.size()
broken.clear()
var t_night := Time.get_ticks_msec()
while c.state.phase != P.MORNING and not c.is_over():
sim.scarecrow.invulnerable_left = 1.0
sim.step(DT)
if c.state.phase == P.NIGHT and c.state.phase_time_left <= 2.0 * DT: # the night's last ticks
for t in ground:
full_last_tick[t] = not sim.characters.has_free(t)
# Every planned arrival arrived or, its type's characters all in use when the night ended,
# was still waiting for one and dropped at sunrise (#25); none vanished (spawn_skipped).
var expect := plan.type_counts(plan.count_scale_in(c.config))
r.check(arrivals == expect and title_ok, "night %d, '%s': the plan's %s arrived %s" % [night, plan.title, expect, arrivals])
var dropped := {}
var accounted := sim.enemies.spawn_skipped == skipped0
for t in expect:
var gone := int(expect[t]) - int(arrivals.get(t, 0))
accounted = accounted and gone >= 0
if gone > 0:
dropped[t] = gone
accounted = accounted and ground.has(t) and (bool(full_at_end.get(t, false)) or bool(full_last_tick.get(t, false)))
for t in arrivals:
accounted = accounted and expect.has(t)
var dropped_total := 0
for t in dropped:
dropped_total += int(dropped[t])
accounted = accounted and dropped_total == sim.waves.dropped
r.check(accounted and title_ok, "night %d, '%s': the plan's %s arrived %s, %s dropped at sunrise with every character of the type in use (%d skipped)" % [
night, plan.title, expect, arrivals, dropped, sim.enemies.spawn_skipped - skipped0])
var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
r.info("night %d: %d crops, %d animals, %d supplies lost; %d structures broken (%.1f s)" % [night, e["crops_lost"],
var dropped_names := PackedStringArray()
for t in dropped:
dropped_names.append("%d %s" % [dropped[t], EnemySystem.TYPE_NAMES[t]])
r.info("night %d: %d of %d arrived, %d dropped%s; %d crops, %d animals, %d supplies lost; %d structures broken (%.1f s)" % [
night, sim.waves.spawned, plan.total(plan.count_scale_in(c.config)), dropped_total,
" (%s)" % ", ".join(dropped_names) if not dropped_names.is_empty() else "", e["crops_lost"],
e["animals_lost"], e["supplies_lost"], broken.size(), (Time.get_ticks_msec() - t_night) / 1000.0])
if night < nights:
all_good = all_good and c.state.structures.size() == structures_at_night - broken.size() and c.state.supplies_in_transit == 0

View file

@ -5,14 +5,41 @@ extends SceneTree
## godot --headless --path . --script res://game/tools/soak_night.gd -- --mode=guard
## Options:
## --mode=cycle plays whole cycles: by day it gathers until GATHER_UNTIL, then puts a
## gate back in the pen opening if it's gone and builds BUILD_PLAN in order
## (what it can afford, walking to each site), and at night it guards (as
## --mode=guard) against the night's plan. Reports each cycle (per target)
## and checks that structures, materials, and health carry over.
## --cycles=3 sets how many (5 plays the whole vacation, one night plan
## gate back in the pen opening if it's gone, buys the corn shooter as soon
## as it can, repairs damaged structures it can pay for, and builds
## BUILD_PLAN in order (what it can afford, walking to each site; a site
## whose structure was broken is built again), and at night it guards (as
## --mode=guard) against the night's plan. Reports each night: arrivals
## (planned / arrived / waited / dropped, from
## WaveDirector), the peak alive per type, losses per category, the
## scarecrow's HP at dawn, upgrade levels, materials banked, and the sim
## tick (FarmSim.step, night and dawn: average, 99th percentile, max), as
## a table and as one "ROW {json}" line per night for scripts. Checks that
## structures (the Workbench granted after night 1 aside) and materials
## carry over, and that no supplies are left in transit.
## --cycles=3 sets how many (30 plays the whole vacation, one night plan
## each); --build=0 skips building, --guard=0 leaves the night to the
## defenses. With materials left after the plan it buys upgrade levels
## (UPGRADE_ORDER) at the workbench; --upgrades=0 skips them.
## (UPGRADE_ORDER) at the workbench; --upgrades=0 skips them; --gather=0
## skips gathering.
## A lost night (game over) is reported, then retried from its morning
## (--retries=1 times). If the scarecrow still falls, the soak carries on
## with the scarecrow shielded (it takes no hits) from that night on, so
## the later nights are still measured (--shield=after, the default);
## --shield=off stops there instead, --shield=always shields it from the
## start. A farm stripped bare stops the soak once the retries are used.
## Measuring: --start=20 skips to day 20 first (CampaignDebug's F3 path:
## the farm as it is), --load=<file> starts from a saved morning instead
## (as written by --save-at=20,30 --save-dir=<dir>: those mornings are
## saved as <dir>/night_<n>.json), --stock=200 adds that much wood, scrap,
## and straw to the shed on the first morning, and --frame=1 also times
## the enemy characters' per-frame update and animation (EnemyCharacters
## and its AnimationPlayers, CPU only: headless draws nothing).
## --count-scale=4 plays the nights at another GameConfig.wave_count_scale
## (every plan without its own count_scale: nights 2-30), and
## --plan-scale=2:3,3:4 gives nights their own count_scale (in memory only).
## --pool=thief:64,breaker:28 overrides GameConfig.character_pool (any mode), set before the
## farm loads.
## --mode=gather plays one day instead: the scarecrow walks (along the navigation
## grid) to the nearest gather point with charges, holds interact until it
## is used up or the pouch is full, stores the pouch at the shed, and
@ -79,6 +106,9 @@ func _run() -> void:
thieves = int(arg.trim_prefix("--thieves="))
elif arg.begins_with("--seed="):
seed_value = int(arg.trim_prefix("--seed="))
elif arg.begins_with("--pool="):
_pool_override(arg.trim_prefix("--pool="))
seed(seed_value)
var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
root.add_child(farm)
await process_frame
@ -88,6 +118,7 @@ func _run() -> void:
_player.set_physics_process(false)
var c := _sim.campaign
var cfg := _sim.config
var vacation := cfg.campaign_nights
cfg.night_thieves = thieves
cfg.campaign_nights = 99
_sim.loot._rng.seed = seed_value
@ -99,20 +130,70 @@ func _run() -> void:
return
if _mode == "cycle":
var cycles := 3
for a in OS.get_cmdline_user_args():
if String(a).begins_with("--cycles="):
cycles = int(String(a).trim_prefix("--cycles="))
var start := 1
var load_path := ""
cfg.night_thieves = 0 # the night's plan
for a in OS.get_cmdline_user_args():
if String(a).begins_with("--thieves="):
cfg.night_thieves = int(String(a).trim_prefix("--thieves="))
for a in OS.get_cmdline_user_args():
if String(a) == "--build=0":
var arg := String(a)
if arg.begins_with("--cycles="):
cycles = int(arg.trim_prefix("--cycles="))
elif arg.begins_with("--thieves="):
cfg.night_thieves = int(arg.trim_prefix("--thieves="))
elif arg == "--build=0":
_do_build = false
elif String(a) == "--guard=0":
elif arg == "--guard=0":
_do_guard = false
elif String(a) == "--upgrades=0":
elif arg == "--upgrades=0":
_do_upgrades = false
elif arg == "--gather=0":
_do_gather = false
elif arg == "--frame=1":
_time_frame = true
elif arg.begins_with("--retries="):
_retries = maxi(int(arg.trim_prefix("--retries=")), 0)
elif arg.begins_with("--shield="):
_shield_mode = arg.trim_prefix("--shield=")
elif arg.begins_with("--start="):
start = maxi(int(arg.trim_prefix("--start=")), 1)
elif arg.begins_with("--load="):
load_path = arg.trim_prefix("--load=")
elif arg.begins_with("--stock="):
_stock = maxi(int(arg.trim_prefix("--stock=")), 0)
elif arg.begins_with("--count-scale="):
cfg.wave_count_scale = float(arg.trim_prefix("--count-scale="))
elif arg.begins_with("--plan-scale="):
for part in arg.trim_prefix("--plan-scale=").split(",", false):
var kv := part.split(":")
if kv.size() == 2 and _sim.waves.plan_for(int(kv[0])) != null:
_sim.waves.plan_for(int(kv[0])).count_scale = float(kv[1])
elif arg.begins_with("--save-dir="):
_save_dir = arg.trim_prefix("--save-dir=")
elif arg.begins_with("--save-at="):
for x in arg.trim_prefix("--save-at=").split(",", false):
_save_at.append(int(x))
if not _shield_mode in ["after", "off", "always"]:
push_error("soak: --shield is after, off, or always (not '%s')" % _shield_mode)
_quit()
return
_shielded = _shield_mode == "always"
if load_path != "":
var saved := SaveGame.read(load_path)
if saved.status != SaveGame.Status.OK:
push_error("soak: can't load %s: %s" % [load_path, saved.message])
_quit()
return
c.load_state(saved.state)
var debug := farm.get_node("CampaignDebug") as CampaignDebug
while c.state.night < start:
if not debug.jump_morning(1):
push_error("soak: can't skip to day %d (debug builds only)" % start)
_quit()
return
# The vacation ends after its last night (the farmers' return) unless more are asked for.
cfg.campaign_nights = maxi(vacation, c.state.night + cycles - 1)
print("soak cycle: seed %d, character pool %s (thieves %d, breakers %d), wave_count_scale %.2f" % [seed_value,
cfg.character_pool, _sim.characters.pool_size(EnemySystem.TYPE_THIEF), _sim.characters.pool_size(EnemySystem.TYPE_BREAKER),
cfg.wave_count_scale])
_cycles(cycles)
_quit()
return
@ -155,38 +236,81 @@ func _quit() -> void:
var _fields := {}
var _built := {} # BUILD_PLAN index -> true
var _skip := {} # BUILD_PLAN index -> true: it can't go at its site today
var _skip_told := {} # BUILD_PLAN index -> true: said so once
var _ever_built := {} # BUILD_PLAN index -> true once built (building it again is a rebuild)
var _do_build := true
var _do_guard := true
var _do_upgrades := true
var _do_gather := true
var _time_frame := false
var _retries := 1
var _shield_mode := "after"
var _shielded := false
var _stock := 0
var _save_at: Array[int] = []
var _save_dir := ""
var _carry_errors: Array[String] = []
## Upgrade levels bought: [day, id, level].
var _buys: Array = []
var _rebuilt: int = 0
## --pool's edited GameConfig, held so the resource cache hands this one to the farm.
var _config_keep: GameConfig
## --pool=thief:64,breaker:28: GameConfig.character_pool for the farm about to load (the
## characters are made when it loads).
func _pool_override(spec: String) -> void:
_config_keep = load("res://game/resources/game_config.tres") as GameConfig
var pool := _config_keep.character_pool.duplicate()
for part in spec.split(",", false):
var kv := part.split(":")
if kv.size() == 2:
pool[kv[0].strip_edges()] = int(kv[1])
_config_keep.character_pool = pool
func _cycles(n: int) -> void:
var c := _sim.campaign
var s := c.state
print("soak cycle: %d cycles, night plan '%s' (%d thieves), gather until %.0f s, build %s, guard %s" % [
n, _sim.waves.tonight().title, _sim.waves.tonight().total(), GATHER_UNTIL, _do_build, _do_guard])
print("| Night | Gathered | Built (total) | Upgrades | Crops: stolen / recovered / lost | Animals: grabbed / out / led back / lost | Supplies: taken / back / lost | Left | HP | Broken | Shed after |")
print("|---|---|---|---|---|---|---|---|---|---|")
var cfg := _sim.config
print("soak cycle: %d cycles from night %d; gather %s (until %.0f s), build %s, upgrades %s, guard %s; retries %d, shield %s, stock %d" % [
n, c.state.night, _do_gather, GATHER_UNTIL, _do_build, _do_upgrades, _do_guard, _retries, _shield_mode, _stock])
print("| Night | Result | Arrivals: planned / arrived / waited / dropped | Peak alive: crows / thieves / breakers / UFOs (all) | Lost: crops / animals / supplies | Left: crops / animals / supplies | HP at dawn | Levels (bought today) | Banked: wood / scrap / straw / goop | Built / broken / repaired (standing) | Tick avg / p99 / max (us) |")
print("|---|---|---|---|---|---|---|---|---|---|---|")
var lost_by := {}
_sim.loot.loot_event.connect(func(kind: StringName, id: int, _p: Vector3) -> void:
if kind == &"lost" and _sim.loot.category[id] == LootSystem.Category.SUPPLY:
lost_by[_sim.loot.sack_material[id]] = int(lost_by.get(_sim.loot.sack_material[id], 0)) + _sim.loot.sack_amount[id])
var all_ticks := PackedInt32Array()
var lost_nights: Array[String] = []
var t0 := Time.get_ticks_msec()
for k in n:
if c.is_over():
break
var shed0: Dictionary = s.resources.shed.duplicate()
var built0 := _sim.structures.count()
var played := 0
var attempt := 0
var stop := ""
while played < n:
var s := c.state
var night := s.night
if played == 0 and attempt == 0 and _stock > 0:
for m in ["wood", "scrap", "straw"]:
s.resources.shed[m] = int(s.resources.shed[m]) + _stock
c._morning_snapshot = s.to_dict() # so a retry keeps it
if attempt == 0 and _save_at.has(night) and _save_dir != "":
var path := _save_dir.path_join("night_%d.json" % night)
print("soak: the morning of night %d saved to %s (%s)" % [night, path, error_string(SaveGame.write(c.morning_snapshot(), path))])
var ever_built0 := _ever_built.duplicate()
var buys0 := _buys.size()
_skip.clear()
_fields.clear() # the structures may have changed overnight
_rebuilt = 0
var gathered := {"wood": 0, "scrap": 0, "straw": 0}
var cb := func(m: String, amount: int, _node: GatherNode) -> void: gathered[m] += amount
_sim.interactions.gathered.connect(cb)
var w0 := Time.get_ticks_msec()
c.begin_day()
var t := 0.0
while c.is_daytime():
var me := Vector2(_player.global_position.x, _player.global_position.z)
if not (t < GATHER_UNTIL and _gather_tick(me)):
if not (_do_gather and t < GATHER_UNTIL and _gather_tick(me)):
Input.action_release("interact")
if _do_build:
_build_tick(me)
@ -196,49 +320,240 @@ func _cycles(n: int) -> void:
t += DT
Input.action_release("interact")
_sim.interactions.gathered.disconnect(cb)
# Night: guard. Record what should carry over.
# Night: guard, and measure. Record what should carry over.
var plan := _sim.waves.tonight()
var planned: Dictionary = plan.type_counts(plan.count_scale_in(cfg)) if plan != null else {}
var arrived := {}
var cb_in := func(h: int, _at: Vector2) -> void:
var d := _sim.enemies.resolve_handle(h)
if d >= 0:
arrived[int(_sim.enemies.type[d])] = int(arrived.get(int(_sim.enemies.type[d]), 0)) + 1
_sim.waves.arrived.connect(cb_in)
var breaks: Array[int] = [] # a lambda can't add to a captured int
var cb2 := func(_i: int, _t: String, _at: Vector3) -> void: breaks.append(1)
_sim.structures.destroyed.connect(cb2)
var built_night := _sim.structures.count()
var had_workbench := _sim.structures.has_workbench()
var res_night: Dictionary = s.resources.to_dict()
var blocked0 := _sim.scarecrow.rejected_hits
lost_by.clear()
var fears0 := _fears
var ticks := PackedInt32Array()
var frames := PackedInt32Array()
var peak := [0, 0, 0, 0, 0] # per type (EnemySystem.TYPE_NAMES), then all
var waited_by := [0, 0, 0, 0]
var seen := [[null, 0], [null, 0], [null, 0], [null, 0]]
var waiting_peak := 0
var night_t := 0.0
if not _do_guard:
_player.global_position = Vector3(HOME.x, 0.0, HOME.y)
while s.phase != CampaignController.Phase.MORNING and not c.is_over():
if _do_guard:
_guard()
if _shielded:
_sim.scarecrow.invulnerable_left = 1.0
var u0 := Time.get_ticks_usec()
_sim.step(DT)
ticks.append(Time.get_ticks_usec() - u0)
if _time_frame:
var f0 := Time.get_ticks_usec()
_sim.characters._process(DT)
for anim: AnimationPlayer in _sim.characters._anims:
if anim.is_playing():
anim.advance(DT)
frames.append(Time.get_ticks_usec() - f0)
if s.phase == CampaignController.Phase.NIGHT:
night_t += DT
_count_waits(waited_by, seen)
waiting_peak = maxi(waiting_peak, _sim.waves.waiting())
if ticks.size() % 2 == 0:
_peaks(peak)
_sim.waves.arrived.disconnect(cb_in)
_sim.structures.destroyed.disconnect(cb2)
var broken := breaks.size()
Input.action_release("patch")
if c.is_over():
print("| %d | campaign over: %s |" % [k + 1, CampaignController.Outcome.keys()[c.outcome]])
break
# Carry-over checks: nothing is built at night, so structures only go down by breaks;
# wood and scrap only go down by what thieves carried off (straw also by patches).
if _sim.structures.count() != built_night - broken:
_carry_errors.append("cycle %d: %d structures at night - %d broken != %d in the morning" % [k + 1, built_night, broken, _sim.structures.count()])
var now := s.resources.to_dict()
all_ticks.append_array(ticks)
var over := c.is_over()
# The night's record: the log entry once the dawn grace is over, else (it was lost before)
# the counts so far.
var logged := not s.night_log.is_empty() and int(s.night_log[s.night_log.size() - 1]["night"]) == night
var e: Dictionary
if logged:
e = s.night_log[s.night_log.size() - 1]
else:
e = s.night_events.duplicate()
var now := s.asset_counts()
e["crops_lost"] = maxi(c._night_start[0] - now[0], 0) if c._night_start.size() == 3 else 0
e["animals_lost"] = maxi(c._night_start[1] - now[1], 0) if c._night_start.size() == 3 else 0
var result := "ok"
var lost := over and c.outcome != CampaignController.Outcome.VACATION_COMPLETE
if over:
match c.outcome:
CampaignController.Outcome.VACATION_COMPLETE:
result = "farmers back"
CampaignController.Outcome.GAME_OVER_SCARECROW:
result = "scarecrow destroyed %.0f s in" % night_t
CampaignController.Outcome.GAME_OVER_STRIPPED:
result = "farm stripped %.0f s in" % night_t
if _shielded:
result += ", shielded (%d hits blocked)" % (_sim.scarecrow.rejected_hits - blocked0)
if attempt > 0:
result += ", retry %d" % attempt
var bought: Array[String] = []
for i in range(buys0, _buys.size()):
bought.append(Upgrades.name_at(cfg, _buys[i][1], _buys[i][2]))
var banked := {}
var res_now: Dictionary = s.resources.to_dict()
for m in ResourceStore.MATERIALS:
banked[m] = int(res_now["shed"].get(m, 0))
for key in ResourceStore.POUCH_KEYS:
banked[m] += int(res_now[key].get(m, 0))
var tick := _stats(ticks)
var frame := _stats(frames)
var hidden_animating := 0 # pool characters hidden (free) but still playing a clip
for i in _sim.characters._anims.size():
if _sim.characters._anims[i].is_playing() and not _sim.characters._roots[i].visible:
hidden_animating += 1
var row := {
"night": night, "title": plan.title if plan != null else "", "attempt": attempt + 1, "result": result,
"lost_night": lost, "shielded": _shielded, "night_time": snappedf(night_t, 0.1),
"planned": _sum(planned), "arrived": _sum(arrived), "waited": _sim.waves.waited, "dropped": _sim.waves.dropped,
"planned_by": _by_type(planned), "arrived_by": _by_type(arrived), "waited_by": waited_by, "waiting_peak": waiting_peak,
"peak_by": peak.slice(0, 4), "peak": peak[4],
"stolen": [int(e.get("crops_stolen", 0)), int(e.get("animals_stolen", 0)), int(e.get("supplies_stolen", 0))],
"lost": [int(e.get("crops_lost", 0)), int(e.get("animals_lost", 0)), int(e.get("supplies_lost", 0))],
"left": [s.crops, s.animals, s.supplies], "totals": [s.crops_total, s.animals_total, s.supplies_total],
"hp": s.scarecrow_hp, "max_hp": s.scarecrow_max_hp, "damage": int(e.get("scarecrow_damage", 0)),
"patches": int(e.get("patches", 0)),
"levels": Upgrades.levels_bought(cfg, s), "levels_total": Upgrades.levels_total(cfg), "bought": bought,
"banked": banked, "gathered": gathered,
"built": int(e.get("structures_built", 0)), "rebuilt": _rebuilt, "broken": broken,
"repairs": int(e.get("repairs", 0)), "standing": _sim.structures.count(),
"kills_by": [int(e.get("killed_thief", 0)), int(e.get("killed_crow", 0)), int(e.get("killed_breaker", 0)), int(e.get("killed_ufo", 0))],
"tick_avg": tick[0], "tick_p99": tick[1], "tick_max": tick[2], "ticks": ticks.size(),
"frame_avg": frame[0], "frame_p99": frame[1], "frame_max": frame[2], "hidden_animating": hidden_animating,
"pool": [_sim.characters.pool_size(EnemySystem.TYPE_THIEF), _sim.characters.pool_size(EnemySystem.TYPE_BREAKER)],
"wall": (Time.get_ticks_msec() - w0) / 1000.0,
}
var dropped_by := ""
if row["dropped"] > 0:
var parts: Array[String] = []
for ty in EnemySystem.TYPE_NAMES.size():
var gone: int = row["planned_by"][ty] - row["arrived_by"][ty]
if gone > 0 and not lost:
parts.append("%d %s" % [gone, EnemySystem.TYPE_NAMES[ty]])
dropped_by = " (%s)" % ", ".join(parts) if not parts.is_empty() else ""
var pk: Array = row["peak_by"]
print("| %d %s | %s | %d / %d / %d / %d%s | %d / %d / %d / %d (%d) | %d / %d / %d | %d / %d / %d | %d/%d | %d of %d%s | %d / %d / %d / %d | %d (%d rebuilt) / %d / %d (%d) | %.0f / %d / %d |" % [
night, row["title"], result, row["planned"], row["arrived"], row["waited"], row["dropped"], dropped_by,
pk[1], pk[0], pk[2], pk[3], row["peak"], row["lost"][0], row["lost"][1], row["lost"][2],
s.crops, s.animals, s.supplies, s.scarecrow_hp, s.scarecrow_max_hp,
row["levels"], row["levels_total"], (": " + ", ".join(bought)) if not bought.is_empty() else "",
banked["wood"], banked["scrap"], banked["straw"], banked["alien_goop"],
row["built"], _rebuilt, broken, row["repairs"], row["standing"], tick[0], tick[1], tick[2]])
print("ROW " + JSON.stringify(row))
if lost:
lost_nights.append("night %d, attempt %d: %s" % [night, attempt + 1, result])
attempt += 1
var again := attempt <= _retries
if not again and c.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW and _shield_mode == "after" and not _shielded:
_shielded = true
again = true
print("soak: the scarecrow fell on night %d %d times; from here on it's shielded (it takes no hits)" % [night, attempt])
if not again:
stop = "night %d lost: %s" % [night, result]
break
_ever_built = ever_built0
_buys.resize(buys0)
c.retry_night()
continue
played += 1
attempt = 0
if over:
break # the farmers are back
# Carry-over checks: nothing is built at night, so structures only go down by breaks (and
# up by the Workbench, granted when night 1 ends); wood and scrap only go down by what
# thieves carried off (straw also by patches).
var granted := 1 if not had_workbench and _sim.structures.has_workbench() else 0
if _sim.structures.count() != built_night - broken + granted:
_carry_errors.append("night %d: %d structures at night - %d broken + %d granted != %d in the morning" % [night,
built_night, broken, granted, _sim.structures.count()])
for m in ["wood", "scrap"]:
var before := int(res_night["shed"][m])
var after := int(now["shed"][m])
var after := int(res_now["shed"][m])
for key in ResourceStore.POUCH_KEYS: # every scarecrow's pouch (solo: player 2's stays empty)
before += int(res_night[key][m])
after += int(now[key][m])
after += int(res_now[key][m])
if after != before - int(lost_by.get(m, 0)):
_carry_errors.append("cycle %d: %s %d -> %d overnight, %d carried off" % [k + 1, m, before, after, int(lost_by.get(m, 0))])
_carry_errors.append("night %d: %s %d -> %d overnight, %d carried off" % [night, m, before, after, int(lost_by.get(m, 0))])
if s.supplies_in_transit != 0:
_carry_errors.append("cycle %d: %d supplies still in transit in the morning" % [k + 1, s.supplies_in_transit])
var e: Dictionary = s.night_log[s.night_log.size() - 1]
print("| %d %s | %s | %d (%d) | %d | %d / %d / %d | %d / %d / %d / %d | %d / %d / %d | %d crops, %d animals | %d/%d | %d | %s |" % [k + 1,
_sim.waves.plan_for(k + 1).title, ResourceStore.describe(gathered), built_night - built0, built_night, s.upgrades.size(),
e["crops_stolen"], e["crops_recovered"], e["crops_lost"],
e["animals_stolen"], e["animals_strayed"], e["animals_recovered"], e["animals_lost"], e["supplies_stolen"], e["supplies_recovered"],
e["supplies_lost"], s.crops, s.animals, s.scarecrow_hp, s.scarecrow_max_hp, broken, ResourceStore.describe(s.resources.shed)])
print("soak cycle: carry-over %s; %.1f s of wall time" % ["OK" if _carry_errors.is_empty() else "ERRORS %s" % [_carry_errors],
(Time.get_ticks_msec() - t0) / 1000.0])
_carry_errors.append("night %d: %d supplies still in transit in the morning" % [night, s.supplies_in_transit])
var all := _stats(all_ticks)
print("soak cycle: %d nights played%s; carry-over %s; night tick over all nights avg %.0f / p99 %d / max %d us; %.1f s of wall time" % [
played, (", stopped: " + stop) if stop != "" else "", "OK" if _carry_errors.is_empty() else "ERRORS %s" % [_carry_errors],
all[0], all[1], all[2], (Time.get_ticks_msec() - t0) / 1000.0])
print("soak cycle: lost nights: %s" % ("none" if lost_nights.is_empty() else "; ".join(lost_nights)))
var days := {}
for b in _buys:
var key := String(b[1])
days[key] = days.get(key, []) + [int(b[0])]
var lines: Array[String] = []
for id in UPGRADE_ORDER:
if days.has(id):
lines.append("%s day %s" % [id, "/".join(PackedStringArray(days[id].map(func(d: int) -> String: return str(d))))])
print("soak cycle: levels bought (day of each level): %s" % (", ".join(lines) if not lines.is_empty() else "none"))
print("BUYS " + JSON.stringify(_buys))
## Per-type counts as an Array in EnemySystem.TYPE_NAMES order.
static func _by_type(counts: Dictionary) -> Array:
var out := []
for t in EnemySystem.TYPE_NAMES.size():
out.append(int(counts.get(t, 0)))
return out
static func _sum(counts: Dictionary) -> int:
var n := 0
for t in counts:
n += int(counts[t])
return n
## [average, 99th percentile, max] of tick times (0s when empty).
static func _stats(us: PackedInt32Array) -> Array:
if us.is_empty():
return [0.0, 0, 0]
var sorted := us.duplicate()
sorted.sort()
var total := 0
for u in sorted:
total += u
return [float(total) / sorted.size(), sorted[int(0.99 * (sorted.size() - 1))], sorted[sorted.size() - 1]]
## The peak alive so far, per type and in all.
func _peaks(peak: Array) -> void:
var es := _sim.enemies
var by := [0, 0, 0, 0]
for d in es.active_count:
if es.alive[d] == 1:
by[es.type[d]] += 1
for t in 4:
peak[t] = maxi(peak[t], by[t])
peak[4] = maxi(peak[4], by[0] + by[1] + by[2] + by[3])
## Counts tonight's arrivals that had to wait, per type: what joined each type's waiting list
## (WaveDirector._waiting) since the last tick. seen[t] is [its first entry, its size] then: the
## same first entry means the same list grew, another one that it emptied and filled again.
func _count_waits(waited_by: Array, seen: Array) -> void:
var w := _sim.waves
for t in w._waiting.size():
var list: Array = w._waiting[t]
var was: Array = seen[t]
var kept: int = was[1] if not list.is_empty() and int(was[1]) > 0 and is_same(list[0], was[0]) else 0
waited_by[t] += list.size() - kept
seen[t] = [list[0] if not list.is_empty() else null, list.size()]
## One gathering tick: walk to the nearest point with charges and gather, or store a full pouch.
@ -268,8 +583,12 @@ func _gather_tick(me: Vector2) -> bool:
return true
## One building tick: put a gate back in the pen opening if it's gone, else walk to the next
## BUILD_PLAN site it can afford and place it; otherwise wait in the middle of the crop field.
## One building tick: put a gate back in the pen opening if it's gone, else buy the corn shooter
## once it can, else repair the nearest damaged structure it can pay for, else walk to the next
## BUILD_PLAN site with nothing standing
## (never built, or broken since) that it can afford and build it; with nothing to build, buy
## upgrades; otherwise wait in the middle of the crop field. Building, repairing, and buying are
## instant once it's close (no build mode, no hold to repair, no menu).
func _build_tick(me: Vector2) -> void:
var st := _sim.structures
var r := _sim.campaign.state.resources
@ -279,10 +598,14 @@ func _build_tick(me: Vector2) -> void:
elif st.validate("gate", PEN_GATE.x, PEN_GATE.y, 2, me) == "":
st.place("gate", PEN_GATE.x, PEN_GATE.y, 2)
return
if _do_upgrades and not Upgrades.owned(_sim.campaign.state, "corn_shooter") and _upgrade_tick(me, "corn_shooter"):
return # the gun first
if _repair_tick(me):
return
for i in BUILD_PLAN.size():
if _built.has(i):
continue
var part: Array = BUILD_PLAN[i]
if _skip.has(i) or _standing(part) >= 0:
continue
if not r.can_afford(_sim.config.costs.get(part[0], {})):
continue
var at: Vector2 = part[1]
@ -292,22 +615,67 @@ func _build_tick(me: Vector2) -> void:
var why := st.validate(part[0], at.x, at.y, part[2], me)
if why == "":
st.place(part[0], at.x, at.y, part[2])
if _ever_built.has(i):
_rebuilt += 1
_ever_built[i] = true
else:
print("soak: can't build %s at %s: %s" % [part[0], at, why])
_built[i] = true # built, or impossible here: either way move on
if not _skip_told.has(i):
print("soak: can't build %s at %s: %s" % [part[0], at, why])
_skip_told[i] = true
_skip[i] = true # not today: move on
return
if _do_upgrades and _upgrade_tick(me):
return
_walk_field(Vector2(30.0, -3.0), me)
## The structure standing at a BUILD_PLAN site (its id), or -1.
func _standing(part: Array) -> int:
var at: Vector2 = part[1]
for e in _sim.campaign.state.structures:
if e["type"] == part[0] and Vector2(float(e["x"]), float(e["z"])).distance_to(at) < 0.1:
return int(e["id"])
return -1
## Walks to the nearest damaged structure it can pay to repair fully, and repairs it. Returns false
## if there's none.
func _repair_tick(me: Vector2) -> bool:
var st := _sim.structures
var r := _sim.campaign.state.resources
var pick := -1
var at := Vector2.ZERO
var best := INF
for e in _sim.campaign.state.structures:
var cost := st.repair_cost(int(e["id"]))
if cost.is_empty() or not r.can_afford(cost):
continue
var p := Vector2(float(e["x"]), float(e["z"]))
if p.distance_to(me) < best:
best = p.distance_to(me)
pick = int(e["id"])
at = p
if pick < 0:
return false
if best > 4.0:
_walk_field(at, me)
else:
st.repair(pick)
return true
## Walks to the workbench and buys the next upgrade level it can afford (one that's in stock and
## open by today), the lowest level first: every first level in UPGRADE_ORDER before any second
## one, and so on. Returns false if there's none.
func _upgrade_tick(me: Vector2) -> bool:
## one, and so on. The workbench's own upgrades need it standing (granted after night 1, not
## broken). only: that upgrade or none. Returns false if there's none.
func _upgrade_tick(me: Vector2, only: String = "") -> bool:
var c := _sim.campaign
var pick := ""
for id in UPGRADE_ORDER:
if only != "" and id != only:
continue
if Upgrades.shop_of(c.config, id) == "workbench" and not _sim.structures.workbench_available():
continue
if Upgrades.blocker(c, id) == "" and (pick == "" or Upgrades.level(c.state, id) < Upgrades.level(c.state, pick)):
pick = id
if pick == "":
@ -317,7 +685,10 @@ func _upgrade_tick(me: Vector2) -> bool:
if at.distance_to(me) > bench.reach - 0.3:
_walk_field(at, me)
else:
var before := Upgrades.level(c.state, pick)
Upgrades.buy(c, pick, _sim.structures)
if Upgrades.level(c.state, pick) > before:
_buys.append([c.state.night, pick, Upgrades.level(c.state, pick)])
return true
@ -448,7 +819,7 @@ func _guard() -> void:
if loot.followers() > 0 and best > -25.0:
goal = PEN_INSIDE
best = -25.0
var hurt := kit.hp() <= cfg.scarecrow_max_hp / 2
var hurt := kit.hp() <= _sim.campaign.state.scarecrow_max_hp / 2 # with straw stuffing bought
if hurt and nearest_d > 8.0:
Input.action_press("patch")
return