extends SceneTree ## Plays whole nights headless against the night thief trickle with a scripted scarecrow and ## reports each night, as supporting evidence for Step 4's exit gate (the gate itself is a ## human playtest). Days are skipped; each night runs its full night_length plus the dawn grace. ## 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, 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; --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= starts from a saved morning instead ## (as written by --save-at=20,30 --save-dir=: those mornings are ## saved as /night_.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 ## reports how long gathering everything takes and what it yields. ## --mode=idle | guard idle: the scarecrow stands in the open doing nothing (baseline). ## guard: it goes for the most urgent threat (carriers, then thieves ## taking something, then dropped loot and loose animals, then other ## thieves), attacks thieves in range with a clear line with its best ## weapons (a pumpkin bomb from the off-hand into a crowd, and the corn ## shooter once bought, else the pitchfork, closing in to stab), uses fear on a ## carrier or a crowd in range, leads animals following it back to the pen ## when no carrier is close, and patches up when hurt and nothing is close. ## --minutes=10 night time to play (rounded up to whole nights) ## --thieves=1 GameConfig.night_thieves (at most this many at once) ## --seed=1 randomizes thief targets and arrival points const DT := 1.0 / 60.0 const GATHER_UNTIL := 115.0 ## The scripted scarecrow's defenses, in order: automated defenses around the crop field's ## corners, slowing traps on the approaches, then fences down the field's east side. const BUILD_PLAN := [ ["automated_defense", Vector2(46.0, -15.0), 0], ["automated_defense", Vector2(34.0, 12.5), 0], ["slowing_trap", Vector2(43.5, -17.0), 0], ["automated_defense", Vector2(13.5, -15.0), 0], ["slowing_trap", Vector2(31.0, 11.5), 0], ["fence", Vector2(45.0, -15.5), 2], ["fence", Vector2(45.0, -13.5), 2], ["fence", Vector2(45.0, -11.5), 2], ["fence", Vector2(45.0, -9.5), 2], ["fence", Vector2(45.0, -7.5), 2], ["fence", Vector2(45.0, -5.5), 2], ["automated_defense", Vector2(13.5, 9.0), 0], ["automated_defense", Vector2(7.0, -3.5), 0], ["automated_defense", Vector2(9.5, -14.0), 0], ] ## The scripted scarecrow's upgrades, in order, bought with what's left after building: their ## first levels, then (from the days they open) their next ones, lowest level first. const UPGRADE_ORDER: Array[String] = ["corn_shooter", "long_range", "rapid_fire", "heavy_seeds", "pumpkin_bomb", "reinforced_fences", "quick_fear", "wide_fear", "sticky_tar", "straw_stuffing"] const PEN_GATE := Vector2(4.0, -6.0) const PEN_INSIDE := Vector2(-2.0, -6.0) const HOME := Vector2(10.0, -8.0) # open ground between the pen, the shed, and the field const SHOOT_RANGE := 11.0 var _sim: FarmSim var _player: PlayerCharacter var _mode := "guard" var _fears: int = 0 var _shots: int = 0 func _initialize() -> void: _run.call_deferred() func _run() -> void: var minutes := 10.0 var thieves := 1 var seed_value := 1 for a in OS.get_cmdline_user_args(): var arg := String(a) if arg.begins_with("--mode="): _mode = arg.trim_prefix("--mode=") elif arg.begins_with("--minutes="): minutes = float(arg.trim_prefix("--minutes=")) elif arg.begins_with("--thieves="): 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 _sim = farm.get_node("FarmSim") as FarmSim _sim.set_physics_process(false) _player = farm.get_node("Player") as PlayerCharacter _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 _sim.waves.rng.seed = seed_value _player.global_position = Vector3(HOME.x, 0.0, HOME.y) if _mode == "gather": _gather_day() _quit() return if _mode == "cycle": var cycles := 3 var start := 1 var load_path := "" cfg.night_thieves = 0 # the night's plan for a in OS.get_cmdline_user_args(): 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 arg == "--guard=0": _do_guard = false 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 var nights := ceili(minutes * 60.0 / cfg.night_length) print("soak: mode=%s, %d nights of %.0f s + %.0f s dawn, night_thieves=%d, seed=%d" % [ _mode, nights, cfg.night_length, cfg.dawn_grace, thieves, seed_value]) print("| Night | Stolen | Recovered | Lost | Crops left | Scarecrow HP | Fears | Attacks | Kills |") print("|---|---|---|---|---|---|---|---|---|") var t0 := Time.get_ticks_msec() for n in nights: c.begin_day() c.advance_phase() c.advance_phase() var kills0 := _sim.enemies.kills var fears0 := _fears var shots0 := _shots while c.state.phase != CampaignController.Phase.MORNING and not c.is_over(): if _mode == "guard": _guard() _sim.step(DT) if c.is_over(): print("| %d | campaign over: %s |" % [c.state.night, CampaignController.Outcome.keys()[c.outcome]]) break var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1] print("| %d | %d | %d | %d | %d/%d | %d/%d | %d | %d | %d |" % [e["night"], e["crops_stolen"], e["crops_recovered"], e["crops_lost"], c.state.crops, c.state.crops_total, c.state.scarecrow_hp, c.state.scarecrow_max_hp, _fears - fears0, _shots - shots0, _sim.enemies.kills - kills0]) Input.action_release("patch") print("soak: %.1f s of wall time" % ((Time.get_ticks_msec() - t0) / 1000.0)) _quit() ## Frees the farm, then quits once the audio server has dropped its stopped sounds. func _quit() -> void: for n in root.get_children(): n.queue_free() await process_frame await create_timer(0.25).timeout quit() var _fields := {} 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 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() 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 (_do_gather and t < GATHER_UNTIL and _gather_tick(me)): Input.action_release("interact") if _do_build: _build_tick(me) else: _walk_field(Vector2(30.0, -3.0), me) _sim.step(DT) t += DT Input.action_release("interact") _sim.interactions.gathered.disconnect(cb) # 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 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") 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(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(res_now[key][m]) if after != before - 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("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. ## Returns false when nothing is left to gather or store. func _gather_tick(me: Vector2) -> bool: var it := _sim.interactions var r := _sim.campaign.state.resources var target: GatherNode = null var best := INF for n in it.nodes: var d := Vector2(n.global_position.x, n.global_position.z).distance_to(me) if it.charges(n) > 0 and d < best: best = d target = n if target == null and r.pouch_total() == 0: return false if target == null or r.pouch_room() < target.yield_amount: Input.action_release("interact") var shed := _sim.zones.zone(FarmZone.Kind.SUPPLY_SHED) _walk_field(Vector2(shed.global_position.x, shed.global_position.z + 3.0), me) return true if Vector2(target.global_position.x, target.global_position.z).distance_to(me) > target.reach - 0.1: Input.action_release("interact") _walk_field(_stand_spot(target), me) else: Input.action_press("interact") return true ## 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 if _sim.nav.structure_at[_sim.nav.cell_of(PEN_GATE.x, PEN_GATE.y)] < 0 and r.can_afford(_sim.config.costs["gate"]): if PEN_GATE.distance_to(me) > 4.0: _walk_field(PEN_GATE + Vector2(2.5, 0.0), me) 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(): 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] if at.distance_to(me) > 6.0: _walk_field(at + Vector2(-2.0, 0.0), me) return 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: 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. 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 == "": return false var bench := _sim.interactions.workbench var at := Vector2(bench.global_position.x, bench.global_position.z) 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 func _gather_day() -> void: var c := _sim.campaign var it := _sim.interactions var r := c.state.resources var shed_start: Dictionary = r.shed.duplicate() var shed := _sim.zones.zone(FarmZone.Kind.SUPPLY_SHED) var drop_off := Vector2(shed.global_position.x, shed.global_position.z + 3.0) c.begin_day() var t := 0.0 var trips := 0 var walking := 0.0 var gathering := 0.0 var done_at := -1.0 while c.is_daytime(): var me := Vector2(_player.global_position.x, _player.global_position.z) var target: GatherNode = null var best := INF for n in it.nodes: var d := Vector2(n.global_position.x, n.global_position.z).distance_to(me) if it.charges(n) > 0 and d < best: best = d target = n if target == null and r.pouch_total() == 0: done_at = t break var store := target == null or r.pouch_room() < target.yield_amount if store: Input.action_release("interact") _walk_field(drop_off, me) walking += DT if r.pouch_total() == 0: pass else: var at := Vector2(target.global_position.x, target.global_position.z) if at.distance_to(me) > target.reach - 0.1: Input.action_release("interact") _walk_field(_stand_spot(target), me) walking += DT else: Input.action_press("interact") gathering += DT var before := r.pouch_total() _sim.step(DT) if before > 0 and r.pouch_total() == 0: trips += 1 t += DT Input.action_release("interact") var got := {} for m in ResourceStore.MATERIALS: got[m] = int(r.shed[m]) - int(shed_start[m]) print("gather: %s stored in %d trips; everything gathered and stored after %s (day %.0f s + dusk %.0f s)" % [ ResourceStore.describe(got), trips, ("%.0f s" % done_at) if done_at >= 0.0 else "the day ran out", _sim.config.day_length, _sim.config.dusk_length]) print("gather: %.0f s walking, %.0f s gathering" % [walking, gathering]) ## The free spot closest to a gather point (where the bot stands to gather it). func _stand_spot(n: GatherNode) -> Vector2: var nav := _sim.nav var c := Vector2(n.global_position.x, n.global_position.z) var best := c var best_d := INF for cell in nav.free_cells_in(Rect2(c - Vector2.ONE * n.reach, Vector2.ONE * n.reach * 2.0)): var d := nav.cell_center(cell).distance_to(c) if d < best_d: best_d = d best = nav.cell_center(cell) return best ## Walks along the navigation grid toward goal (one distance field per goal cell, cached). func _walk_field(goal: Vector2, me: Vector2) -> void: var nav := _sim.nav var cell := nav.nearest_free(nav.cell_of(goal.x, goal.y)) if not _fields.has(cell): _fields[cell] = nav.distance_field(PackedInt32Array([cell])) var dir := PackedFloat32Array([0.0, 0.0]) if nav.flow_direction(_fields[cell], me.x, me.y, dir): var next := me + Vector2(dir[0], dir[1]) * _player.run_speed * DT _player.global_position = Vector3(next.x, 0.0, next.y) func _guard() -> void: var es := _sim.enemies var loot := _sim.loot var kit := _sim.scarecrow var cfg := _sim.config var me := Vector2(_player.global_position.x, _player.global_position.z) # Most urgent threat: carriers, then thieves taking a crop, then dropped crops, then others. var goal := HOME var best := INF var near := 0 var carrier_near := false var nearest_thief := -1 var nearest_d := INF for d in es.active_count: if es.alive[d] == 0: continue var p := Vector2(es.pos_x[d], es.pos_z[d]) var dist := p.distance_to(me) var urgency := dist match es.state[d]: ThiefBehavior.State.CARRY: urgency -= 40.0 carrier_near = carrier_near or dist < cfg.fear_radius ThiefBehavior.State.STEAL: urgency -= 20.0 if urgency < best: best = urgency goal = p if dist < cfg.fear_radius and es.state[d] != ThiefBehavior.State.FLEE: near += 1 if dist < nearest_d and _sim.nav.line_clear(me.x, me.y, p.x, p.y): nearest_d = dist nearest_thief = d for id in range(1, loot.item_count + 1): if loot.status[id] == LootSystem.Status.DROPPED: var at := loot.position_of(id) var dist := at.distance_to(me) - 10.0 if loot.category[id] == LootSystem.Category.ANIMAL and loot.followers() >= cfg.max_following_animals: continue if dist < best: best = dist goal = at # Lead followers home when no carrier is close. if loot.followers() > 0 and best > -25.0: goal = PEN_INSIDE best = -25.0 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 Input.action_release("patch") if carrier_near or near >= 2: if kit.use_fear() >= 0: _fears += 1 if nearest_thief >= 0 and nearest_d < SHOOT_RANGE: var target := Vector2(es.pos_x[nearest_thief], es.pos_z[nearest_thief]) var reach := _attack(target, me) if nearest_d < reach: return # hold ground and attack rather than walk into it if _sim.combat.weapon == ScarecrowCombat.Weapon.PITCHFORK: goal = target # close in to stab it _walk_toward(goal, me) ## Attacks the thief at target with the best weapons owned: a pumpkin bomb into a crowd of three ## or more when one is ready, and the corn shooter, else the pitchfork (only within its reach). ## Returns the distance it holds ground at. func _attack(target: Vector2, me: Vector2) -> float: var c := _sim.combat var cfg := _sim.config var es := _sim.enemies var crowd := 0 for d in es.active_count: if es.alive[d] == 1 and Vector2(es.pos_x[d], es.pos_z[d]).distance_to(target) <= cfg.bomb_radius: crowd += 1 var far := target.distance_to(me) if crowd >= 3 and c.offhand == ScarecrowCombat.Weapon.PUMPKIN_BOMB and far >= cfg.bomb_min_range and far <= cfg.bomb_range: if c.offhand_toward(target): _shots += 1 if c.equip(ScarecrowCombat.Weapon.CORN_SHOOTER): if c.attack_toward(target): _shots += 1 return 3.0 c.equip(ScarecrowCombat.Weapon.PITCHFORK) if far <= cfg.pitchfork_reach and c.attack_toward(target): _shots += 1 return cfg.pitchfork_reach * 0.8 func _walk_toward(goal: Vector2, me: Vector2) -> void: var inside := _sim.zones.playable.grow(-1.0) # the scarecrow can't leave the farm goal = Vector2(clampf(goal.x, inside.position.x, inside.end.x), clampf(goal.y, inside.position.y, inside.end.y)) if not _sim.nav.line_clear(me.x, me.y, goal.x, goal.y, true) and goal.distance_to(me) > 2.0: _walk_field((goal / 2.0).round() * 2.0, me) # around walls (gates and fences are no wall to it) return var to := goal - me if to.length() < 0.5: return var step := to.normalized() * _player.run_speed * DT var nav := _sim.nav var next := me + step if not nav.is_free(nav.cell_of(next.x, next.y)): next = Vector2(me.x + step.x, me.y) if nav.is_free(nav.cell_of(me.x + step.x, me.y)) else Vector2(me.x, me.y + step.y) if not nav.is_free(nav.cell_of(next.x, next.y)): var side := Vector2(-step.y, step.x) # boxed in: sidestep next = me + side if not nav.is_free(nav.cell_of(next.x, next.y)): return _player.global_position = Vector3(next.x, 0.0, next.y)