diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8a4129a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,20 @@ +# Start here — REDESIGN: EVOLUTION + +Read [docs/AGENT_HANDOFF.md](docs/AGENT_HANDOFF.md) before editing. It is the current continuation entry point; the conversation history is not required. + +## Current assignment boundary + +The owner resumed implementation after the documentation handoff. **FR-01 Road squad kernel is complete in Core and headless scenarios; FR-02 Animated squad slice is next.** Normal Godot play does not yet expose Garrison controls or animation. When assigned to continue, read the kernel contract and add that playable integration. Routine implementation choices within this plan do not require another approval round. + +## Project rules + +- Work on `Ege-redevelop`. Inspect Git status/branch first; preserve existing uncommitted work. Do not switch or rewrite the branch, delete Git metadata, or push/delete remote branches without the owner's explicit instruction. +- Active game: `Redesign-Evolution/`, Godot 4.7.2 .NET presentation with an independent C# simulation. Course restrictions and legacy compatibility requirements are retired. Do not restart the Java audit or engine comparison. +- Current playable slice: twelve-wave Emberwatch Expedition. Road squad simulation exists; its UI/animation, Stoneford, profile unlocks and the frontier map remain pending. The Windows ZIP predates FR-01. Circuits are deferred for reassessment after the squad/map work. +- Source of truth for the next tasks: FR-01–FR-07 in [docs/FRONTIER_CAMPAIGN_PROPOSAL.md](docs/FRONTIER_CAMPAIGN_PROPOSAL.md). The larger roadmap remains in [docs/REDESIGN_EVOLUTION_ROADMAP.md](docs/REDESIGN_EVOLUTION_ROADMAP.md). +- Keep gameplay authority in Core; Godot owns presentation/input/audio. Preserve deterministic tick behavior, atomic commands, pause/speed semantics and the earlier regression scenarios. Do not let animation callbacks determine combat outcomes. +- Deliver small playable slices. Update `docs/DEVELOPMENT_PROGRESS.md`, the task checklist and `docs/AGENT_HANDOFF.md` when a milestone, limitation or next step changes. Distinguish implemented, tested and proposed features. +- Use `dev.cmd` for the documented Windows build/test/run/smoke/export workflow. `.tools/` and `.artifacts/` are ignored local directories and may be absent in another checkout. +- Latest verification: 96 passing tests, existing Godot UI smoke, squad/no-squad command witnesses and earlier regression scenarios. The smoke log contains a sandbox certificate-store diagnostic. Verify the baseline when beginning further implementation; do not claim the older Windows export contains squad work. + +See the handoff for the first patch scope, code entry points, known balance risks, verification commands and a continuation prompt. diff --git a/README.md b/README.md index f6ed2b3..87314da 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,16 @@ # REDESIGN: EVOLUTION -A new PC tower defense game about elemental reactions and connected defenses. Active implementation: Godot 4.7.2 .NET with independent C# simulation. Course requirements and legacy formats are retired. +A PC tower defense game about an arcane frontier, tower specialization and elemental reactions. Active implementation: Godot 4.7.2 .NET with independent C# simulation. Course requirements and legacy formats are retired. + +## Continuing the project? Start here + +**Read [the agent handoff](docs/AGENT_HANDOFF.md).** It contains the current state, exact next task, code entry points, verification commands and a ready-to-paste continuation prompt. Root [AGENTS.md](AGENTS.md) directs repository-aware agents to the same handoff. + +As of 2026-10-21, development has resumed from `856cb2d` on `Ege-redevelop`. **FR-01 road squad simulation is implemented**, with 96 passing tests and the existing Godot UI smoke passing. Its Garrison controls and animations are not yet available in normal play; the next milestone is **FR-02 Animated squad slice**. The existing Windows ZIP predates this kernel work. + +The direction is **road warriors → stronger animation → a second battlefield and persistent map unlocks → mastery/challenges and results graphs**. The [squad kernel contract](docs/ROAD_SQUAD_KERNEL.md) records implemented rules, provisional values and measured balance limitations. The [frontier task checklist](docs/FRONTIER_CAMPAIGN_PROPOSAL.md) tracks the remaining work; Circuits are deferred for reassessment. + +Check Git status before editing and preserve local changes. FR-01 source and documentation changes are currently uncommitted; include them when transferring work to another checkout. ## Play and develop @@ -25,6 +35,8 @@ Active content lives in `Redesign-Evolution/Game/Content/expedition.json` (forma `dev.cmd sim` runs the expedition through ordinary commands. After building, use `dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --balance` for frost/fire/steel and passive controls across seeds 1/7/42; add `--risk` to accept every Overrun. Individual runs accept `--strategy fire --seed 42`. `--roster`, `--evolution` and `--foundation` select the earlier scenarios; `--no-build` verifies defeat. `dev.cmd benchmark` measures reference scans versus spatial queries, not graphics FPS. Automated victories establish feasibility; human difficulty/enjoyment playtesting remains necessary. +Add `--squad` to an expedition CLI run or balance batch to exercise the new Garrison through ordinary commands. This reserves one tower foundation and adds guard contribution/casualty/engagement statistics. It is an early strategy experiment: several previously winning builds lose after this purchase change, so squad balance remains an explicit FR-02 task. + ## Project - `Redesign-Evolution/Core`: independent authoritative simulation. diff --git a/Redesign-Evolution/Core/Definitions.cs b/Redesign-Evolution/Core/Definitions.cs index 317ef09..22a7d4d 100644 --- a/Redesign-Evolution/Core/Definitions.cs +++ b/Redesign-Evolution/Core/Definitions.cs @@ -22,7 +22,8 @@ public sealed record TowerDefinition(string Id, int Cost, int Damage, double Ran double ForkRadius = 0, int ForkDamagePercent = 50); public sealed record EnemyDefinition(string Id, int Health, double Speed, int Bounty, int LeakDamage, int Armor = 0, double ShieldRadius = 0, int ShieldPercent = 0, string Name = "", - HealingDefinition? Healing = null, BossDefinition? Boss = null, int SlowResistancePercent = 0); + HealingDefinition? Healing = null, BossDefinition? Boss = null, int SlowResistancePercent = 0, + MeleeDefinition? Melee = null); public sealed record SpawnGroup(string EnemyId, int Count, int IntervalTicks, int DelayTicks = 0); public sealed record WaveDefinition(string Title, string Briefing, SpawnGroup[] Groups, int ClearGold = 0, int HealthPercent = 100); public sealed record MapDefinition(string Id, string Title, int Width, int Height, int TileSize, @@ -33,7 +34,7 @@ public sealed record MapDefinition(string Id, string Title, int Width, int Heigh public sealed record GameDefinition(int FormatVersion, string Id, int StartingGold, int StartingLives, MapDefinition Map, TowerDefinition[] Towers, EnemyDefinition[] Enemies, WaveDefinition[] Waves, - CombatDefinition? Combat = null, ExpeditionDefinition? Expedition = null) + CombatDefinition? Combat = null, ExpeditionDefinition? Expedition = null, GarrisonDefinition? Garrison = null) { public GameDefinition Copy() => this with { @@ -118,5 +119,6 @@ public void Validate() Require(wave.HealthPercent is >= 25 and <= 300, $"wave {i + 1}: health percentage"); } ExpeditionContent.Validate(this); + SquadContent.Validate(this); } } diff --git a/Redesign-Evolution/Core/Route.cs b/Redesign-Evolution/Core/Route.cs index c7c86f6..4ceb6a6 100644 --- a/Redesign-Evolution/Core/Route.cs +++ b/Redesign-Evolution/Core/Route.cs @@ -23,4 +23,30 @@ public Point At(double distance) i = ~i; return points[i - 1] + (points[i] - points[i - 1]) * ((distance - ends[i - 1]) / (ends[i] - ends[i - 1])); } + + /// Closest authored road point; equal distances prefer earlier route progress. + public double NearestProgress(Point position) + { + var bestDistance = double.PositiveInfinity; + var progress = 0d; + for (var i = 1; i < points.Length; i++) + { + var segment = points[i] - points[i - 1]; + var offset = position - points[i - 1]; + var fraction = Math.Clamp((offset.X * segment.X + offset.Y * segment.Y) / segment.LengthSquared, 0, 1); + var distance = (points[i - 1] + segment * fraction - position).LengthSquared; + if (distance >= bestDistance) continue; + bestDistance = distance; + progress = ends[i - 1] + fraction * (ends[i] - ends[i - 1]); + } + return progress; + } + + public bool TryGetProgress(Point position, out double progress) + { + progress = 0; + if (!double.IsFinite(position.X) || !double.IsFinite(position.Y)) return false; + progress = NearestProgress(position); + return (At(progress) - position).LengthSquared <= 1e-12; + } } diff --git a/Redesign-Evolution/Core/Simulation.Squads.cs b/Redesign-Evolution/Core/Simulation.Squads.cs new file mode 100644 index 0000000..9662f65 --- /dev/null +++ b/Redesign-Evolution/Core/Simulation.Squads.cs @@ -0,0 +1,279 @@ +namespace Redesign.Core; + +public sealed partial class Simulation +{ + private const double RoadTolerance = 1e-6; + private readonly Dictionary guardById = []; + public GarrisonState? Garrison { get; private set; } + + private bool FoundationOccupied(int foundation) => + Garrison?.Foundation == foundation || towers.Any(t => t.Foundation == foundation); + + private CommandResult BuildGarrison(int foundation) + { + if (definition.Garrison is not { } spec) return new(false, "Squads are unavailable in this mission."); + if (Garrison is not null) return new(false, "Only one Garrison can be built per battlefield."); + if (foundation < 0 || foundation >= definition.Map.Foundations.Length) return new(false, "Choose a marked foundation."); + if (FoundationOccupied(foundation)) return new(false, "This foundation is occupied."); + var position = definition.Map.Center(definition.Map.Foundations[foundation]); + var entry = Route.NearestProgress(position); + var access = (Route.At(entry) - position).Length; + if (access > spec.CommandRadius) return new(false, "The road is beyond this Garrison's command radius."); + if (Gold < spec.Cost) return new(false, "Not enough gold."); + + var id = nextId++; + var guards = new GuardState[GarrisonState.SquadSize]; + for (var i = 0; i < guards.Length; i++) + { + guards[i] = new(nextId++, spec.Guard, position, entry, access); + guardById.Add(guards[i].Id, guards[i]); + } + Garrison = new(id, foundation, position, entry, access, spec, guards); + Gold -= spec.Cost; GoldSpent += spec.Cost; + Emit(EventKind.GarrisonBuilt, position, id, spec.Cost); + return new(true, "Three Shieldguards ready. Rally on the road; fallen guards recover between waves.", id); + } + + public bool IsSquadRallyReachable(Point position) => Garrison is { } garrison && + Route.TryGetProgress(position, out var progress) && + garrison.AccessDistance + Math.Abs(progress - garrison.EntryProgress) <= garrison.Definition.CommandRadius + RoadTolerance; + + private CommandResult RallyGuards(Point position) + { + if (Garrison is not { } garrison) return new(false, "Build a Garrison first."); + if (!IsSquadRallyReachable(position)) return new(false, "Choose a road point within the squad's travel radius."); + Route.TryGetProgress(position, out var progress); + if (!garrison.Retreating && Math.Abs(progress - garrison.RallyProgress) <= RoadTolerance) + return new(false, "The squad is already rallying there."); + foreach (var guard in garrison.Guards) ReleaseGuard(guard); + garrison.RallyProgress = progress; garrison.Retreating = false; + Emit(EventKind.SquadRallied, position, garrison.Id); + return new(true, "Rally ordered. Guards release enemies and travel along the road.", garrison.Id); + } + + private CommandResult RetreatGuards() + { + if (Garrison is not { } garrison) return new(false, "Build a Garrison first."); + if (garrison.Retreating) return new(false, "The squad is already retreating."); + foreach (var guard in garrison.Guards) ReleaseGuard(guard); + garrison.Retreating = true; + Emit(EventKind.SquadRetreated, garrison.Position, garrison.Id); + return new(true, "Retreat ordered. No healing or replacements until planning.", garrison.Id); + } + + private static void CancelGuardAttack(GuardState guard) + { + guard.AttackTargetId = 0; guard.AttackAtTick = 0; + // Orders and interrupted attacks never reset the cooldown. + } + + private static void CancelEnemyMelee(EnemyState enemy) + { + enemy.MeleeTargetId = 0; enemy.MeleeAtTick = 0; + } + + private void ReleaseGuard(GuardState guard) + { + if (enemyById.TryGetValue(guard.EngagedEnemyId, out var enemy)) ReleaseEnemyEngagement(enemy); + guard.EngagedEnemyId = 0; + CancelGuardAttack(guard); + } + + private void ReleaseEnemyEngagement(EnemyState enemy) + { + if (enemy.EngagedGuardId == 0) return; + if (guardById.TryGetValue(enemy.EngagedGuardId, out var guard)) + { + guard.EngagedEnemyId = 0; CancelGuardAttack(guard); + Emit(EventKind.Disengaged, guard.Position, guard.Id, destination: enemy.Position); + } + enemy.EngagedGuardId = 0; CancelEnemyMelee(enemy); + } + + private bool ReadyToEngage(GuardState guard) => Garrison is { Retreating: false } garrison && guard.Alive && + guard.OnRoad && guard.EngagedEnemyId == 0 && Math.Abs(guard.RoadProgress - garrison.RallyProgress) <= RoadTolerance; + + private void MoveGuards() + { + if (Garrison is not { } garrison) return; + var entrance = Route.At(garrison.EntryProgress); + foreach (var guard in garrison.Guards) + { + guard.PreviousPosition = guard.Position; + if (!guard.Alive) continue; + if (guard.EngagedEnemyId != 0 && (!enemyById.TryGetValue(guard.EngagedEnemyId, out var opponent) || !opponent.Alive)) + ReleaseGuard(guard); + if (guard.EngagedEnemyId != 0) continue; + var travel = guard.Definition.Speed / TicksPerSecond; + if (garrison.Retreating) + { + if (guard.OnRoad) + { + var distance = Math.Abs(guard.RoadProgress - garrison.EntryProgress); + var step = Math.Min(travel, distance); + guard.RoadProgress += Math.Sign(garrison.EntryProgress - guard.RoadProgress) * step; + travel -= step; + if (distance <= step) { guard.RoadProgress = garrison.EntryProgress; guard.OnRoad = false; } + } + if (!guard.OnRoad) guard.AccessRemaining = Math.Min(garrison.AccessDistance, guard.AccessRemaining + travel); + } + else + { + if (!guard.OnRoad) + { + var step = Math.Min(travel, guard.AccessRemaining); + guard.AccessRemaining -= step; travel -= step; + if (guard.AccessRemaining <= 0) { guard.OnRoad = true; guard.RoadProgress = garrison.EntryProgress; } + } + if (guard.OnRoad) + { + var step = Math.Min(travel, Math.Abs(garrison.RallyProgress - guard.RoadProgress)); + guard.RoadProgress += Math.Sign(garrison.RallyProgress - guard.RoadProgress) * step; + } + } + guard.Position = guard.OnRoad ? Route.At(guard.RoadProgress) : + entrance + (garrison.Position - entrance) * (guard.AccessRemaining / garrison.AccessDistance); + } + } + + // Resolve swept road contact before committing movement so even fast enemies cannot tunnel through a free guard. + private double MoveAgainstGuards(EnemyState enemy, double nextProgress) + { + if (!enemy.Alive || Garrison is not { Retreating: false } garrison || enemy.Definition.Melee is not { Unstoppable: false }) return nextProgress; + if (enemy.EngagedGuardId != 0) return enemy.Progress; + GuardState? selected = null; + var contact = nextProgress; + foreach (var guard in garrison.Guards) + { + if (!ReadyToEngage(guard)) continue; + var reach = guard.Definition.Reach; + if (enemy.Progress > guard.RoadProgress + reach || nextProgress < guard.RoadProgress - reach) continue; + var encounter = Math.Max(enemy.Progress, guard.RoadProgress - reach); + if (selected is null || encounter < contact || encounter == contact && guard.Id < selected.Id) + { selected = guard; contact = encounter; } + } + if (selected is null) return nextProgress; + enemy.EngagedGuardId = selected.Id; selected.EngagedEnemyId = enemy.Id; + Emit(EventKind.Engaged, selected.Position, selected.Id, destination: Route.At(contact)); + return contact; + } + + private static bool InMeleeReach(Point a, Point b, double radius) => (a - b).LengthSquared <= radius * radius + RoadTolerance; + + private void ResolveSquadCombat() + { + if (Garrison is not { } garrison) return; + // Tower, projectile and persistent-effect kills already resolved. Their victims cannot retaliate. + foreach (var guard in garrison.Guards) + { + if (!guard.Alive) continue; + if (guard.EngagedEnemyId != 0) guard.EngagedTicks++; + if (guard.AttackAtTick > 0 && Tick >= guard.AttackAtTick) + { + enemyById.TryGetValue(guard.AttackTargetId, out var victim); + CancelGuardAttack(guard); + if (victim is { Alive: true } && !garrison.Retreating && + InMeleeReach(guard.Position, victim.Position, guard.Definition.Reach)) + { + var healthBefore = victim.Health; + DealDamage(victim, guard.Definition.Damage, guard.Id, DamageKind.Impact); + Emit(EventKind.GuardStruck, guard.Position, guard.Id, healthBefore - victim.Health, destination: victim.Position); + } + } + if (guard.AttackAtTick > 0 || Tick < guard.NextAttackTick || garrison.Retreating || !guard.OnRoad || + Math.Abs(guard.RoadProgress - garrison.RallyProgress) > RoadTolerance) continue; + enemyById.TryGetValue(guard.EngagedEnemyId, out var target); + if (target is null) + { + // Unstoppable enemies can be struck as they pass, but never held. + foreach (var enemy in enemies) + { + if (!enemy.Alive || enemy.Definition.Melee is not { Unstoppable: true } || + !InMeleeReach(guard.Position, enemy.Position, guard.Definition.Reach)) continue; + if (target is null || Preferred(enemy, target, TargetPriority.First, DamageKind.Impact)) target = enemy; + } + } + if (target is not { Alive: true }) continue; + guard.AttackTargetId = target.Id; guard.AttackAtTick = Tick + guard.Definition.WindupTicks; + guard.NextAttackTick = Tick + guard.Definition.CooldownTicks; + Emit(EventKind.GuardAttackStarted, guard.Position, guard.Id, guard.Definition.Damage, destination: target.Position); + } + foreach (var enemy in enemies) + { + if (!enemy.Alive || enemy.Definition.Melee is not { } melee) continue; + if (enemy.MeleeAtTick > 0 && Tick >= enemy.MeleeAtTick) + { + guardById.TryGetValue(enemy.MeleeTargetId, out var victim); + CancelEnemyMelee(enemy); + if (melee.Cleave) + { + // Warning follows the advancing boss; retreat out of its radius before contact. + foreach (var guard in garrison.Guards) + if (guard.Alive && InMeleeReach(guard.Position, enemy.Position, melee.Reach)) HurtGuard(guard, enemy, melee.Damage); + } + else if (victim is { Alive: true } && InMeleeReach(victim.Position, enemy.Position, melee.Reach)) + HurtGuard(victim, enemy, melee.Damage); + } + if (enemy.MeleeAtTick > 0 || Tick < enemy.NextMeleeTick) continue; + guardById.TryGetValue(enemy.EngagedGuardId, out var target); + if (melee.Unstoppable) + { + foreach (var guard in garrison.Guards) + if (guard.Alive && InMeleeReach(guard.Position, enemy.Position, melee.Reach)) { target = guard; break; } + } + if (target is not { Alive: true }) continue; + enemy.MeleeTargetId = target.Id; enemy.MeleeAtTick = Tick + melee.WindupTicks; + enemy.NextMeleeTick = Tick + melee.CooldownTicks; + Emit(EventKind.EnemyMeleeStarted, enemy.Position, enemy.Id, melee.Damage, destination: target.Position, effectId: melee.Cleave ? "cleave" : null); + } + } + + private void HurtGuard(GuardState guard, EnemyState attacker, int amount) + { + var damage = Math.Min(guard.Health, amount); + guard.Health -= damage; + Emit(EventKind.GuardHit, guard.Position, guard.Id, damage, destination: attacker.Position); + if (guard.Alive) return; + ReleaseGuard(guard); Garrison!.Casualties++; + Emit(EventKind.GuardFallen, guard.Position, guard.Id); + } + + private void FinishSquadWave(bool recover) + { + if (Garrison is not { } garrison) return; + foreach (var guard in garrison.Guards) + { + ReleaseGuard(guard); + if (!recover) continue; + guard.Health = guard.Definition.Health; + guard.Position = guard.PreviousPosition = garrison.Position; + guard.OnRoad = false; guard.RoadProgress = garrison.EntryProgress; guard.AccessRemaining = garrison.AccessDistance; + guard.NextAttackTick = 0; + } + foreach (var enemy in enemies) CancelEnemyMelee(enemy); + if (recover) Emit(EventKind.SquadRecovered, garrison.Position, garrison.Id, GarrisonState.SquadSize); + } + + private void WriteSquad(BinaryWriter writer) + { + // Old fixtures without squad content retain their exact digest representation. + if (definition.Garrison is null) return; + writer.Write(Garrison is not null); + if (Garrison is not { } garrison) return; + writer.Write(garrison.Id); writer.Write(garrison.Definition.Id); writer.Write(garrison.Foundation); + writer.Write(garrison.EntryProgress); writer.Write(garrison.AccessDistance); writer.Write(garrison.RallyProgress); writer.Write(garrison.Retreating); + writer.Write(garrison.DamageDealt); writer.Write(garrison.Kills); writer.Write(garrison.Casualties); + foreach (var guard in garrison.Guards) + { + writer.Write(guard.Id); writer.Write(guard.Health); writer.Write(guard.OnRoad); + writer.Write(guard.RoadProgress); writer.Write(guard.AccessRemaining); writer.Write(guard.Position.X); writer.Write(guard.Position.Y); + writer.Write(guard.EngagedEnemyId); writer.Write(guard.AttackTargetId); writer.Write(guard.AttackAtTick); writer.Write(guard.NextAttackTick); + writer.Write(guard.DamageDealt); writer.Write(guard.Kills); writer.Write(guard.EngagedTicks); + } + foreach (var enemy in enemies) + { + writer.Write(enemy.Id); writer.Write(enemy.EngagedGuardId); writer.Write(enemy.MeleeTargetId); + writer.Write(enemy.MeleeAtTick); writer.Write(enemy.NextMeleeTick); + } + } +} diff --git a/Redesign-Evolution/Core/Simulation.cs b/Redesign-Evolution/Core/Simulation.cs index 3d795d5..5c1167a 100644 --- a/Redesign-Evolution/Core/Simulation.cs +++ b/Redesign-Evolution/Core/Simulation.cs @@ -74,7 +74,7 @@ public CommandResult Apply(GameCommand command) case PlaceTower placement: if (placement.Foundation < 0 || placement.Foundation >= definition.Map.Foundations.Length) return new(false, "Choose a marked foundation."); - if (towers.Any(t => t.Foundation == placement.Foundation)) return new(false, "This foundation is occupied."); + if (FoundationOccupied(placement.Foundation)) return new(false, "This foundation is occupied."); if (!towerDefinitions.TryGetValue(placement.TowerId ?? definition.Towers[0].Id, out var spec)) return new(false, "Unknown tower type."); if (Gold < spec.Cost) return new(false, "Not enough gold."); @@ -129,6 +129,9 @@ public CommandResult Apply(GameCommand command) if (Phase != RunPhase.Wave) return new(false, "Pause is available during a wave."); IsPaused = pause.Paused; return new(true, IsPaused ? "Tactical pause — you can still build." : "Defense resumed."); + case PlaceGarrison placement: return BuildGarrison(placement.Foundation); + case RallySquad rally: return RallyGuards(rally.Position); + case RetreatSquad: return RetreatGuards(); case ChooseRelic choice: return ClaimRelic(choice.RelicId); case SetChallenge challenge: if (definition.Expedition is null || Phase != RunPhase.Planning || rewardOffers.Count > 0) @@ -149,13 +152,15 @@ public void Step() enemies.Add(enemy); enemyById.Add(enemy.Id, enemy); PendingSpawns--; } + MoveGuards(); foreach (var enemy in enemies) { PrepareAbility(enemy); enemy.StatusSet.Expire(Tick); enemy.PreviousPosition = enemy.Position; var speed = enemy.Definition.Speed * (enemy.Enraged ? 1 + (enemy.Definition.Boss?.EnrageSpeedPercent ?? 0) / 100d : 1); - enemy.Progress = Math.Min(Route.Length, enemy.Progress + speed * (100 - enemy.SlowPercent) / (100d * TicksPerSecond)); + var nextProgress = Math.Min(Route.Length, enemy.Progress + speed * (100 - enemy.SlowPercent) / (100d * TicksPerSecond)); + enemy.Progress = MoveAgainstGuards(enemy, nextProgress); enemy.Position = Route.At(enemy.Progress); } if (!referenceQueries) spatial.Rebuild(enemies); @@ -218,12 +223,14 @@ public void Step() else projectile.Position += difference * (travel / difference.Length); } ResolvePersistentEffects(); + ResolveSquadCombat(); ResolveEnemyAbilities(); // Resolve deaths first: a killed enemy at the gate cannot also leak. foreach (var enemy in enemies) { if (!enemy.Alive || enemy.Progress < Route.Length) continue; enemy.Alive = false; Leaks++; + ReleaseEnemyEngagement(enemy); Lives = Math.Max(0, Lives - enemy.Definition.LeakDamage); Emit(EventKind.Leaked, enemy.Position, enemy.Id, enemy.Definition.LeakDamage); } @@ -232,6 +239,7 @@ public void Step() if (Lives == 0) { Phase = RunPhase.Defeat; IsPaused = false; + FinishSquadWave(false); Emit(EventKind.Defeat, Route.At(Route.Length)); } else if (PendingSpawns == 0 && enemies.Count == 0) @@ -239,6 +247,7 @@ public void Step() projectiles.Clear(); burningAreas.Clear(); pendingImpacts.Clear(); CompleteWaveRewards(); Phase = WaveNumber == definition.Waves.Length ? RunPhase.Victory : RunPhase.Planning; + FinishSquadWave(Phase == RunPhase.Planning); Emit(Phase == RunPhase.Victory ? EventKind.Victory : EventKind.WaveCleared, Route.At(Route.Length)); } } @@ -266,19 +275,25 @@ private bool Preferred(EnemyState candidate, EnemyState current, TargetPriority (candidate.Progress == current.Progress && candidate.Id < current.Id); } - private void DealDamage(EnemyState enemy, int amount, int towerId, DamageKind kind, + private void DealDamage(EnemyState enemy, int amount, int sourceId, DamageKind kind, AttackKind attack = AttackKind.Bolt, ReactionStatistics? reaction = null) { if (!enemy.Alive) return; + towerHistory.TryGetValue(sourceId, out var tower); + var guard = tower is null ? guardById[sourceId] : null; var afterArmor = kind != DamageKind.Impact ? amount : Math.Max(1, amount - enemy.EffectiveArmor); var afterShield = Math.Max(1, (int)((long)afterArmor * (100 - enemy.ShieldPercent) / 100)); var damage = Math.Min(afterShield, enemy.Health); enemy.Health -= damage; DamageDealt += damage; - var tower = towerHistory[towerId]; tower.DamageDealt += damage; - if (reaction is not null) { reaction.Damage += damage; tower.ReactionDamage += damage; ReactionDamage += damage; } - Emit(EventKind.Hit, enemy.Position, enemy.Id, damage, attack, damageKind: kind); + if (tower is not null) tower.DamageDealt += damage; + else { guard!.DamageDealt += damage; Garrison!.DamageDealt += damage; } + if (reaction is not null) { reaction.Damage += damage; tower!.ReactionDamage += damage; ReactionDamage += damage; } + Emit(EventKind.Hit, enemy.Position, enemy.Id, damage, attack, damageKind: kind, effectId: guard is null ? null : "melee"); if (enemy.Health > 0) return; - enemy.Alive = false; Kills++; tower.Kills++; + enemy.Alive = false; Kills++; + ReleaseEnemyEngagement(enemy); CancelEnemyMelee(enemy); + if (tower is not null) tower.Kills++; + else { guard!.Kills++; Garrison!.Kills++; } Gold += enemy.Definition.Bounty; GoldEarned += enemy.Definition.Bounty; Emit(EventKind.Killed, enemy.Position, enemy.Id, enemy.Definition.Bounty); } @@ -311,6 +326,7 @@ public string Checksum() { writer.Write(p.Id); writer.Write(p.SourceId); writer.Write(p.TargetId); writer.Write(p.Position.X); writer.Write(p.Position.Y); writer.Write(p.AimPosition.X); writer.Write(p.AimPosition.Y); writer.Write(p.Definition.Id); } WriteEffects(writer); WriteExpedition(writer); + WriteSquad(writer); } return Convert.ToHexString(SHA256.HashData(stream.ToArray())).ToLowerInvariant(); } diff --git a/Redesign-Evolution/Core/SquadDefinitions.cs b/Redesign-Evolution/Core/SquadDefinitions.cs new file mode 100644 index 0000000..c6a527b --- /dev/null +++ b/Redesign-Evolution/Core/SquadDefinitions.cs @@ -0,0 +1,51 @@ +namespace Redesign.Core; + +public sealed record GuardDefinition(string Id, string Name, int Health, int Damage, double Speed, + double Reach, int CooldownTicks, int WindupTicks); +public sealed record GarrisonDefinition(string Id, string Name, string Description, int Cost, + double CommandRadius, GuardDefinition Guard); +public sealed record MeleeDefinition(int Damage, double Reach, int CooldownTicks, int WindupTicks, + bool Unstoppable = false, bool Cleave = false); + +internal static class SquadContent +{ + public static void Validate(GameDefinition game) + { + static void Require(bool valid, string field) + { + if (!valid) throw new ArgumentException("Invalid squad content: " + field); + } + static bool Distance(double value) => double.IsFinite(value) && value is > 0 and <= 4096; + static bool Timing(int cooldown, int windup) => cooldown is >= 2 and <= 36000 && windup > 0 && windup < cooldown; + + foreach (var enemy in game.Enemies) + { + if (enemy.Melee is not { } melee) + { + Require(game.Garrison is null, $"enemy '{enemy.Id}' needs explicit melee rules when squads are enabled"); + continue; + } + Require(melee.Damage is > 0 and <= 10000 && Distance(melee.Reach) && Timing(melee.CooldownTicks, melee.WindupTicks), + $"enemy '{enemy.Id}' melee values"); + Require(!melee.Cleave || melee.Unstoppable, $"enemy '{enemy.Id}' cleave requires unstoppable movement"); + Require(enemy.Boss is null || melee.Unstoppable && melee.Cleave, + $"boss '{enemy.Id}' must be unstoppable with a cleave"); + } + if (game.Garrison is not { } garrison) return; + Require(!string.IsNullOrWhiteSpace(garrison.Id) && !string.IsNullOrWhiteSpace(garrison.Name) && + !string.IsNullOrWhiteSpace(garrison.Description) && !game.Towers.Any(t => t.Id == garrison.Id), "garrison identity"); + Require(garrison.Cost is > 0 and <= 10000 && Distance(garrison.CommandRadius), "garrison cost/command radius"); + Require(garrison.Guard is not null, "guard definition"); + if (garrison.Guard is not { } guard) return; + Require(!string.IsNullOrWhiteSpace(guard.Id) && !string.IsNullOrWhiteSpace(guard.Name) && + guard.Health is > 0 and <= 10000 && guard.Damage is > 0 and <= 10000 && + double.IsFinite(guard.Speed) && guard.Speed is > 0 and <= 4096 && Distance(guard.Reach) && + Timing(guard.CooldownTicks, guard.WindupTicks), "guard identity/combat values"); + // A blocker must be close enough for its opponent to retaliate. + Require(game.Enemies.All(e => e.Melee!.Reach >= guard.Reach), "enemy melee reach must cover guard engagement reach"); + var route = new Route(game.Map); + Require(game.Map.Foundations.Any(c => + (route.At(route.NearestProgress(game.Map.Center(c))) - game.Map.Center(c)).Length <= garrison.CommandRadius), + "no foundation can reach the road"); + } +} diff --git a/Redesign-Evolution/Core/SquadState.cs b/Redesign-Evolution/Core/SquadState.cs new file mode 100644 index 0000000..47ff69f --- /dev/null +++ b/Redesign-Evolution/Core/SquadState.cs @@ -0,0 +1,58 @@ +using System.Collections.ObjectModel; + +namespace Redesign.Core; + +public sealed record PlaceGarrison(int Foundation) : GameCommand; +public sealed record RallySquad(Point Position) : GameCommand; +public sealed record RetreatSquad : GameCommand; + +public sealed class GuardState +{ + internal GuardState(int id, GuardDefinition definition, Point position, double entryProgress, double accessDistance) + { + Id = id; Definition = definition; Position = PreviousPosition = position; + RoadProgress = entryProgress; AccessRemaining = accessDistance; Health = definition.Health; + } + + public int Id { get; } + public GuardDefinition Definition { get; } + public int Health { get; internal set; } + public bool Alive => Health > 0; + public Point Position { get; internal set; } + public Point PreviousPosition { get; internal set; } + public bool OnRoad { get; internal set; } + public double RoadProgress { get; internal set; } + public double AccessRemaining { get; internal set; } + public int EngagedEnemyId { get; internal set; } + public int AttackTargetId { get; internal set; } + public long AttackAtTick { get; internal set; } + public long NextAttackTick { get; internal set; } + public long DamageDealt { get; internal set; } + public int Kills { get; internal set; } + public long EngagedTicks { get; internal set; } +} + +public sealed class GarrisonState +{ + public const int SquadSize = 3; + internal GarrisonState(int id, int foundation, Point position, double entryProgress, + double accessDistance, GarrisonDefinition definition, GuardState[] guards) + { + Id = id; Foundation = foundation; Position = position; EntryProgress = RallyProgress = entryProgress; + AccessDistance = accessDistance; Definition = definition; Guards = Array.AsReadOnly(guards); + } + + public int Id { get; } + public int Foundation { get; } + public Point Position { get; } + public GarrisonDefinition Definition { get; } + public double EntryProgress { get; } + public double AccessDistance { get; } + public double RallyProgress { get; internal set; } + public bool Retreating { get; internal set; } + public ReadOnlyCollection Guards { get; } + public long DamageDealt { get; internal set; } + public int Kills { get; internal set; } + public int Casualties { get; internal set; } + public long EngagedTicks => Guards.Sum(g => g.EngagedTicks); +} diff --git a/Redesign-Evolution/Core/State.cs b/Redesign-Evolution/Core/State.cs index ec7d2b4..d05eb46 100644 --- a/Redesign-Evolution/Core/State.cs +++ b/Redesign-Evolution/Core/State.cs @@ -1,7 +1,8 @@ namespace Redesign.Core; public enum RunPhase { Planning, Wave, Victory, Defeat } -public enum EventKind { Built, Sold, Fired, Hit, Killed, Leaked, WaveStarted, WaveCleared, Victory, Defeat, Blast, Upgraded, Reaction, RelicChosen, Healed, Rally, BossEnraged } +public enum EventKind { Built, Sold, Fired, Hit, Killed, Leaked, WaveStarted, WaveCleared, Victory, Defeat, Blast, Upgraded, Reaction, RelicChosen, Healed, Rally, BossEnraged, + GarrisonBuilt, SquadRallied, SquadRetreated, Engaged, Disengaged, GuardAttackStarted, EnemyMeleeStarted, GuardHit, GuardFallen, SquadRecovered, GuardStruck } public readonly record struct GameEvent(long Tick, EventKind Kind, Point Position, int EntityId = 0, long Amount = 0, AttackKind Attack = AttackKind.Bolt, Point? Destination = null, DamageKind DamageKind = DamageKind.Impact, string? EffectId = null); @@ -51,6 +52,10 @@ public sealed class EnemyState(int id, Point position, EnemyDefinition definitio public bool WindingUp { get; internal set; } public bool Enraged { get; internal set; } public int SummonsCreated { get; internal set; } + public int EngagedGuardId { get; internal set; } + public int MeleeTargetId { get; internal set; } + public long MeleeAtTick { get; internal set; } + public long NextMeleeTick { get; internal set; } public bool BossVulnerable => Definition.Boss is { } boss && (WindingUp || SummonsCreated >= boss.MaxSummons); public bool IsSupport => Definition.ShieldRadius > 0 || Definition.Healing is not null; internal StatusSet StatusSet { get; } = new(); diff --git a/Redesign-Evolution/Game/ArenaCanvas.Squads.cs b/Redesign-Evolution/Game/ArenaCanvas.Squads.cs new file mode 100644 index 0000000..d6733dc --- /dev/null +++ b/Redesign-Evolution/Game/ArenaCanvas.Squads.cs @@ -0,0 +1,197 @@ +using Godot; +using Redesign.Core; + +namespace Redesign.Game; + +public enum GuardPose { Idle, Walk, Anticipate, Contact, Recover, Defend, Hurt, Fallen } + +public partial class ArenaCanvas +{ + private Vector2? previewPointer; + private readonly Dictionary guardPoses = []; + private sealed class GuardFeedback + { + public long StruckAt = -1000, HurtAt = -1000, FallenAt = -1000; + public Vector2 Facing = Vector2.Left; + } + // The same interpolated clock drives movement, poses, impacts and warnings. Pause freezes all four. + public double PresentationTick => Game.Run.Tick == 0 ? 0 : Game.Run.Tick - 1 + Game.Alpha; + + public void SetPreviewPointer(Vector2 position) { previewPointer = position; hover = FoundationAt(position); } + + private void ReceiveSquadEvent(GameEvent e) + { + if (e.Kind == EventKind.SquadRecovered) { guardPoses.Clear(); return; } + if (e.Kind is not (EventKind.GuardAttackStarted or EventKind.GuardStruck or EventKind.GuardHit or EventKind.GuardFallen)) return; + if (!guardPoses.TryGetValue(e.EntityId, out var feedback)) guardPoses[e.EntityId] = feedback = new(); + if (e.Destination is { } target && (target - e.Position).LengthSquared > .001) + feedback.Facing = V(target - e.Position).Normalized(); + if (e.Kind == EventKind.GuardStruck) feedback.StruckAt = e.Tick; + if (e.Kind == EventKind.GuardHit) feedback.HurtAt = e.Tick; + if (e.Kind == EventKind.GuardFallen) feedback.FallenAt = e.Tick; + } + + public GuardPose PoseFor(GuardState guard) + { + guardPoses.TryGetValue(guard.Id, out var feedback); + if (!guard.Alive) return GuardPose.Fallen; + if (feedback is not null && PresentationTick - feedback.HurtAt < 10) return GuardPose.Hurt; + if ((guard.Position - guard.PreviousPosition).LengthSquared > .0001) return GuardPose.Walk; + if (guard.AttackAtTick > Game.Run.Tick) return GuardPose.Anticipate; + if (feedback is not null && PresentationTick - feedback.StruckAt < 6) return GuardPose.Contact; + if (feedback is not null && PresentationTick - feedback.StruckAt < 19) return GuardPose.Recover; + var enemy = Game.Run.Enemies.FirstOrDefault(e => e.Id == guard.EngagedEnemyId); + if (enemy?.MeleeAtTick > Game.Run.Tick) return GuardPose.Defend; + return GuardPose.Idle; + } + + // Small formation offsets separate the three silhouettes. They never change collision or reach. + public Vector2 GuardVisualPosition(GuardState guard) + { + var garrison = Game.Run.Garrison!; + var slot = garrison.Guards.ToList().IndexOf(guard) - 1; + var tangent = V(Game.Run.Route.At(guard.RoadProgress + 1) - Game.Run.Route.At(guard.RoadProgress - 1)).Normalized(); + var side = new Vector2(-tangent.Y, tangent.X); + return V(guard.PreviousPosition).Lerp(V(guard.Position), (float)Game.Alpha) + side * slot * 19 + tangent * Math.Abs(slot) * 4; + } + + private GuardState? GuardAt(Vector2 position) => Game.Run.Garrison?.Guards + .OrderBy(g => GuardVisualPosition(g).DistanceSquaredTo(position)) + .FirstOrDefault(g => GuardVisualPosition(g).DistanceSquaredTo(position) < 18 * 18); + + private void DrawSquadOrders() + { + var garrison = Game.Run.Garrison; + var placing = Game.BuildingGarrison && hover >= 0 && !Game.Run.Towers.Any(t => t.Foundation == hover) && garrison is null; + if (!placing && !(Game.GarrisonSelected && garrison is not null)) return; + var position = placing ? Game.Content.Map.Center(Game.Content.Map.Foundations[hover]) : garrison!.Position; + var entry = Game.Run.Route.NearestProgress(position); + var access = (Game.Run.Route.At(entry) - position).Length; + var budget = Game.Content.Garrison!.CommandRadius - access; + if (budget >= 0) + { + var start = Math.Max(0, entry - budget); var end = Math.Min(Game.Run.Route.Length, entry + budget); + // Include each bend exactly; sampling alone would visually cut road corners. + var marks = Game.Content.Map.Route.Select(Game.Content.Map.Center).Select(Game.Run.Route.NearestProgress) + .Where(d => d > start && d < end).Prepend(start).Append(end); + var path = marks.Select(d => V(Game.Run.Route.At(d))).ToArray(); + DrawPolyline(path, new Color(GameRoot.Mint, .12f), 48, true); + DrawPolyline(path, new Color(GameRoot.Mint, .85f), 2, true); + foreach (var d in new[] { start, end }) DrawCircle(V(Game.Run.Route.At(d)), 5, GameRoot.Mint); + } + DrawDashedLine(V(position), V(Game.Run.Route.At(entry)), new Color(GameRoot.Mint, .7f), 2, 7); + if (garrison is not null) + { + var rally = V(Game.Run.Route.At(garrison.RallyProgress)); + var tint = garrison.Retreating ? GameRoot.Muted : GameRoot.Mint; + DrawArc(rally, 14, 0, Mathf.Tau, 24, tint, 2, true); + DrawLine(rally, rally + new Vector2(0, -35), tint, 2, true); + DrawColoredPolygon([rally + new Vector2(1, -35), rally + new Vector2(18, -29), rally + new Vector2(1, -23)], tint); + } + if (Game.Rallying && previewPointer is { } pointer) + { + var onRoad = Game.TryRoadPointer(pointer, out var destination); + var reachable = onRoad && Game.Run.IsSquadRallyReachable(destination); + var p = onRoad ? V(destination) : pointer; + var tint = reachable ? GameRoot.Mint : GameRoot.Red; + DrawArc(p, 22, 0, Mathf.Tau, 32, tint, 2, true); + DrawLine(p + new Vector2(-7, -7), p + new Vector2(7, 7), tint, 2); + DrawLine(p + new Vector2(-7, 7), p + new Vector2(7, -7), tint, 2); + var label = reachable ? "RALLY HERE" : onRoad ? "BEYOND REACH" : "CHOOSE THE ROAD"; + var labelAt = new Vector2(Math.Clamp(p.X - 70, 8, 800), Math.Clamp(p.Y + 40, 90, 550)); + DrawRect(new(labelAt + new Vector2(-7, -18), new(158, 25)), new Color(GameRoot.Ink, .95f)); + DrawString(font, labelAt, label, HorizontalAlignment.Left, -1, 13, tint); + } + } + + private void DrawGarrison() + { + if (Game.Run.Garrison is not { } garrison) return; + var p = V(garrison.Position); + DrawEllipseShadow(p + new Vector2(0, 13), 31); + DrawRect(new(p.X - 25, p.Y - 12, 50, 30), new Color("596b62")); + DrawRect(new(p.X - 20, p.Y - 9, 40, 26), new Color("a8ac88")); + DrawColoredPolygon([p + new Vector2(-30, -12), p + new Vector2(0, -35), p + new Vector2(30, -12)], new("264b50")); + DrawLine(p + new Vector2(-30, -12), p + new Vector2(0, -35), GameRoot.Mint, 3); + DrawRect(new(p.X - 8, p.Y - 5, 16, 24), new Color("172e32")); + DrawLine(p + new Vector2(21, 5), p + new Vector2(21, -40), new("d4c998"), 2); + DrawColoredPolygon([p + new Vector2(22, -40), p + new Vector2(36, -35), p + new Vector2(22, -25)], GameRoot.Mint); + DrawString(font, p + new Vector2(-6, 10), "G", HorizontalAlignment.Left, -1, 13, GameRoot.Mint); + if (Game.GarrisonSelected) DrawArc(p, 35, 0, Mathf.Tau, 40, GameRoot.Mint, 2, true); + } + + private void DrawGuards() + { + if (Game.Run.Garrison is not { } garrison) return; + foreach (var guard in garrison.Guards.OrderBy(g => GuardVisualPosition(g).Y)) + { + var p = GuardVisualPosition(guard); var pose = PoseFor(guard); + guardPoses.TryGetValue(guard.Id, out var feedback); + var enemy = Game.Run.Enemies.FirstOrDefault(e => e.Id == guard.EngagedEnemyId); + var facing = enemy is null ? feedback?.Facing ?? Vector2.Left : (V(enemy.Position) - p).Normalized(); + if (pose == GuardPose.Walk) facing = V(guard.Position - guard.PreviousPosition).Normalized(); + DrawEllipseShadow(p + new Vector2(0, 9), 12); + if (pose == GuardPose.Fallen) + { + var fall = feedback is null ? 1 : Math.Clamp((float)(PresentationTick - feedback.FallenAt) / 16, 0, 1); + DrawLine(p + new Vector2(-8 * fall, -13 * (1 - fall)), p + new Vector2(10, 5), new("688181"), 7); + DrawCircle(p + new Vector2(-11 * fall, -14 * (1 - fall)), 5, new("8a9c95")); + DrawLine(p + new Vector2(2, -7), p + new Vector2(13, -11), new("a7b6ac"), 2); + DrawString(font, p + new Vector2(-5, 22), "+", HorizontalAlignment.Left, -1, 14, GameRoot.Muted); + continue; + } + if (Game.GarrisonSelected) DrawArc(p + new Vector2(0, 8), 14, 0, Mathf.Tau, 24, new Color(GameRoot.Mint, .7f), 1, true); + if (enemy is not null) DrawLine(p + new Vector2(0, 8), V(enemy.Position) + new Vector2(0, 8), new Color(GameRoot.Gold, .6f), 1, true); + var stride = pose == GuardPose.Walk ? MathF.Sin((float)PresentationTick * .35f + guard.Id) * 4 : 0; + var lunge = pose == GuardPose.Contact ? facing * 6 : pose == GuardPose.Hurt ? -facing * 3 : Vector2.Zero; + p += lunge; + DrawLine(p + new Vector2(-4, 0), p + new Vector2(-5, 10 + stride), new("1c2e37"), 4); + DrawLine(p + new Vector2(4, 0), p + new Vector2(5, 10 - stride), new("1c2e37"), 4); + DrawColoredPolygon([p + new Vector2(-7, -13), p + new Vector2(7, -13), p + new Vector2(10, 5), p + new Vector2(-10, 5)], new("327b74")); + DrawRect(new(p.X - 6, p.Y - 12, 12, 13), pose == GuardPose.Hurt ? GameRoot.Red : new Color("c5d6cc")); + DrawCircle(p + new Vector2(0, -19), 7, new("748f91")); + DrawLine(p + new Vector2(-5, -20), p + new Vector2(5, -20), new("d8e5db"), 2); + DrawRect(new(p.X - 4, p.Y - 17, 8, 3), new Color("173237")); + var shield = p + new Vector2(facing.X >= 0 ? 9 : -9, pose == GuardPose.Defend ? -13 : -5); + DrawColoredPolygon([shield + new Vector2(-6, -7), shield + new Vector2(6, -7), shield + new Vector2(5, 5), shield + new Vector2(0, 9), shield + new Vector2(-5, 5)], new("1c4b51")); + DrawLine(shield + new Vector2(0, -5), shield + new Vector2(0, 5), GameRoot.Mint, 2); + var hand = p + new Vector2(facing.X >= 0 ? -6 : 6, -7); + var blade = pose == GuardPose.Anticipate ? new Vector2(-facing.X * 6, -22) : pose == GuardPose.Contact ? facing * 27 : new Vector2(facing.X * 12, -14); + DrawLine(hand, hand + blade, new("1b3038"), 5, true); + DrawLine(hand, hand + blade, new("e5e9d0"), 2, true); + if (pose == GuardPose.Contact) DrawArc(p, 27, facing.Angle() - .6f, facing.Angle() + .6f, 12, new Color(GameRoot.Gold, .8f), 2, true); + DrawRect(new(p.X - 12, p.Y - 33, 24, 5), GameRoot.Ink); + DrawRect(new(p.X - 11, p.Y - 32, 22f * guard.Health / guard.Definition.Health, 3), guard.Health <= guard.Definition.Health / 3 ? GameRoot.Red : GameRoot.Mint); + if (Game.Run.Enemies.Any(e => e.Definition.Melee is { Cleave: true } m && e.MeleeAtTick > Game.Run.Tick && (e.Position - guard.Position).LengthSquared <= m.Reach * m.Reach)) + DrawString(font, p + new Vector2(-3, -38), "!", HorizontalAlignment.Left, -1, 18, GameRoot.Red); + } + } + + private void DrawCleaveWarnings() + { + foreach (var enemy in Game.Run.Enemies) + { + if (enemy.Definition.Melee is not { Cleave: true } melee || enemy.MeleeAtTick <= Game.Run.Tick) continue; + var p = V(enemy.PreviousPosition).Lerp(V(enemy.Position), (float)Game.Alpha); + var radius = (float)melee.Reach; + var progress = Math.Clamp(1 - (float)(enemy.MeleeAtTick - PresentationTick) / melee.WindupTicks, 0, 1); + DrawCircle(p, radius, new Color(GameRoot.Red, .12f + progress * .12f)); + DrawArc(p, radius, 0, Mathf.Tau, 64, GameRoot.Red, 2, true); + DrawArc(p, radius - 5, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * progress, 48, new("fff2cd"), 3, true); + for (var i = 0; i < 12; i++) + { + var d = Vector2.FromAngle(i * Mathf.Tau / 12); + DrawLine(p + d * (radius - 12), p + d * radius, new Color(GameRoot.Red, .8f), 2, true); + } + DrawRect(new(270, 76, 420, 31), new Color(GameRoot.Ink, .97f)); + DrawString(font, new(283, 98), $"CLEAVE IN {(enemy.MeleeAtTick - Game.Run.Tick) / 60d:0.0}s / RETREAT [H]", HorizontalAlignment.Left, -1, 17, GameRoot.Red); + } + } + + private void DrawEnemyMelee(EnemyState enemy, Vector2 p) + { + if (enemy.Definition.Melee is not { Cleave: false } melee || enemy.MeleeAtTick <= Game.Run.Tick) return; + var progress = Math.Clamp(1 - (float)(enemy.MeleeAtTick - PresentationTick) / melee.WindupTicks, 0, 1); + DrawArc(p + new Vector2(0, 3), 24, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * progress, 24, new Color(GameRoot.Red, .9f), 2, true); + } +} diff --git a/Redesign-Evolution/Game/ArenaCanvas.cs b/Redesign-Evolution/Game/ArenaCanvas.cs index e5f55d4..feaf1ef 100644 --- a/Redesign-Evolution/Game/ArenaCanvas.cs +++ b/Redesign-Evolution/Game/ArenaCanvas.cs @@ -13,7 +13,7 @@ public partial class ArenaCanvas : Control private double visualTime; private Font font = null!; private Vector2[] drawnRoute = []; - private sealed class VisualEffect(GameEvent e) { public GameEvent Event = e; public float Age; } + private sealed class VisualEffect(GameEvent e) { public GameEvent Event = e; public float Age; public float RestAge; } public override void _Ready() { font = ThemeDB.FallbackFont; @@ -25,13 +25,13 @@ public override void _Ready() for (var c = a; ; c = new(c.X + dx, c.Y + dy)) { road.Add(c); if (c == b) break; } } GuiInput += HandleInput; - MouseExited += () => hover = -1; + MouseExited += () => { hover = -1; previewPointer = null; }; } private void HandleInput(InputEvent e) { if (e is InputEventMouseMotion motion) { - hover = FoundationAt(motion.Position); + SetPreviewPointer(motion.Position); var enemy = Game.Run.Enemies.FirstOrDefault(enemy => V(enemy.Position).DistanceSquaredTo(motion.Position) < 24 * 24); TooltipText = enemy is null ? "" : $"{enemy.Definition.Name}: {enemy.Health}/{enemy.Definition.Health} health, {enemy.EffectiveArmor} armor, {enemy.SlowPercent}% slow.\n" + (enemy.Definition.ShieldRadius > 0 @@ -43,11 +43,21 @@ private void HandleInput(InputEvent e) TooltipText += $"\nMends {heal.Amount} health in radius {heal.Radius:0} every {heal.IntervalTicks / 60d:0.0}s. Kill it before its green ring completes."; if (enemy?.Definition.Boss is { } boss) TooltipText += $"\n{(enemy.BossVulnerable ? "EXPOSED: no armor or personal guard." : $"Guarded: {boss.GuardPercent}% damage reduction.")}\nRallies {boss.SummonsPerPulse} Raiders; {boss.MaxSummons - enemy.SummonsCreated} remain. Half-health enrage doubles rally frequency."; + var guard = GuardAt(motion.Position); + if (guard is not null) TooltipText = $"Shieldguard: {guard.Health}/{guard.Definition.Health} HP. Holds one enemy; extra enemies pass.\nClick to select the squad. Rally [F], retreat [H]. Recovery between waves only."; } + if (Game.OrdersBlocked) return; + if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Right }) + { Game.CancelOrders(); AcceptEvent(); return; } if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) { - var index = FoundationAt(click.Position); - if (index >= 0) Game.SelectFoundation(index); + if (Game.Rallying) Game.RallyAtPointer(click.Position); + else + { + var index = FoundationAt(click.Position); + if (index >= 0) Game.SelectFoundation(index); + else if (GuardAt(click.Position) is not null) Game.SelectGarrison(); + } AcceptEvent(); } } @@ -59,14 +69,19 @@ public int FoundationAt(Vector2 position) } public void Receive(GameEvent e) { + ReceiveSquadEvent(e); if (e.Kind is EventKind.Hit or EventKind.Killed or EventKind.Leaked or EventKind.Built or EventKind.Fired or EventKind.Blast or EventKind.Reaction or EventKind.Upgraded or EventKind.Healed or EventKind.Rally or EventKind.BossEnraged) { if (effects.Count == 160) effects.RemoveAt(0); effects.Add(new(e)); } } - public void ClearEffects() { effects.Clear(); hover = -1; } + public void ClearEffects() { effects.Clear(); guardPoses.Clear(); hover = -1; previewPointer = null; } public override void _Process(double delta) { visualTime += delta; - foreach (var e in effects) e.Age += (float)delta; + foreach (var e in effects) + { + if (Game.Run.Phase != RunPhase.Wave) e.RestAge += (float)delta; + e.Age = Math.Max(0, (float)(PresentationTick - e.Event.Tick) / 60) + e.RestAge; + } effects.RemoveAll(e => e.Age > .85f); } public override void _Draw() @@ -97,6 +112,8 @@ public override void _Draw() } TerrainEffects(); AbilityTelegraphs(); + DrawSquadOrders(); + DrawCleaveWarnings(); DrawString(font, new(8, 292), "INBOUND", HorizontalAlignment.Left, -1, 12, GameRoot.Gold); DrawLine(new(10, 307), new(44, 307), GameRoot.Gold, 2); DrawLine(new(36, 301), new(44, 307), GameRoot.Gold, 2); @@ -104,7 +121,7 @@ public override void _Draw() for (var i = 0; i < map.Foundations.Length; i++) { var p = V(map.Center(map.Foundations[i])); - var occupied = Game.Run.Towers.Any(t => t.Foundation == i); + var occupied = Game.Run.Towers.Any(t => t.Foundation == i) || Game.Run.Garrison?.Foundation == i; DrawRect(new(p.X - 23, p.Y - 15, 46, 36), new Color("132a28")); DrawRect(new(p.X - 21, p.Y - 19, 42, 36), new Color("5b6d60")); DrawRect(new(p.X - 17, p.Y - 15, 34, 28), new Color("394e47")); @@ -120,7 +137,7 @@ public override void _Draw() var selected = Game.Run.Towers.FirstOrDefault(t => t.Id == Game.SelectedTower); Vector2? range = selected is null ? null : V(selected.Position); var rangeSpec = selected?.Definition ?? Game.BuildDefinition; - if (Game.Building && hover >= 0) + if (Game.Building && !Game.BuildingGarrison && hover >= 0) { range = V(map.Center(map.Foundations[hover])); rangeSpec = Game.BuildDefinition; } @@ -139,6 +156,7 @@ public override void _Draw() } Castle(V(map.Center(map.Route[^1]))); foreach (var tower in Game.Run.Towers) Tower(tower); + DrawGarrison(); foreach (var enemy in Game.Run.Enemies) if (!enemy.IsSupport && enemy.Definition.Boss is null) Enemy(enemy); // Keep escort silhouettes/staves readable when fast units overlap their formation. @@ -146,6 +164,7 @@ public override void _Draw() if (enemy.IsSupport && enemy.Definition.Boss is null) Enemy(enemy); foreach (var enemy in Game.Run.Enemies) if (enemy.Definition.Boss is not null) Enemy(enemy); + DrawGuards(); foreach (var shot in Game.Run.Projectiles) { var p = V(shot.PreviousPosition).Lerp(V(shot.Position), (float)Game.Alpha); @@ -169,7 +188,7 @@ private void Enemy(EnemyState enemy) { var p = V(enemy.PreviousPosition).Lerp(V(enemy.Position), (float)Game.Alpha); var spec = enemy.Definition; - var stride = MathF.Sin((float)(Game.Run.Tick * .3 + enemy.Id)) * 3; + var stride = enemy.EngagedGuardId == 0 ? MathF.Sin((float)(PresentationTick * .3 + enemy.Id)) * 3 : 0; DrawEllipseShadow(p + new Vector2(0, 9), spec.Armor > 0 ? 20 : 15); DrawLine(p + new Vector2(-8, 3), p + new Vector2(-13, 12 + stride), new("262433"), 4); DrawLine(p + new Vector2(8, 3), p + new Vector2(13, 12 - stride), new("262433"), 4); @@ -226,6 +245,7 @@ private void Enemy(EnemyState enemy) DrawString(font, p + new Vector2(-5, -39), "+", HorizontalAlignment.Left, -1, 14, new("e0cef7")); } EnemyStatuses(enemy, p); + DrawEnemyMelee(enemy, p); } private void Tower(TowerState tower) diff --git a/Redesign-Evolution/Game/AudioCues.cs b/Redesign-Evolution/Game/AudioCues.cs index 23c88bf..6f9366e 100644 --- a/Redesign-Evolution/Game/AudioCues.cs +++ b/Redesign-Evolution/Game/AudioCues.cs @@ -11,6 +11,8 @@ public partial class AudioCues : Node private readonly Dictionary attacks = []; private readonly Dictionary reactions = []; private ulong lastReaction; + private ulong lastMelee; + private AudioStreamWav cleave = null!; private int nextVoice; private readonly ulong[] lastShot = new ulong[3]; public bool Muted { get; set; } @@ -27,6 +29,12 @@ public override void _Ready() sounds[EventKind.RelicChosen] = Tone(720, .45, .7); sounds[EventKind.Rally] = Tone(105, .4, -.2); sounds[EventKind.BossEnraged] = Tone(180, .5, -.7); + sounds[EventKind.GarrisonBuilt] = Tone(360, .24, .7); + sounds[EventKind.SquadRallied] = Tone(620, .12, .3); + sounds[EventKind.SquadRetreated] = Tone(460, .16, -.5); + sounds[EventKind.GuardStruck] = Tone(1150, .06, -.9); + sounds[EventKind.GuardFallen] = Tone(240, .24, -.6); + cleave = Tone(95, .5, .5); reactions["shatter"] = Tone(1350, .15, -.8); reactions["ignition"] = Tone(130, .24, .8); sounds[EventKind.Leaked] = Tone(150, .22, -.3); @@ -50,7 +58,14 @@ public void Receive(GameEvent e) var now = Time.GetTicksMsec(); if (now - lastReaction < 100) return; lastReaction = now; } + else if (e.Kind == EventKind.EnemyMeleeStarted && e.EffectId == "cleave") sound = cleave; else if (!sounds.TryGetValue(e.Kind, out sound)) return; + if (e.Kind is EventKind.GuardStruck or EventKind.GuardFallen) + { + var now = Time.GetTicksMsec(); + if (now - lastMelee < 100) return; + lastMelee = now; + } var voice = voices[nextVoice++ % voices.Length]; voice.Stream = sound; voice.Play(); } public void StopAll() { foreach (var voice in voices) voice.Stop(); } diff --git a/Redesign-Evolution/Game/Content/expedition.json b/Redesign-Evolution/Game/Content/expedition.json index 1f2b7d0..357d5ec 100644 --- a/Redesign-Evolution/Game/Content/expedition.json +++ b/Redesign-Evolution/Game/Content/expedition.json @@ -3,6 +3,23 @@ "id": "emberwatch-expedition-v1", "startingGold": 180, "startingLives": 12, + "garrison": { + "id": "garrison", + "name": "Shieldguard Garrison", + "description": "Three guards hold one enemy each. Rally along the road or retreat; recover only between waves. One permanent foundation per run.", + "cost": 120, + "commandRadius": 230, + "guard": { + "id": "shieldguard", + "name": "Shieldguard", + "health": 80, + "damage": 8, + "speed": 100, + "reach": 20, + "cooldownTicks": 60, + "windupTicks": 15 + } + }, "map": { "id": "emberwatch", "title": "Emberwatch", @@ -478,6 +495,7 @@ { "id": "runner", "name": "Runner", + "melee": { "damage": 8, "reach": 24, "cooldownTicks": 60, "windupTicks": 20 }, "health": 55, "bounty": 2, "leakDamage": 1, @@ -486,6 +504,7 @@ { "id": "bulwark", "name": "Bulwark", + "melee": { "damage": 20, "reach": 24, "cooldownTicks": 90, "windupTicks": 30 }, "health": 180, "bounty": 5, "leakDamage": 2, @@ -494,6 +513,7 @@ }, { "id": "warden", + "melee": { "damage": 10, "reach": 24, "cooldownTicks": 60, "windupTicks": 20 }, "leakDamage": 2, "shieldRadius": 100, "speed": 43, @@ -505,6 +525,7 @@ { "id": "mender", "name": "Mender", + "melee": { "damage": 6, "reach": 24, "cooldownTicks": 90, "windupTicks": 30 }, "health": 135, "bounty": 6, "healing": { @@ -519,6 +540,7 @@ { "id": "raider", "name": "Raider", + "melee": { "damage": 10, "reach": 24, "cooldownTicks": 42, "windupTicks": 14 }, "health": 65, "bounty": 0, "leakDamage": 1, @@ -526,6 +548,7 @@ }, { "id": "captain", + "melee": { "damage": 40, "reach": 28, "cooldownTicks": 90, "windupTicks": 30 }, "health": 400, "leakDamage": 3, "slowResistancePercent": 25, @@ -537,6 +560,7 @@ { "armor": 20, "id": "bellwarden", + "melee": { "damage": 70, "reach": 76, "cooldownTicks": 180, "windupTicks": 60, "unstoppable": true, "cleave": true }, "boss": { "maxSummons": 12, "intervalTicks": 300, diff --git a/Redesign-Evolution/Game/GameRoot.Evolution.cs b/Redesign-Evolution/Game/GameRoot.Evolution.cs index 7581af8..e6aa871 100644 --- a/Redesign-Evolution/Game/GameRoot.Evolution.cs +++ b/Redesign-Evolution/Game/GameRoot.Evolution.cs @@ -35,7 +35,7 @@ private void OpenEvolution() BranchChoices = Content.Combat?.Branches.Where(b => b.TowerId == tower.FamilyId).ToArray() ?? []; if (BranchChoices.Length == 0) return; if (Run.Phase == RunPhase.Wave) Run.Apply(new Pause(true)); - Building = false; + Building = false; ClearSquadSelection(); evolutionTitle.Text = $"EVOLVE / {tower.Definition.Name.ToUpperInvariant()}"; evolutionHint.Text = $"{Run.Gold} gold available. Choose one permanent specialization for this tower.\n" + (Run.Phase == RunPhase.Wave ? "Battle paused. After choosing or closing, press Space to resume." : "Paths change how a tower fights. Pair a setup tower with a finisher."); diff --git a/Redesign-Evolution/Game/GameRoot.Expedition.cs b/Redesign-Evolution/Game/GameRoot.Expedition.cs index 68d34f3..03d3f6d 100644 --- a/Redesign-Evolution/Game/GameRoot.Expedition.cs +++ b/Redesign-Evolution/Game/GameRoot.Expedition.cs @@ -54,7 +54,7 @@ private void OpenRelicReview() } private void ShowRelics(bool choosing) { - EvolutionPanel.Visible = false; Building = false; + EvolutionPanel.Visible = false; Building = false; ClearSquadSelection(); var offers = choosing ? Run.RewardOffers : Run.Relics; rewardTitle.Text = choosing ? $"WAVE {Run.WaveNumber} HELD / CLAIM A RELIC" : "YOUR EXPEDITION / RELICS"; rewardHint.Text = choosing ? "Choose one. It lasts for this run and changes existing and future towers. The other two are left behind.\n" + diff --git a/Redesign-Evolution/Game/GameRoot.Squads.cs b/Redesign-Evolution/Game/GameRoot.Squads.cs new file mode 100644 index 0000000..2c01279 --- /dev/null +++ b/Redesign-Evolution/Game/GameRoot.Squads.cs @@ -0,0 +1,139 @@ +using Godot; +using Redesign.Core; +using Redesign.Infrastructure; + +namespace Redesign.Game; + +public partial class GameRoot +{ + public Button GarrisonButton { get; private set; } = null!; + public Button RallyButton { get; private set; } = null!; + public Button RetreatButton { get; private set; } = null!; + public bool BuildingGarrison { get; private set; } + public bool GarrisonSelected { get; private set; } + public bool Rallying { get; private set; } + public bool OrdersBlocked => EvolutionPanel.Visible || RewardPanel.Visible || Run.Phase is RunPhase.Victory or RunPhase.Defeat; + + private void BuildSquadInterface() + { + GarrisonButton = AddButton(this, "GARRISON [G]", new(1224, 374), new(164, 72), ChooseGarrison); + GarrisonButton.AddThemeFontSizeOverride("font_size", 13); + RallyButton = AddButton(this, "RALLY ON ROAD [F]", new(1052, 612), new(336, 36), BeginRally); + RetreatButton = AddButton(this, "RETREAT TO GARRISON [H]", new(1052, 658), new(336, 36), OrderRetreat); + RallyButton.TooltipText = "Choose a reachable road point. Travel releases enemies and takes time. Orders can be issued while paused."; + RetreatButton.TooltipText = "Release enemies and return to the Garrison. No healing or replacements during a wave. Rally again to redeploy."; + } + + private void RefreshSquadInterface(bool ended) + { + var garrison = Run.Garrison; + GarrisonButton.Visible = Content.Garrison is not null; + GarrisonButton.Disabled = ended; + var living = garrison?.Guards.Count(g => g.Alive) ?? 0; + GarrisonButton.Text = garrison is null ? $"GARRISON [G]\n{Content.Garrison?.Cost} G / Hold the road" : $"SHIELDGUARDS [G]\n{living}/3 ready / Select"; + GarrisonButton.Modulate = GarrisonSelected || BuildingGarrison ? Mint : garrison is not null || Run.Gold >= Content.Garrison?.Cost ? Colors.White : Muted; + GarrisonButton.TooltipText = $"One permanent foundation, {Content.Garrison?.Cost} gold; cannot be sold. Three Shieldguards, one enemy each.\n" + + "Extra enemies pass. Full recovery between waves, never during combat. Rally under tower coverage. Melee preserves chill/oil for towers."; + RallyButton.Visible = RetreatButton.Visible = GarrisonSelected && garrison is not null && !ended; + RallyButton.Text = Rallying ? "CHOOSE ROAD / ESC TO CANCEL" : "RALLY ON ROAD [F]"; + RetreatButton.Disabled = garrison?.Retreating == true; + if (BuildingGarrison) + { + detailTitle.Text = $"GARRISON / {Content.Garrison!.Cost} G"; + detailBody.Text = "3 guards / one enemy held per guard\nOne permanent foundation. Cannot be sold.\nHover to preview reachable road.\nRecover only between waves."; + } + else if (GarrisonSelected && garrison is not null) + { + detailTitle.Text = $"SHIELDGUARDS / {living} OF 3 READY"; + var held = garrison.Guards.Count(g => g.EngagedEnemyId != 0); + var state = Run.Phase == RunPhase.Planning ? "Deploy at wave start" : garrison.Retreating ? "Returning to Garrison" : held > 0 ? $"Holding {held} / 3 enemies" : "Following rally orders"; + detailBody.Text = state + "\n" + string.Join(" ", garrison.Guards.Select((g, i) => $"{i + 1}: {(g.Alive ? g.Health + " HP" : "FALLEN")}")) + + $"\n{garrison.DamageDealt} damage / {garrison.Kills} stopped\nRecovery between waves. Extra enemies pass."; + } + if (ended) { Building = false; BuildingGarrison = false; Rallying = false; } + } + + private void ClearSquadSelection() { BuildingGarrison = false; GarrisonSelected = false; Rallying = false; } + + public void CancelOrders() + { + Building = false; SelectedTower = 0; ClearSquadSelection(); + Message("Orders cancelled. Select a defense or choose a build card."); RefreshInterface(); + } + + public void ChooseGarrison() + { + if (OrdersBlocked || Content.Garrison is null) return; + if (Run.Garrison is not null) { SelectGarrison(); return; } + Building = BuildingGarrison = true; SelectedTower = 0; GarrisonSelected = Rallying = false; + Message("Garrison: three guards. Choose a permanent foundation near tower coverage; it cannot be sold."); RefreshInterface(); + } + + public void SelectGarrison() + { + if (OrdersBlocked || Run.Garrison is null) return; + Building = BuildingGarrison = Rallying = false; SelectedTower = 0; GarrisonSelected = true; + Message("Shieldguards selected. Rally [F], then click the road. Retreat [H] releases enemies; recovery is between waves."); RefreshInterface(); + } + + public void BeginRally() + { + if (OrdersBlocked || Run.Garrison is null) return; + SelectGarrison(); Rallying = true; + Message("Rally: click the highlighted road. Distant or off-road orders are rejected. Escape or right-click cancels."); RefreshInterface(); + } + + public void OrderRetreat() + { + if (OrdersBlocked || Run.Garrison is null) return; + SelectGarrison(); Message(Run.Apply(new RetreatSquad()).Message); RefreshInterface(); + } + + public bool TryRoadPointer(Vector2 pointer, out Redesign.Core.Point position) + { + var p = new Redesign.Core.Point(pointer.X, pointer.Y); + position = Run.Route.At(Run.Route.NearestProgress(p)); + return pointer.X >= 0 && pointer.Y >= 0 && pointer.X <= Board.Size.X && pointer.Y <= Board.Size.Y && + (position - p).LengthSquared <= 26 * 26; + } + + public void RallyAtPointer(Vector2 pointer) + { + if (OrdersBlocked || !Rallying) return; + if (!TryRoadPointer(pointer, out var position)) { Message("Choose a point on the highlighted road, not the grass."); return; } + var result = Run.Apply(new RallySquad(position)); Message(result.Message); + if (result.Success || Run.Garrison is { Retreating: false } g && (position - Run.Route.At(g.RallyProgress)).LengthSquared < .001) + Rallying = false; + RefreshInterface(); + } + + private void PrepareSquadDemo(string[] args) + { + if (!args.Any(a => a is "--squad-demo" or "--squad-boss-demo" or "--squad-placement-demo")) return; + if (args.Contains("--squad-placement-demo")) { ChooseGarrison(); Board.SetPreviewPointer(ArenaCanvas.V(Content.Map.Center(Content.Map.Foundations[3]))); return; } + var bossDemo = args.Contains("--squad-boss-demo"); + var budget = 150000; + while (budget-- > 0 && Run.Phase is RunPhase.Planning or RunPhase.Wave) + { + if (Run.Phase == RunPhase.Planning) + { + foreach (var command in ExpeditionStrategy.PlanningCommands(Run, squad: true)) + if (!Run.Apply(command).Success) throw new InvalidOperationException("Squad demo command failed: " + command); + Run.Apply(new StartWave()); + } + Run.Step(); + foreach (var e in Run.DrainEvents()) Board.Receive(e); + var ready = bossDemo ? Run.Enemies.Any(e => e.Definition.Boss is not null && e.MeleeAtTick > Run.Tick + 15) : + Run.Garrison?.Guards.Count(g => g.EngagedEnemyId != 0) >= 2; + if (ready) + { + Run.Apply(new Pause(true)); SelectGarrison(); + var speed = args.Contains("--speed=4") ? 4 : args.Contains("--speed=2") ? 2 : 1; + SetSpeed(speed); + if (args.Contains("--animate")) Run.Apply(new Pause(false)); + return; + } + } + throw new InvalidOperationException("Squad demo could not reach its encounter."); + } +} diff --git a/Redesign-Evolution/Game/GameRoot.cs b/Redesign-Evolution/Game/GameRoot.cs index a98792d..0167641 100644 --- a/Redesign-Evolution/Game/GameRoot.cs +++ b/Redesign-Evolution/Game/GameRoot.cs @@ -55,6 +55,7 @@ public override void _Ready() capturePath = args.FirstOrDefault(a => a.StartsWith("--capture="))?[10..]; if (args.Contains("--smoke")) AddChild(new SmokeHarness { Game = this }); PrepareExpeditionDemo(args); + PrepareSquadDemo(args); if (args.Contains("--paths-demo")) { SelectedTower = Run.Apply(new PlaceTower(2, "prism")).EntityId; @@ -95,19 +96,21 @@ private void BuildInterface() var shortcuts = new[] { "B", "P", "C" }; BuildButtons = Content.Towers.Select((tower, i) => { - var button = AddButton(this, $"{tower.Name.ToUpperInvariant()} {tower.Cost} G [{shortcuts[i]}]\n{tower.Description}", - new(1052, 292 + i * 62), new(336, 54), () => ChooseBuild(i)); - button.AddThemeFontSizeOverride("font_size", 14); - button.TooltipText = $"{tower.Damage} {tower.DamageKind.ToString().ToLowerInvariant()} damage every {tower.CooldownTicks / 60d:0.00}s. Range {tower.Range:0}."; + var role = i == 0 ? "Precision" : i == 1 ? "Anti-armor" : "Area damage"; + var button = AddButton(this, $"{tower.Name.ToUpperInvariant()} [{shortcuts[i]}]\n{tower.Cost} G / {role}", + new(1052 + i % 2 * 172, 292 + i / 2 * 82), new(164, 72), () => ChooseBuild(i)); + button.AddThemeFontSizeOverride("font_size", 13); + button.TooltipText = $"{tower.Description}\n{tower.Damage} {tower.DamageKind.ToString().ToLowerInvariant()} damage every {tower.CooldownTicks / 60d:0.00}s. Range {tower.Range:0}."; return button; }).ToArray(); - detailTitle = AddLabel(this, "", new(1052, 490), new(336, 28), 20, Text); - detailBody = AddLabel(this, "", new(1052, 530), new(336, 72), 15, Muted, wrap: true); + detailTitle = AddLabel(this, "", new(1052, 478), new(336, 28), 20, Text); + detailBody = AddLabel(this, "", new(1052, 516), new(336, 88), 14, Muted, wrap: true); PriorityButton = AddButton(this, "TARGET: FIRST [T]", new(1052, 612), new(336, 36), CyclePriority); PriorityButton.TooltipText = "First: nearest the gate. Strongest: highest current health. Support: Wardens and Menders first. Primed: ready for this tower's reaction, then nearest the gate."; EvolveButton = AddButton(this, "EVOLVE [U]", new(1052, 658), new(162, 36), OpenEvolution); SellButton = AddButton(this, "SELL", new(1224, 658), new(164, 36), SellSelected); SellButton.AddThemeFontSizeOverride("font_size", 14); + BuildSquadInterface(); StartButton = AddButton(this, "START WAVE [N]", new(1052, 720), new(336, 58), StartNextWave, true); ChallengeButton = AddButton(this, "OVERRUN: OFF", new(1052, 788), new(336, 38), ToggleChallenge); soundButton = AddButton(this, "SOUND ON [M]", new(1052, 848), new(336, 28), ToggleSound); @@ -152,7 +155,7 @@ public override void _Draw() DrawRect(new(28, 178, 984, 658), Border, false, 1); DrawRect(new(1032, 156, 378, 680), Panel); DrawRect(new(1032, 156, 378, 680), Border, false, 1); - DrawLine(new(1052, 478), new(1388, 478), Border, 1); + DrawLine(new(1052, 462), new(1388, 462), Border, 1); DrawLine(new(870, 31), new(870, 100), Border, 1); DrawLine(new(1050, 31), new(1050, 100), Border, 1); DrawLine(new(1230, 31), new(1230, 100), Border, 1); @@ -185,7 +188,7 @@ public void RefreshInterface() for (var i = 0; i < BuildButtons.Length; i++) { BuildButtons[i].Disabled = ended; - BuildButtons[i].Modulate = Building && BuildType == i ? Mint : Run.Gold >= Content.Towers[i].Cost ? Colors.White : Muted; + BuildButtons[i].Modulate = Building && !BuildingGarrison && BuildType == i ? Mint : Run.Gold >= Content.Towers[i].Cost ? Colors.White : Muted; } for (var i = 0; i < SpeedButtons.Length; i++) SpeedButtons[i].Modulate = Speed == (1 << i) ? Mint : Colors.White; var tower = Run.Towers.FirstOrDefault(t => t.Id == SelectedTower); @@ -217,7 +220,10 @@ public void RefreshInterface() resultBody.Text = $"{Run.Kills} stopped / {Run.Leaks} breached / {Run.Lives} lives remain\n{Run.DamageDealt} damage dealt · {Run.GoldEarned} gold earned\n{Run.WaveNumber} waves faced · {Run.Tick / 60d:0.0}s simulated"; resultBody.Text += "\n" + string.Join(" / ", Run.Reactions.Select(r => $"{r.Triggers} {r.Definition.Name}")) + $" / {Run.ReactionDamage} reaction damage"; resultBody.Text += $"\nRelics: {string.Join(", ", Run.Relics.Select(r => r.Name))}\n{Run.WaveReports.Count} waves cleared / {Run.WaveReports.Count(w => w.ChallengeWon)} Overruns earned / seed {Run.Seed}"; + if (Run.Garrison is { } garrison) + resultBody.Text += $"\nShieldguards: {garrison.DamageDealt} damage / {garrison.Kills} stopped / {garrison.Casualties} fallen / {garrison.EngagedTicks / 60d:0}s total engagement"; } + RefreshSquadInterface(ended); RefreshExpeditionInterface(); } @@ -225,21 +231,26 @@ public void ChooseBuild(int type = 0) { if (EvolutionPanel.Visible || RewardPanel.Visible) return; if (Run.Phase is RunPhase.Victory or RunPhase.Defeat || type < 0 || type >= Content.Towers.Length) return; - BuildType = type; Building = true; SelectedTower = 0; + ClearSquadSelection(); BuildType = type; Building = true; SelectedTower = 0; Message($"{BuildDefinition.Name}: {BuildDefinition.Description} Choose a foundation."); RefreshInterface(); } public void SelectFoundation(int index) { if (EvolutionPanel.Visible || RewardPanel.Visible) return; if (Run.Phase is RunPhase.Victory or RunPhase.Defeat) return; + if (Run.Garrison?.Foundation == index) { SelectGarrison(); return; } var tower = Run.Towers.FirstOrDefault(t => t.Foundation == index); - if (tower is not null) { SelectedTower = tower.Id; Building = false; Message("Tower selected. Its range is shown on the battlefield."); } + if (tower is not null) { ClearSquadSelection(); SelectedTower = tower.Id; Building = false; Message("Tower selected. Its range is shown on the battlefield."); } else if (Building) { - var result = Run.Apply(new PlaceTower(index, BuildDefinition.Id)); Message(result.Message); - if (result.Success) { SelectedTower = result.EntityId; Building = false; } + var result = Run.Apply(BuildingGarrison ? new PlaceGarrison(index) : new PlaceTower(index, BuildDefinition.Id)); Message(result.Message); + if (result.Success) + { + if (BuildingGarrison) { SelectGarrison(); BeginRally(); } + else { SelectedTower = result.EntityId; Building = false; } + } } - else Message("Choose Boltworks [B], Prism [P] or Crucible [C], then an empty foundation."); + else Message("Choose a tower [B/P/C] or Garrison [G], then an empty foundation."); RefreshInterface(); } private void SellSelected() { Message(Run.Apply(new SellTower(SelectedTower)).Message); SelectedTower = 0; RefreshInterface(); } @@ -260,6 +271,7 @@ public void Restart() EvolutionPanel.Visible = false; RewardPanel.Visible = false; Run = new Simulation(Content, unchecked(Run.Seed + 1)); clock = new(); Speed = 1; Building = false; SelectedTower = 0; BuildType = 0; + ClearSquadSelection(); Board.ClearEffects(); audio.StopAll(); Message("A fresh defense. Read the forecast and choose your tower mix."); RefreshInterface(); } public override void _UnhandledKeyInput(InputEvent @event) @@ -284,6 +296,9 @@ public override void _UnhandledKeyInput(InputEvent @event) case Key.B: ChooseBuild(0); break; case Key.P: ChooseBuild(1); break; case Key.C: ChooseBuild(2); break; + case Key.G: ChooseGarrison(); break; + case Key.F: BeginRally(); break; + case Key.H: OrderRetreat(); break; case Key.T: CyclePriority(); break; case Key.U: OpenEvolution(); break; case Key.I: OpenRelicReview(); break; @@ -293,7 +308,7 @@ public override void _UnhandledKeyInput(InputEvent @event) case Key.Key2: SetSpeed(2); break; case Key.Key4: SetSpeed(4); break; case Key.M: ToggleSound(); break; - case Key.Escape: Building = false; SelectedTower = 0; Message("Placement cancelled."); break; + case Key.Escape: CancelOrders(); break; case Key.R: if (Run.Phase is RunPhase.Victory or RunPhase.Defeat) Restart(); break; default: return; } diff --git a/Redesign-Evolution/Infrastructure/ExpeditionStrategy.cs b/Redesign-Evolution/Infrastructure/ExpeditionStrategy.cs index 71f2912..60a6044 100644 --- a/Redesign-Evolution/Infrastructure/ExpeditionStrategy.cs +++ b/Redesign-Evolution/Infrastructure/ExpeditionStrategy.cs @@ -2,10 +2,13 @@ namespace Redesign.Infrastructure; +/// A published purchase/deployment experiment, not live AI or a rule of the game. +public sealed record SquadDeployment(int Foundation, int RecruitBeforeWave, double RallyOffset = 0); + /// Deliberately simple, published balance witnesses. They use the same commands as the player. public static class ExpeditionStrategy { - public static IEnumerable PlanningCommands(Simulation run, string style = "frost", bool risk = false) + public static IEnumerable PlanningCommands(Simulation run, string style = "frost", bool risk = false, bool squad = false, SquadDeployment? deployment = null) { if (run.RewardOffers.Count > 0) { @@ -19,6 +22,15 @@ public static IEnumerable PlanningCommands(Simulation run, string s yield return new ChooseRelic(chosen.Id); } var content = run.Definition; + deployment ??= new(3, 3); + if (squad && style != "none" && run.Garrison is null && run.WaveNumber + 1 >= deployment.RecruitBeforeWave && + content.Garrison is { } garrison && run.Gold >= garrison.Cost) + yield return new PlaceGarrison(deployment.Foundation); + if (squad && run.Garrison is { } guards) + { + var progress = Math.Clamp(guards.EntryProgress + deployment.RallyOffset, 0, run.Route.Length); + if (progress != guards.RallyProgress || guards.Retreating) yield return new RallySquad(run.Route.At(progress)); + } var plan = style switch { "fire" => new[] { (1, "boltworks", false), (2, "prism", false), (0, "crucible", false), (1, "pitchbow", true), (2, "sun", true), @@ -37,6 +49,7 @@ public static IEnumerable PlanningCommands(Simulation run, string s if (style == "none") plan = []; foreach (var (foundation, id, upgrade) in plan) { + if (squad && foundation == deployment.Foundation) continue; var tower = run.Towers.FirstOrDefault(t => t.Foundation == foundation); if (!upgrade && tower is not null || upgrade && tower?.BranchId is not null) continue; var cost = upgrade ? content.Combat!.Branches.Single(b => b.Upgrade.Id == id).Cost : content.Towers.Single(t => t.Id == id).Cost; diff --git a/Redesign-Evolution/SimRunner/ExpeditionRunner.cs b/Redesign-Evolution/SimRunner/ExpeditionRunner.cs index fbf0268..67e1e7f 100644 --- a/Redesign-Evolution/SimRunner/ExpeditionRunner.cs +++ b/Redesign-Evolution/SimRunner/ExpeditionRunner.cs @@ -19,7 +19,7 @@ public static int Run(string[] args) { if (run.Phase == RunPhase.Planning) { - foreach (var command in ExpeditionStrategy.PlanningCommands(run, style, args.Contains("--risk"))) + foreach (var command in ExpeditionStrategy.PlanningCommands(run, style, args.Contains("--risk"), args.Contains("--squad"))) { var result = run.Apply(command); if (!result.Success) throw new InvalidOperationException($"Wave {run.WaveNumber + 1} {command}: {result.Message}"); @@ -31,7 +31,10 @@ public static int Run(string[] args) Console.WriteLine(JsonSerializer.Serialize(new { Style = style, run.Seed, Outcome = run.Phase.ToString(), Wave = run.WaveNumber, run.Tick, run.Kills, run.Leaks, run.Lives, run.Gold, run.GoldSpent, run.ReactionDamage, Relics = run.Relics.Select(r => r.Id), Waves = run.WaveReports, - Towers = run.Towers.Select(t => new { t.Definition.Id, t.Foundation, t.DamageDealt, t.Kills }), Checksum = run.Checksum() })); + Towers = run.Towers.Select(t => new { t.Definition.Id, t.Foundation, t.DamageDealt, t.Kills }), + Squad = run.Garrison is { } squad ? new { squad.Foundation, squad.DamageDealt, squad.Kills, squad.Casualties, + squad.EngagedTicks, Guards = squad.Guards.Select(g => new { g.Id, g.Health, g.DamageDealt, g.Kills, g.EngagedTicks }) } : null, + Checksum = run.Checksum() })); success &= budget > 0 && (batch || run.Phase == (style == "none" ? RunPhase.Defeat : RunPhase.Victory)); } return success ? 0 : 1; diff --git a/Redesign-Evolution/Tests/SquadTests.cs b/Redesign-Evolution/Tests/SquadTests.cs new file mode 100644 index 0000000..fead33e --- /dev/null +++ b/Redesign-Evolution/Tests/SquadTests.cs @@ -0,0 +1,377 @@ +using Redesign.Core; +using Redesign.Infrastructure; +using Xunit; + +namespace Redesign.Tests; + +public class SquadTests +{ + private static GameDefinition Fixture(int count = 4) => new(2, "squad-test", 1000, 100, + new("road", "Road", 10, 5, 32, [new(0, 1), new(9, 1)], [new(2, 0), new(4, 0), new(9, 4)]), + [new("beam", 10, 100, 500, 60, 1, Attack: AttackKind.Beam, DamageKind: DamageKind.Energy)], + [new("grunt", 1000, 60, 7, 1, Melee: new(10, 12, 30, 10))], + [new("Pressure", "", [new("grunt", count, 1)])], + Garrison: new("garrison", "Garrison", "Three guards", 120, 240, new("guard", "Guard", 30, 4, 64, 8, 30, 5))); + + private static Simulation Deploy(GameDefinition? content = null, bool reference = false) + { + var run = new Simulation(content ?? Fixture(), 42, reference); + Assert.True(run.Apply(new PlaceGarrison(0)).Success); + Assert.True(run.Apply(new StartWave()).Success); + return run; + } + + private static void Until(Simulation run, Func condition, int budget = 10000) + { + while (!condition() && run.Phase == RunPhase.Wave && budget-- > 0) run.Step(); + Assert.True(condition(), $"Condition not reached: tick {run.Tick}, phase {run.Phase}"); + } + + private static void RejectedWithoutMutation(Simulation run, GameCommand command) + { + run.DrainEvents(); + var before = run.Checksum(); + Assert.False(run.Apply(command).Success); + Assert.Equal(before, run.Checksum()); + Assert.Empty(run.DrainEvents()); + } + + [Fact] + public void Purchases_orders_and_shared_foundations_validate_before_any_mutation() + { + var d = Fixture(); + var empty = new Simulation(d with { Garrison = null }); + RejectedWithoutMutation(empty, new PlaceGarrison(0)); + RejectedWithoutMutation(empty, new RallySquad(new(80, 48))); + RejectedWithoutMutation(empty, new RetreatSquad()); + var poor = new Simulation(d with { StartingGold = 119 }); + RejectedWithoutMutation(poor, new PlaceGarrison(0)); + var far = new Simulation(d with { Garrison = d.Garrison! with { CommandRadius = 40 } }); + RejectedWithoutMutation(far, new PlaceGarrison(2)); + + var run = new Simulation(d); + RejectedWithoutMutation(run, new PlaceGarrison(-1)); + RejectedWithoutMutation(run, new PlaceGarrison(3)); + Assert.True(run.Apply(new PlaceTower(1)).Success); + RejectedWithoutMutation(run, new PlaceGarrison(1)); + var built = run.Apply(new PlaceGarrison(0)); + Assert.True(built.Success); + Assert.Equal(3, run.Garrison!.Guards.Count); + Assert.Equal(870, run.Gold); + Assert.Equal(130, run.GoldSpent); + Assert.Equal(5, run.Garrison.Guards.Select(g => g.Id).Append(built.EntityId).Append(run.Towers[0].Id).Distinct().Count()); + RejectedWithoutMutation(run, new PlaceGarrison(2)); + RejectedWithoutMutation(run, new PlaceTower(0)); + RejectedWithoutMutation(run, new SellTower(built.EntityId)); + foreach (var point in new[] { new Point(double.NaN, 48), new(double.PositiveInfinity, 48), new(80, 49), new(304, 48), new(-1, 48) }) + RejectedWithoutMutation(run, new RallySquad(point)); + var atBoundary = run.Route.At(run.Garrison.EntryProgress + 208); + Assert.True(run.Apply(new RallySquad(atBoundary)).Success); + RejectedWithoutMutation(run, new RallySquad(atBoundary)); + } + + [Fact] + public void Command_reach_uses_road_distance_and_guards_travel_around_corners() + { + var d = Fixture(1); + d = d with + { + Map = d.Map with { Route = [new(0, 2), new(7, 2), new(7, 0), new(2, 0)], Foundations = [new(2, 3)] }, + Enemies = [d.Enemies[0] with { Speed = .01 }] + }; + var run = new Simulation(d); run.Apply(new PlaceGarrison(0)); + var garrison = run.Garrison!; + // This point is physically close, but far away along the winding road. + Assert.True((run.Route.At(run.Route.Length) - garrison.Position).Length < garrison.Definition.CommandRadius); + RejectedWithoutMutation(run, new RallySquad(run.Route.At(run.Route.Length))); + var destination = run.Route.At(256); + Assert.True(run.Apply(new RallySquad(destination)).Success); + Assert.All(garrison.Guards, g => Assert.Equal(garrison.Position, g.Position)); + run.Apply(new StartWave()); + Until(run, () => garrison.Guards.All(g => g.Position == destination)); + Assert.All(garrison.Guards, g => Assert.True(g.OnRoad)); + Assert.InRange(run.Tick, 209, 211); // 224 world units at 64 units/second, including the access spur. + var positions = garrison.Guards.Select(g => g.Position).ToArray(); + Assert.True(run.Apply(new RetreatSquad()).Success); + Assert.Equal(positions, garrison.Guards.Select(g => g.Position)); + while (garrison.Guards[0].OnRoad) + { + run.Step(); + if (garrison.Guards[0].OnRoad) Assert.True(run.Route.TryGetProgress(garrison.Guards[0].Position, out _)); + } + Until(run, () => garrison.Guards.All(g => g.Position == garrison.Position)); + Assert.InRange(run.Tick, 419, 422); + } + + [Fact] + public void Three_guards_hold_three_enemies_excess_pass_and_unsupported_guards_eventually_fall() + { + var run = Deploy(); var squad = run.Garrison!; + Until(run, () => squad.Guards.All(g => g.EngagedEnemyId != 0)); + Assert.Equal(3, squad.Guards.Select(g => g.EngagedEnemyId).Distinct().Count()); + Assert.Equal(squad.Guards.Select(g => g.Id), run.Enemies.Take(3).Select(e => e.EngagedGuardId)); + Assert.Equal(0, run.Enemies[3].EngagedGuardId); + var held = run.Enemies.Take(3).Select(e => e.Progress).ToArray(); + for (var i = 0; i < 15; i++) run.Step(); + Assert.Equal(held, run.Enemies.Take(3).Select(e => e.Progress)); + Assert.True(run.Enemies[3].Progress > squad.RallyProgress); + Until(run, () => squad.Guards.All(g => !g.Alive)); + Assert.All(run.Enemies, e => Assert.Equal(0, e.EngagedGuardId)); + Assert.All(squad.Guards, g => Assert.Equal(0, g.EngagedEnemyId)); + Assert.Equal(3, squad.Casualties); + Until(run, () => run.Phase != RunPhase.Wave); + Assert.Equal(RunPhase.Victory, run.Phase); Assert.Equal(4, run.Leaks); Assert.Equal(0, run.Kills); + Assert.Equal(0, run.GoldEarned); Assert.True(squad.EngagedTicks > 0); + Assert.Equal(squad.DamageDealt, run.DamageDealt); + Assert.Equal(squad.Guards.Sum(g => g.DamageDealt), run.DamageDealt); + Assert.Equal(3, run.DrainEvents().Count(e => e.Kind == EventKind.GuardFallen)); + } + + [Fact] + public void Swept_contact_catches_fast_enemies_without_exceeding_guard_capacity() + { + var d = Fixture(); + d = d with { Enemies = [d.Enemies[0] with { Speed = 100000 }], Waves = [new("Rush", "", [new("grunt", 4, 1, 40)])] }; + var run = Deploy(d); + Until(run, () => run.PendingSpawns == 0); + Assert.Equal(3, run.Enemies.Count); Assert.Equal(1, run.Leaks); + Assert.All(run.Enemies, e => Assert.Equal(56, e.Progress)); + Assert.Equal(3, run.Garrison!.Guards.Count(g => g.EngagedEnemyId != 0)); + } + + [Fact] + public void Orders_release_both_sides_preserve_cooldowns_and_cannot_heal_or_teleport() + { + var run = Deploy(); var squad = run.Garrison!; + Until(run, () => squad.Guards.All(g => g.Health < g.Definition.Health)); + var positions = squad.Guards.Select(g => g.Position).ToArray(); + var health = squad.Guards.Select(g => g.Health).ToArray(); + var cooldowns = squad.Guards.Select(g => g.NextAttackTick).ToArray(); + var enemyCooldowns = run.Enemies.Select(e => e.NextMeleeTick).ToArray(); + Assert.True(run.Apply(new RallySquad(run.Route.At(96))).Success); + Assert.Equal(positions, squad.Guards.Select(g => g.Position)); + Assert.Equal(health, squad.Guards.Select(g => g.Health)); + Assert.Equal(cooldowns, squad.Guards.Select(g => g.NextAttackTick)); + Assert.Equal(enemyCooldowns, run.Enemies.Select(e => e.NextMeleeTick)); + Assert.All(run.Enemies, e => { Assert.Equal(0, e.EngagedGuardId); Assert.Equal(0, e.MeleeAtTick); }); + Assert.All(squad.Guards, g => { Assert.Equal(0, g.EngagedEnemyId); Assert.Equal(0, g.AttackAtTick); }); + run.Step(); Assert.NotEqual(positions[0], squad.Guards[0].Position); + Assert.True(run.Apply(new RetreatSquad()).Success); + RejectedWithoutMutation(run, new RetreatSquad()); + Until(run, () => squad.Guards.All(g => g.Position == squad.Position)); + Assert.Equal(health, squad.Guards.Select(g => g.Health)); + Assert.All(squad.Guards, g => Assert.False(g.OnRoad)); + } + + [Fact] + public void Guards_recover_and_regroup_only_on_entering_planning_with_ids_and_statistics_preserved() + { + var d = Fixture(); d = d with { Waves = [d.Waves[0], d.Waves[0]] }; + var run = Deploy(d); var squad = run.Garrison!; + var ids = squad.Guards.Select(g => g.Id).ToArray(); + Until(run, () => squad.Guards.All(g => !g.Alive)); + for (var i = 0; i < 30; i++) run.Step(); + Assert.All(squad.Guards, g => Assert.False(g.Alive)); + Until(run, () => run.Phase == RunPhase.Planning); + Assert.Equal(ids, squad.Guards.Select(g => g.Id)); + Assert.Equal(3, squad.Casualties); Assert.True(squad.DamageDealt > 0); + Assert.All(squad.Guards, g => { Assert.Equal(g.Definition.Health, g.Health); Assert.Equal(squad.Position, g.Position); }); + Assert.Single(run.DrainEvents(), e => e.Kind == EventKind.SquadRecovered); + run.Apply(new StartWave()); run.Step(); + Assert.All(squad.Guards, g => Assert.NotEqual(squad.Position, g.Position)); + } + + [Fact] + public void Wounded_survivors_heal_between_waves_without_a_gold_cost() + { + var d = Fixture(1); + d = d with { Enemies = [d.Enemies[0] with { Health = 12 }], Waves = [d.Waves[0], d.Waves[0]] }; + var run = Deploy(d); var guard = run.Garrison!.Guards[0]; + Until(run, () => guard.Health < guard.Definition.Health); + Assert.Equal(RunPhase.Wave, run.Phase); + Until(run, () => run.Phase == RunPhase.Planning); + Assert.Equal(30, guard.Health); Assert.Equal(0, run.Garrison.Casualties); + Assert.Equal(120, run.GoldSpent); Assert.Equal(887, run.Gold); + } + + [Fact] + public void Lethal_melee_credits_capped_damage_and_bounty_once_before_enemy_retaliation() + { + var d = Fixture(3); d = d with { Enemies = [d.Enemies[0] with { Health = 3 }] }; + var run = Deploy(d); Until(run, () => run.Phase != RunPhase.Wave); + Assert.Equal(3, run.Kills); Assert.Equal(0, run.Leaks); + Assert.Equal(9, run.DamageDealt); Assert.Equal(9, run.Garrison!.DamageDealt); + Assert.Equal(3, run.Garrison.Kills); Assert.Equal(21, run.GoldEarned); + Assert.Equal(901, run.Gold); Assert.All(run.Garrison.Guards, g => Assert.Equal(30, g.Health)); + var events = run.DrainEvents(); Assert.Equal(3, events.Count(e => e.Kind == EventKind.Killed)); + var contacts = events.Where(e => e.Kind == EventKind.GuardStruck).ToArray(); + Assert.Equal(3, contacts.Length); Assert.All(contacts, e => Assert.Equal(3, e.Amount)); + Assert.All(contacts, e => Assert.Contains(run.Garrison.Guards, g => g.Id == e.EntityId)); + Assert.DoesNotContain(events, e => e.Kind is EventKind.GuardHit or EventKind.Leaked); + RejectedWithoutMutation(run, new PlaceGarrison(1)); + } + + [Fact] + public void Tower_kill_releases_a_duel_before_due_melee_without_double_credit() + { + var run = Deploy(Fixture(1)); + Until(run, () => run.Garrison!.Guards[0].EngagedEnemyId != 0); + var guard = run.Garrison!.Guards[0]; var enemy = run.Enemies[0]; + enemy.Health = 1; guard.AttackAtTick = enemy.MeleeAtTick = run.Tick + 1; + var health = guard.Health; + run.Apply(new PlaceTower(1)); run.DrainEvents(); run.Step(); + Assert.Equal(health, guard.Health); Assert.Equal(0, guard.EngagedEnemyId); Assert.Equal(0, enemy.EngagedGuardId); + Assert.Equal(1, run.Kills); Assert.Equal(1, run.Towers[0].Kills); Assert.Equal(0, run.Garrison.Kills); + Assert.Equal(7, run.GoldEarned); Assert.Equal(1, run.Towers[0].DamageDealt); + var events = run.DrainEvents(); + Assert.Single(events, e => e.Kind == EventKind.Killed); + Assert.DoesNotContain(events, e => e.Kind == EventKind.GuardStruck); + } + + [Fact] + public void Basic_melee_respects_armor_and_preserves_chill_and_oil_for_towers() + { + var d = Fixture(1); + var source = ContentLoader.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "expedition.json"))); + d = d with { Combat = source.Combat! with { Branches = [] }, Enemies = [d.Enemies[0] with { Armor = 2 }] }; + var run = Deploy(d); Until(run, () => run.Garrison!.Guards[0].EngagedEnemyId != 0); + var enemy = run.Enemies[0]; + enemy.StatusSet.Apply(d.Combat.Statuses.Single(s => s.Id == "chill"), 2, 999, run.Tick); + enemy.StatusSet.Apply(d.Combat.Statuses.Single(s => s.Id == "oil"), 1, 999, run.Tick); + Until(run, () => run.Garrison!.DamageDealt > 0); + Assert.Equal(2, run.Garrison!.DamageDealt); + Assert.Equal(2, enemy.Statuses.Single(s => s.Definition.Id == "chill").Count); + Assert.Equal(1, enemy.Statuses.Single(s => s.Definition.Id == "oil").Count); + Assert.All(run.Reactions, r => Assert.Equal(0, r.Triggers)); + Assert.Equal(0, run.ReactionDamage); + } + + [Theory] + [InlineData(false)] [InlineData(true)] + public void Moving_boss_warns_before_cleave_and_retreat_can_escape(bool retreat) + { + var d = Fixture(1); + var boss = new EnemyDefinition("boss", 1000, 12, 0, 12, + Boss: new("grunt", 1, 1, 600, 30, 0, 50, 25), Melee: new(30, 48, 90, 20, true, true)); + d = d with { Enemies = [d.Enemies[0] with { Bounty = 0 }, boss], Waves = [new("Boss", "", [new("boss", 1, 1)])] }; + var run = Deploy(d); var squad = run.Garrison!; + Until(run, () => run.Enemies.Count > 0 && run.Enemies[0].MeleeAtTick > 0); + var enemy = run.Enemies[0]; var contact = enemy.MeleeAtTick; var progress = enemy.Progress; + Assert.Equal(0, enemy.EngagedGuardId); Assert.All(squad.Guards, g => Assert.Equal(30, g.Health)); + Assert.Single(run.DrainEvents(), e => e.Kind == EventKind.EnemyMeleeStarted); + if (retreat) Assert.True(run.Apply(new RetreatSquad()).Success); + Until(run, () => run.Tick == contact - 1); + Assert.All(squad.Guards, g => Assert.Equal(30, g.Health)); + run.Step(); + Assert.True(enemy.Progress > progress); + Assert.All(squad.Guards, g => Assert.Equal(retreat ? 30 : 0, g.Health)); + Assert.Equal(retreat ? 0 : 3, squad.Casualties); + } + + [Fact] + public void Captain_can_be_held_but_defeats_unsupported_guards_and_cannot_stall_forever() + { + var d = Fixture(1); + d = d with { Enemies = [d.Enemies[0] with { Health = 400, Armor = 20, Melee = new(40, 28, 90, 30) }], + Garrison = d.Garrison! with { Guard = d.Garrison.Guard with { Health = 80 } } }; + var run = Deploy(d); + Until(run, () => run.Garrison!.Guards[0].Health == 40); + Assert.NotEqual(0, run.Enemies[0].EngagedGuardId); + Until(run, () => run.Phase != RunPhase.Wave); + Assert.Equal(3, run.Garrison!.Casualties); Assert.Equal(1, run.Leaks); Assert.Equal(0, run.Kills); + } + + [Fact] + public void Squad_pause_freezes_travel_windups_health_and_engagements() + { + var run = Deploy(); + Until(run, () => run.Garrison!.Guards[0].AttackAtTick > 0); + run.DrainEvents(); run.Apply(new Pause(true)); var digest = run.Checksum(); + var clock = new SimulationClock(); + for (var i = 0; i < 200; i++) { run.Step(); clock.Advance(run, 1d / 60, 4); } + Assert.Equal(digest, run.Checksum()); Assert.Empty(run.DrainEvents()); + run.Apply(new Pause(false)); run.Step(); Assert.NotEqual(digest, run.Checksum()); + } + + [Fact] + public void Squad_combat_and_orders_match_reference_queries_tick_by_tick() + { + var d = Fixture(12); + var a = Deploy(d); var b = Deploy(d, true); + foreach (var run in new[] { a, b }) run.Apply(new PlaceTower(1)); + for (var i = 0; i < 3000 && a.Phase == RunPhase.Wave; i++) + { + foreach (var run in new[] { a, b }) + { + if (i == 80) run.Apply(new RallySquad(run.Route.At(128))); + if (i == 100) run.Apply(new RetreatSquad()); + if (i == 160) run.Apply(new RallySquad(run.Route.At(96))); + run.Step(); + } + Assert.Equal(a.Checksum(), b.Checksum()); Assert.Equal(a.DrainEvents(), b.DrainEvents()); + } + Assert.Equal(RunPhase.Victory, a.Phase); + Assert.True(a.Garrison!.DamageDealt > 0); + } + + [Theory] + [InlineData(30, 1)] [InlineData(144, 2)] [InlineData(144, 4)] + public void Render_rate_and_speed_do_not_change_squad_combat(int fps, int speed) + { + var a = Deploy(); var b = Deploy(); + Until(a, () => a.Phase != RunPhase.Wave); + var clock = new SimulationClock(); var budget = 20000; + while (b.Phase == RunPhase.Wave && budget-- > 0) clock.Advance(b, 1d / fps, speed); + Assert.Equal(a.Checksum(), b.Checksum()); Assert.Equal(a.DrainEvents(), b.DrainEvents()); + } + + [Fact] + public void Full_expedition_squad_witness_reproduces_with_healing_boss_relics_and_reference_queries() + { + var content = ContentLoader.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "expedition.json"))); + Simulation Finish(bool reference = false, bool frames = false) + { + var run = new Simulation(content, 42, reference); var clock = new SimulationClock(); var budget = 150000; + while (run.Phase is RunPhase.Wave or RunPhase.Planning && budget-- > 0) + { + if (run.Phase == RunPhase.Planning) + { + foreach (var command in ExpeditionStrategy.PlanningCommands(run, squad: true)) + Assert.True(run.Apply(command).Success, command.ToString()); + Assert.True(run.Apply(new StartWave()).Success); + } + if (frames) clock.Advance(run, 1d / 144, 4); else run.Step(); + run.DrainEvents(); + } + Assert.True(budget > 0); Assert.Equal(RunPhase.Victory, run.Phase); + return run; + } + var expected = Finish(); var reference = Finish(reference: true); var frames = Finish(frames: true); + Assert.Equal(expected.Checksum(), reference.Checksum()); Assert.Equal(expected.Checksum(), frames.Checksum()); + Assert.Equal(12, expected.WaveReports.Count); Assert.True(expected.Garrison!.DamageDealt > 0); + Assert.True(expected.Garrison.Casualties > 0); Assert.True(expected.Garrison.EngagedTicks > 0); + Assert.Equal(expected.DamageDealt, expected.Towers.Sum(t => t.DamageDealt) + expected.Garrison.DamageDealt); + Assert.Equal(expected.Kills, expected.Towers.Sum(t => t.Kills) + expected.Garrison.Kills); + } + + [Fact] + public void Invalid_squad_definitions_fail_at_load_and_optional_content_preserves_old_missions() + { + var d = Fixture(); var spec = d.Garrison!; + foreach (var invalid in new[] { spec with { Cost = 0 }, spec with { CommandRadius = double.NaN }, + spec with { Id = "beam" }, spec with { Guard = spec.Guard with { WindupTicks = 30 } }, + spec with { Guard = spec.Guard with { Health = 0 } }, spec with { Guard = spec.Guard with { Reach = 13 } } }) + Assert.Throws(() => (d with { Garrison = invalid }).Validate()); + foreach (var invalid in new MeleeDefinition?[] { null, new(1, double.PositiveInfinity, 30, 5), new(0, 12, 30, 5), + new(1, 12, 30, 30), new(1, 12, 30, 5, Cleave: true) }) + Assert.Throws(() => (d with { Enemies = [d.Enemies[0] with { Melee = invalid }] }).Validate()); + var active = ContentLoader.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "expedition.json"))); + Assert.Throws(() => (active with { Enemies = active.Enemies.Select(e => e.Boss is null ? e : e with { Melee = new(40, 80, 90, 30) }).ToArray() }).Validate()); + foreach (var file in new[] { "foundation.json", "emberwatch.json" }) + { + var old = ContentLoader.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, file))); + Assert.Null(old.Garrison); Assert.All(old.Enemies, e => Assert.Null(e.Melee)); + RejectedWithoutMutation(new Simulation(old), new PlaceGarrison(0)); + } + } +} diff --git a/docs/AGENT_HANDOFF.md b/docs/AGENT_HANDOFF.md new file mode 100644 index 0000000..f91dca2 --- /dev/null +++ b/docs/AGENT_HANDOFF.md @@ -0,0 +1,109 @@ +# Agent handoff — start here + +Updated 2026-10-21. Read this file first, then the specific design sections needed for the assigned task. No reconstruction of the previous chat or original Java repository is necessary. + +## Thirty-second status + +| Item | State | +|---|---| +| Branch / session baseline | `Ege-redevelop` / `856cb2d` (`New-Direction`); session began clean | +| Latest owner instruction | Continue developing according to the plan; the earlier documentation-only pause is superseded | +| Accepted next direction | Road warriors, stronger animation, an unlockable frontier map, persistent mastery and useful results graphs | +| Completed new milestone | **FR-01 Road squad kernel**, verified in Core and headless scenarios | +| Next implementation task | **FR-02 Animated squad slice**: actual Garrison controls, reach preview, animation, boss warnings and balance on Emberwatch | +| Then | **FR-03** mission catalog/Stoneford → **FR-04** profile/map unlocks → **FR-05/06** mastery/challenges and graphs → **FR-07** combined evaluation | +| Deferred | Resonance Circuits/Resolve until the squad prototype demonstrates whether either adds a distinct decision | +| Current playable game | Twelve waves, four stages, three tower families/six paths, Shatter/Ignition, seven relics, three drafts, optional Overruns, Menders/Captains/Raiders and Bellwarden | +| Not implemented | Garrison player controls/animation, second map, world map, persistent profile/unlocks, mid-wave saves, final art or Circuits | +| Last recorded verification | 96 tests pass; existing Godot smoke passes with a sandbox certificate-store diagnostic; squad/no-squad command comparisons and earlier regressions pass | +| Current work | FR-01 source/tests/content/docs are local changes; no dependency change, new export, commit or push | + +The research/handoff is committed in `856cb2d`; FR-01 source and updated documents are currently local/uncommitted. Preserve them. A separate checkout needs these changes as well as the baseline; the branch name alone does not transfer uncommitted files. The existing Windows ZIP and rendered captures predate FR-01. Normal Godot play still shows three tower cards and does not expose squads yet. + +## Read in this order + +1. [Road squad kernel](ROAD_SQUAD_KERNEL.md): implemented commands, road reach/travel, combat ordering, provisional values, animation/event contract and measured squad losses. +2. [Frontier campaign proposal](FRONTIER_CAMPAIGN_PROPOSAL.md): accepted direction, maps/progression, research and **FR task acceptance criteria**. FR-01 is checked; FR-02–FR-07 remain pending. +3. [Development progress](DEVELOPMENT_PROGRESS.md): latest evidence, historical package evidence, limitations and next tasks. +4. [Architecture decision](ARCHITECTURE_DECISION.md) and [game design](GAME_DESIGN_DOCUMENT.md): Core/Game boundary and existing combat/economy rules. +5. [Master roadmap](REDESIGN_EVOLUTION_ROADMAP.md): wider scope and release gates. The FR sequence supersedes Circuits-first work. + +[EXPEDITION_REWORK.md](EXPEDITION_REWORK.md) contains the existing balance witnesses and their limits. [PLAYABLE_BUILD.md](PLAYABLE_BUILD.md) is the player-facing control guide. The earlier Java audit and retirement manifests are historical reference, not active requirements. + +## Next reviewable slice: FR-02 + +The authoritative squad is implemented. Connect it to the playable game in small patches: + +- Add a separate Garrison card and selection/occupancy rendering. It costs 120 gold, occupies one permanent foundation, deploys three Shieldguards and cannot be sold/rebuilt in this prototype. Do not represent it as an ordinary projectile tower. +- Add visible rally and retreat controls plus keyboard equivalents. Snap the preview to the road and call `IsSquadRallyReachable`; command radius is **access distance plus road travel**, not a circular footprint. Use `PlaceGarrison`, `RallySquad` and `RetreatSquad` without moving entities in Godot. +- Render walk, anticipation/contact/recovery, defend, hurt and fall from positions/timers/events. Pause and speed change presentation throughput, never hit rules. Explain that guards recover/regroup only during planning and otherwise have finite health. +- Show each guard's engagement and health, excess enemies passing, and clear unit selection. Basic melee intentionally preserves chill/oil for towers. +- Distinguish the Bellwarden's new 60-tick cleave warning/radius from its existing reinforcement rally warning. It never stops for guards. Captains are blockable but their 40-damage hits defeat an 80-health guard in two blows. +- Extend actual board/control/key smoke coverage and inspect 1×/2×/4× and pause. Compare deliberate Garrison and no-Garrison layouts and purchase timing; the first `--squad` witness is substantially weaker in several cases. Preserve useful alternatives before broadening the roster. + +Keep Core's verified death/release, travel and cooldown rules intact. No dead actor may retain a block, attack or pay twice. Export and inspect the next coherent playable slice; no fresh squad package or animation has been verified yet. + +Do not start a broad troop roster, Resolve, Circuits, terrain rerouting or an engine migration in this patch. Stoneford/profile unlocks follow this slice. + +## Code entry points + +| Location | Relevance | +|---|---| +| `Redesign-Evolution/Core/Definitions.cs` / `State.cs` | Validated content, commands, entity state, enemy movement and wave report contracts | +| `Core/Simulation.cs` | Command validation/mutation, authoritative 60 Hz tick, combat, outcomes and checksum | +| `Core/Simulation.Squads.cs` / `SquadDefinitions.cs` / `SquadState.cs` | Garrison/rally/retreat, movement/contact, melee/recovery, events/checksum and validated rules | +| `Core/Simulation.Enemies.cs` | Mender healing, boss warnings/rallies/enrage and scaled enemy definitions | +| `Core/Simulation.Effects.cs` / `EffectState.cs` | Status ownership, reaction consumption, damage attribution, ground/echo rules | +| `Core/Simulation.Expedition.cs` / `ExpeditionDefinitions.cs` | Relic offers/modifiers, contract forecasts and wave rewards | +| `Core/Route.cs` / `EnemySpatialIndex.cs` | One immutable authored route, projection/road reach for guards, bounded enemy queries; no arbitrary rerouting | +| `Game/GameRoot.cs` and partials | Current scene/controller/UI. Loads `expedition.json` directly; stage/reward display assumes the current expedition | +| `Game/ArenaCanvas.cs` and partials / `AudioCues.cs` | Current procedural rendering/events and synthesized audio; presentation has no gameplay authority | +| `Game/Content/expedition.json` | Active balance data. `emberwatch.json` and `foundation.json` are earlier regression inputs | +| `Infrastructure/ExpeditionStrategy.cs` / `SimRunner/ExpeditionRunner.cs` | Published automated command witnesses; not live autoplay | +| `Tests/SquadTests.cs` / `ExpeditionTests.cs` / `EnemyAbilityTests.cs` | Squad kernel cases, full-run reproducibility and prior encounter coverage | +| `Game/SmokeHarness.cs` / repository-root `scripts/dev.ps1` | Actual UI integration and supported build/export workflow | + +Paths abbreviated after the first row are relative to `Redesign-Evolution/`, except the explicitly marked repository-root script. + +## Commands and environment + +Windows/PowerShell. SDK pinned to **10.0.400**, Godot **4.7.2 .NET**, target **net8.0**. Use the repository wrappers; do not change the machine's execution policy. Setup requires the SDK/runtime prerequisites and network access to fetch the pinned engine/templates/packages. It does not install the SDK itself. + +```powershell +git status --short +git branch --show-current +.\dev.cmd setup # only if the workspace-local toolchain is absent +.\dev.cmd test +.\dev.cmd smoke +.\dev.cmd run +``` + +After building, reproduce the existing strategies: + +```powershell +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --balance +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --balance --risk +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --balance --squad +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --foundation +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --evolution +``` + +`--balance` covers seeds 1/7/42 and specialized/passive controls. It returns success when the batch terminates; **inspect individual outcomes**, since controls are meant to lose. `--squad` reserves foundation 3 and attempts recruitment before wave 3, then uses the existing purchase priorities. This opt-in witness reports squad damage/kills/casualties/engagement ticks. Frost wins seeds 1/42, fire wins 7; the other specialized squad witnesses lose. Refine strategies and balance deliberately rather than treating batch completion as a balance pass. + +Run `.\dev.cmd benchmark` when combat/query changes warrant profiling. Run `.\dev.cmd export` after the next coherent playable slice; it builds, tests the packaged game and creates the Windows ZIP with notices/play instructions. Inspect actual rendered UI in addition to headless checks. Existing demo/capture flags are implemented in `GameRoot`: `--demo`, `--rewards-demo`, `--boss-demo`, `--paths-demo`, `--capture=` after the engine's `--` separator. When launching background verification processes on Windows, use hidden windows and bounded timeouts. + +Outputs are ignored/local and may not exist in a fresh checkout. `.artifacts/tests/foundation.trx` now records 96 tests; `squad-balance.jsonl`, `squad-no-garrison-balance.jsonl`, `editor-smoke.log` and `spatial-benchmark.json` record this delivery. `.artifacts/windows/` and `Redesign-Evolution-Emberwatch-Windows.zip` are older exports; the progress ledger labels their historical hash/evidence. If a sandbox prevents NuGet auditing, use the environment's permission mechanism or report the limitation; do not suppress audits. Current smoke passed despite a sandbox root certificate-store diagnostic. + +## Important design limits + +- Blocking interacts with slow/area damage, but the first squad purchase plan loses more often than its no-Garrison equivalents. Automatic wins establish solvability, not enjoyment or universal balance. Review the recorded losses before tuning or claiming FR-02 complete. +- Current combat witnesses last roughly 5.5–7.5 minutes plus planning. The 25–40-minute full-run target is not achieved. Do not pad the campaign by chaining duplicate twelve-wave encounters. +- Profile/unlock persistence does not exist. Before advertising it, add versioning, atomic writes, recovery and exact-once award handling. Profile progress and mid-wave saves are separate features. +- A second authored single-route map is feasible without general pathfinding. Multiple entrances, player-built walls and arbitrary rerouting need more design. +- Mastery/Renown should create new options and clear goals. The claim that grind attracts more players remains unproven; no infinite stat treadmill or player-growth promise is part of the accepted plan. +- Field Standards/Resolve, extra regions, more squad classes and online challenges are experiments or later candidates. Do not silently promote them into the first deliverable. +- Collect EX-05 human observations alongside development. Their absence does not block bounded prototypes, but it does prevent claiming the next design is proven fun or balanced. + +## Paste this to the next implementation agent + +> Continue REDESIGN: EVOLUTION on `Ege-redevelop`. Read `AGENTS.md`, `docs/AGENT_HANDOFF.md`, `docs/ROAD_SQUAD_KERNEL.md` and the FR checklist. FR-01 is implemented with 96 passing tests; normal Godot play still lacks squad controls/animation. Preserve the current uncommitted changes and verify the baseline, then implement FR-02 Garrison selection/rally/retreat UI, route-based reach preview, state-driven animation and readable boss cleave warnings. Compare deliberate squad/no-squad builds; current headless squad purchase experiments have documented losses. Extend engine smoke, inspect actual rendering/speed/pause and export the coherent slice. Keep gameplay in Core and update progress/handoff/checklist with actual results. Stoneford/profile unlocks follow; Circuits remain deferred. Do not switch branches, rewrite history or push. diff --git a/docs/ARCHITECTURE_DECISION.md b/docs/ARCHITECTURE_DECISION.md index 3c825fc..b1a2472 100644 --- a/docs/ARCHITECTURE_DECISION.md +++ b/docs/ARCHITECTURE_DECISION.md @@ -62,10 +62,16 @@ Relics rebuild effective attack definitions from unmodified family/branch defini `ExpeditionStrategy` is an opt-in, published command witness for frost/fire/physical, underbuilt and no-defense comparisons. It never operates in normal play. `expedition.json` is active; `emberwatch.json`/`foundation.json` remain regression inputs. Same-build/content determinism is tested across 144 FPS/4×, direct ticks and reference queries. Cross-revision checksums change with new state and are not a save compatibility contract. -Future complete versioned JSON snapshots include tick, IDs, spawn queue, RNG, projectiles, cooldowns, statuses, circuits, bosses and profile modifiers, with content fingerprint and atomic replacement. Invalid saves cannot mutate the current run. No legacy importer. Save/resume is RE3-05, not a first-slice feature. +FR-01 adds a separate optional `GarrisonDefinition`, immutable guard/melee definitions, bounded squad state and `PlaceGarrison`/`RallySquad`/`RetreatSquad` commands. `Simulation.Squads` owns guard travel, swept one-to-one contact, finite health, attack windups/cooldowns, release and between-wave recovery. The route exposes nearest progress and exact road membership; command reach includes the fixed access spur and road distance. There is no new general navigation framework, physics authority or entity system. Missing melee rules in squad-enabled content fail validation. + +The extended tick order is due spawns → guard travel → enemy preparation/status expiry and swept engagement/movement → spatial/escort rebuild → towers/projectiles/echoes/areas → guard melee → enemy melee → existing healing/summons → leaks/outcome and planning recovery. Direct melee shares damage/armor/shield/bounty resolution with a separate guard/Garrison source and never enters the reaction pipeline. Both sides release immediately on death or an order; cancelled windups retain cooldowns. An unstoppable boss has a warned cleave, not a hidden blocking exception by enemy ID. Guard state, orders, contributions and enemy melee/engagement timers participate in the checksum. Earlier content without squads retains its digest representation. + +The [kernel contract](ROAD_SQUAD_KERNEL.md) records exact values, recovery policy and the UI/event boundary. FR-02 must read this state; animation callbacks never determine hit timing. The opt-in `--squad` command witness is a test/balance tool, not normal-play autoplay. Its losses remain evidence for subsequent tuning. + +Future complete versioned JSON snapshots include tick, IDs, spawn queue, RNG, projectiles, cooldowns, statuses, squad engagements, bosses and profile modifiers, plus any retained circuit state, with content fingerprint and atomic replacement. Invalid saves cannot mutate the current run. No legacy importer. Save/resume is RE3-05, separate from profile unlock persistence. ## Controlled retirement Record baseline be87036f68d752d98d096f8f7c7f1a3ad6e082d6 and asset manifest; retire reviewed course/Java application/build files. Preserve their existing Git history. Do not switch branches, rewrite history, delete Git metadata, push or touch unrelated files. No active Java build is required. -Deliver three-wave foundation → six-wave roster → reactions/specializations → expedition/playtest gate → circuits → full run → polished candidate. Update progress on every consequential decision and verified milestone. +Delivered three-wave foundation → six-wave roster → reactions/specializations → expedition → FR-01 squad kernel. Next: FR-02 animated playable squad → Stoneford/profile unlocks → mastery/challenges/graphs → combined evaluation → full run/polish. Reassess Circuits later; it is not a prerequisite for those slices. Update progress on every consequential decision and verified milestone. diff --git a/docs/DEVELOPMENT_PROGRESS.md b/docs/DEVELOPMENT_PROGRESS.md index e5245eb..c13f120 100644 --- a/docs/DEVELOPMENT_PROGRESS.md +++ b/docs/DEVELOPMENT_PROGRESS.md @@ -1,12 +1,38 @@ # Development progress -Updated 2026-10-21. Branch `Ege-redevelop`. This continuation began clean at `0da2b22` (`logic polish`); its changes are uncommitted. No branch switch, history rewrite, commit, push or remote operation was performed. Unrelated files, dependencies and lockfiles were preserved. +Updated 2026-10-21. Branch `Ege-redevelop`. The expedition is in `3748e0d`; the direction/handoff was subsequently committed as `856cb2d`. This implementation session began clean at `856cb2d` after the owner requested development to continue. No branch switch, history rewrite, commit, push or remote operation was performed. Dependencies, lockfiles and unrelated files remain unchanged. -## Current delivery +**Continuing agent: read [AGENT_HANDOFF.md](AGENT_HANDOFF.md) first. FR-01 is complete; FR-02 is next.** Squad combat is implemented in Core/headless scenarios. Garrison controls/animation are not yet exposed in normal Godot play. + +## Latest delivery — FR-01 road squad kernel + +The [frontier plan](FRONTIER_CAMPAIGN_PROPOSAL.md) remains road squad → animation → second map/profile unlocks → mastery/challenges/graphs. FR-00 and FR-01 are complete; FR-02–FR-07 remain pending. [ROAD_SQUAD_KERNEL.md](ROAD_SQUAD_KERNEL.md) records exact commands, values, tick ordering and unresolved balance questions. + +- Implemented optional validated Garrison/guard/melee definitions; one permanent 120-gold foundation and three Shieldguards. Shared occupancy and invalid commands are atomic. +- Added nearest-road access, path-distance rally bounds, road travel/retreat, swept contact, finite one-to-one engagements, attack windups/cooldowns, guard deaths and immediate release. Commands preserve health/cooldowns; no mid-wave recovery. All guards fully heal/revive/regroup on entering planning, with stable identity/statistics. +- Captains are blockable and defeat full-health guards in two hits; Bellwarden moves through troops and warns before a nearby cleave. Melee uses existing armor/shield/bounty rules and separate guard/Garrison credit without consuming tower setup or triggering reactions. Events/state expose the future animation contract. +- Added checksums and 20 squad test cases, plus opt-in CLI `--squad` witnesses with contribution/casualty/engagement reports. No new library, general entity framework or UI implementation. +- Current changes are local/uncommitted. Include source and docs when handing work to another checkout. The existing Windows ZIP predates FR-01; no export or new rendered squad capture was produced. + +| Current verification | Result | +|---|---| +| Baseline before edits | 76 passing tests; initial sandbox NU1900 warnings resolved by a locked restore from the official NuGet feed; audits remained enabled | +| `dev.cmd test` after FR-01 | Zero build warnings/errors; **96 passed**, zero failed | +| `dev.cmd smoke` | Existing twelve-wave UI flow passes; sandbox logs a root certificate-store diagnostic. No squad UI is claimed | +| Squad correctness | Atomic orders/occupancy, path reach/corners, fast contact/capacity, death/recovery, exact damage/bounty credit, status preservation, Captain attrition, boss warning/escape, pause/speed and grid/reference comparisons | +| Complete squad expedition | Seed-42 frost reproduces under direct ticks, reference queries and 144 FPS/4×; wave and damage/kill totals reconcile | +| Baseline balance batch | All 18 scenarios terminate; frost/fire/steel retain preceding winning life totals across seeds 1/7/42; controls retain their losses | +| Squad balance batch | All 18 terminate; frost wins seeds 1/42, fire wins 7, remaining specialized witnesses lose. This early purchase/layout is not balanced; details in kernel report | +| Prior fixtures | Three-wave: 3,004 ticks, 36 kills, zero leaks, 180 gold. Six-wave evolution: 9,060 ticks, 151 kills, zero leaks, 975 gold | +| Dense diagnostic | Six matching grid/reference digests; grid mean 1.064–1.204 ms/tick, 5,058 bytes/tick. Measures shared kernel overhead without deployed squads, not FPS or squad animation | + +Current local evidence: `.artifacts/tests/foundation.trx` (now 96 cases), `.artifacts/squad-balance.jsonl`, `.artifacts/squad-no-garrison-balance.jsonl`, `.artifacts/editor-smoke.log` and `.artifacts/spatial-benchmark.json`. The historical expedition evidence below is retained separately. + +## Earlier playable expedition delivery **Phase 2: expedition intervention, EX-01 through EX-04 complete.** Player feedback identified repetition, weak rewards and superficial difficulty. The active game now loads `expedition.json`: twelve waves/four stages, three earned drafts from seven relics, optional Overruns, Menders, Raiders, armored Captains and a guarded/rallying/enraged Bellwarden. Starting economy, branch payoff and formations were retuned. Godot presentation and the independent C# simulation are retained. -The self-contained Windows package and fresh extraction passed integration checks; packaged reward/boss captures were inspected. **EX-05 human playtest/decision gate is next.** Resonance Circuits remain planned and unimplemented. This is an expedition prototype, not a finished commercial game or validated 25–40-minute run. +The preceding self-contained Windows package and fresh extraction passed integration checks; packaged reward/boss captures were inspected. EX-05 human observations remain a parallel evaluation gate. Resonance Circuits are deferred for reassessment after the squad/map work. This is an expedition prototype, not a finished commercial game or validated 25–40-minute run. The package/capture evidence below is historical; the current kernel has not been re-exported. ## Completed work @@ -21,7 +47,7 @@ The self-contained Windows package and fresh extraction passed integration check The prior `emberwatch.json` and `foundation.json` files are unchanged this session. They remain regression scenarios and do not constrain active design. Academic requirements and legacy formats remain retired. -## Verification +## Earlier expedition verification Toolchain: SDK 10.0.400, Godot 4.7.2 .NET, net8.0. Export bundles .NET 8.0.30; diagnostic development runtime reports 8.0.0. Review framework support before release. Locked NuGet restore/audit refreshed successfully with normal network access after initial sandbox NU1900 warnings; audits were not disabled. @@ -44,12 +70,12 @@ Toolchain: SDK 10.0.400, Godot 4.7.2 .NET, net8.0. Export bundles .NET 8.0.30; d Checksums changed because ability/reward/report state is included. Cross-revision equality is not a compatibility promise. Earlier spatial/effect tests retain per-tick event comparisons. Human enjoyment, final balance and a manual full playthrough are not established by the integration harness. -## Artifacts +## Earlier expedition artifacts - Launch `.\dev.cmd run`, or `.artifacts/windows/Redesign-Evolution.exe` with neighboring PCK/runtime directory. - Share `.artifacts/Redesign-Evolution-Emberwatch-Windows.zip`; extract the whole archive and run `windows/Redesign-Evolution.exe`. Current play instructions and Godot/.NET notices are included. - Verified ZIP: **72,976,047 bytes**, SHA-256 `4634c68129b738f162650eb8ca69a558c0330b9764047109c9706ea076072adb`; adjacent `.zip.sha256` matches. -- `.artifacts/tests/foundation.trx`: 76-test report; historical filename retained. +- `.artifacts/tests/foundation.trx`: historical filename reused; the latest run now contains 96 cases, not the earlier 76. - `.artifacts/expedition-balance.jsonl`, `expedition-risk.jsonl`: eighteen runs each with wave/resource/tower details. Reproduce with SimRunner `--balance` and `--balance --risk`. - `.artifacts/expedition-regressions.json`: five earlier CLI scenarios and current digests. - `.artifacts/expedition-benchmark.json`: dense combat diagnostic, not GPU/FPS measurement. @@ -62,15 +88,16 @@ Full comparison: [EXPEDITION_REWORK.md](EXPEDITION_REWORK.md). Standard witnesse Winning combat takes about 5.5–7.5 minutes at 1×, plus untimed human planning. One map, seven relics and fixed formations limit replayability. Profiles, save/resume, Circuits, Sapper disruption, a second map, accessibility/settings and final art remain open. Procedural art/audio remains prototype quality. Do not pad waves or add permanent bonuses to compensate for weak decisions. -No implementation blocker. Delivery checks are complete. Human observations are the next design input, not a permission requirement for routine fixes or already authorized work. +No implementation blocker. FR-01 ends at the independently testable kernel boundary. UI/animation and deliberate Garrison balance are the next milestone. Human observations remain necessary design evidence; their absence does not block bounded prototypes. The sandbox certificate-store diagnostic does not fail the existing smoke flow but prevents calling its engine log clean. ## Exact next work -1. **EX-05:** record at least three human runs. Note first-relic time, saved/regretted purchases, unclear deaths, repeated/ignored relic choices, priority changes and declined contracts. Tune frost dominance, reward diversity and contract value from evidence; retain useful fire/physical alternatives and meaningful losses. -2. After EX-05, **RE2-04:** implement validated directed links (four-tile range, one outgoing/two incoming, reject cycles/self/duplicates/invalid endpoints), between-wave rewiring and removal on sale. Document upgrade/link persistence. Add one-hop reaction charge, cap three, limit generation to once per source per 60 ticks; no recursive empowered generation. -3. Define useful empowered payloads for every branch, distinguishing them from Split Lens/Barbed Relay/Echo Spindle. These relics occupy part of the earlier circuit concept; revise the signature if it adds no distinct decision. Prove two useful layouts under the expedition economy before expanding it. -4. **RE2-05/RE3-03:** telegraphed disruption and a second authored map once the loop merits them. Additional content and longer runs must create new decisions. Keep the expedition playable and prior regressions passing; update this ledger after each verified slice. -5. Do not switch branches, rewrite history or push. Preserve unrelated files. No further approval is required for the already authorized milestones. +1. **FR-02 controls:** inspect/preserve FR-01 changes and read the kernel contract. Add Garrison card/selection/occupancy, route-based reach preview, rally/retreat controls and clear permanent-foundation/recovery information. Wire commands to Core; no duplicated combat in Godot. +2. **FR-02 animation/balance:** render walk/anticipation/contact/recovery/defend/hurt/fall and distinct cleave warnings. Inspect 1×/2×/4× and pause, extend actual UI smoke, compare deliberate Garrison/no-Garrison strategies, then export the coherent slice. Current `--squad` losses are documented evidence, not a reason to assert balance or blindly buff permanent power. +3. **FR-03 → FR-04:** introduce the mission catalog and distinct Stoneford battlefield, then the frontier UI and versioned persistent unlocks. Verify clear → unlock → application restart, recovery and duplicate-award prevention. Profile progress is separate from mid-wave saves. +4. **FR-05 / FR-06 → FR-07:** add one alternative doctrine/challenge and reconciled local result graphs; evaluate the combined slice before expanding content. Full acceptance criteria and dependencies live in the frontier checklist. +5. **EX-05 alongside these slices:** record at least three human runs. Note first-relic time, saved/regretted purchases, unclear deaths, repeated/ignored relic choices, priority changes and declined contracts. Tune frost dominance and rewards from evidence. Reassess Circuits/Resolve after squad/map evaluation; neither is the next implementation task. +6. Keep the expedition playable and prior regressions passing; update the progress, checklist and handoff after each verified slice. Stay on `Ege-redevelop`, preserve unrelated work and do not rewrite history or push. The assigned implementer can make routine decisions within this scope without another approval round. ## Original baseline evidence diff --git a/docs/FRONTIER_CAMPAIGN_PROPOSAL.md b/docs/FRONTIER_CAMPAIGN_PROPOSAL.md new file mode 100644 index 0000000..1e789e2 --- /dev/null +++ b/docs/FRONTIER_CAMPAIGN_PROPOSAL.md @@ -0,0 +1,122 @@ +# Frontier campaign and road warriors — research and proposal + +2026-10-21. Research/design proposal responding to the player's request for maps, unlocks, warriors, stronger presentation and a longer progression chase. The existing expedition is the playable baseline. Research began at `3748e0d`; implementation resumed from the committed handoff at `856cb2d` on `Ege-redevelop`. + +**Current status:** the owner resumed development. FR-01 is implemented and tested in Core/headless scenarios; **FR-02 UI/animation is next**. See [ROAD_SQUAD_KERNEL.md](ROAD_SQUAD_KERNEL.md) for exact implemented rules and balance evidence, and [AGENT_HANDOFF.md](AGENT_HANDOFF.md) for continuation. Maps/profile unlocks and later systems remain unimplemented; prices, timings and experiments remain provisional. + +## Recommendation + +Build toward a frontier campaign in which players unlock distinct battlefields and recruit small specialist squads to fight alongside their towers. Prioritize one animated road squad, a second authored battlefield and persistent first-clear/unlock progress. Reevaluate Circuits after this prototype: troop positioning may provide a more visible and understandable signature than another attack modifier. + +Difficulty should increase through choices under pressure. Longer progression should reward mastery and experimentation. Whether either attracts or retains more players is a hypothesis to test; feature lists, positive store reviews and developer descriptions cannot establish that causal claim. + +## Comparable games — first-party research + +Sources checked 2026-10-21. These are observations about mechanics and developer intent, not measurements of retention or sales effects. + +| Reference | Verified feature | Design lesson for this project | +|---|---|---| +| [Kingdom Rush Battles: Paladin Barracks, Ironhide support](https://support.ironhidegames.com/support/solutions/articles/4000223657-paladin-barracks-skills-breakdown-defend-the-lines-in-kingdom-rush-battles) | Soldiers engage and block enemies, extending the time other defenses can attack | A road squad can multiply positioning value while having limited damage and survivability. This comparison does not imply migrating our game to PvP. | +| [Thronefall, developer/publisher Steam description](https://store.steampowered.com/app/2239150/Thronefall/) | Different maps, recruitable troops, unlockable weapons/perks and optional difficulty mutators | Combine places to discover, loadout choices and voluntary challenge. Do not attempt its full city-building/action scope. | +| [Emberward, developer Steam description](https://store.steampowered.com/app/2459550/Emberward/) | Player-shaped mazes, spatially demanding towers, run-specific maps/equipment and persistent talents | Changing the spatial problem can refresh the same tower roster. We should author different layouts before considering unrestricted maze construction. | +| [The Last Spell, developer posts from May–June 2021](https://store.steampowered.com/news/posts/?appids=1105670&enddate=1623158663&feed=steam_community_announcements) | The developers distinguish direct power growth from unlocks that introduce new play styles; they describe progression as onboarding and a source of objectives after losses | Persistent rewards can support both struggling and experienced players. The historical post explicitly discusses tuning unlock pace; it is not evidence of current balance or a universal progression formula. | +| [Kingdom Rush Genesis: Knights Order devlog, 2026-05-14](https://www.ironhidegames.com/News/Details/472) | The described unit upgrades change armor, helmets and banners | Make growth visible in the battlefield silhouette, not solely in a menu. This is a development preview, not a claim about released content. | + +## The player experience + +Choose an unlocked frontier location → inspect its threats and squad loadout → build, rally and defend → earn relic choices → win or fall → see what worked and what unlocked → choose the next destination or a harder contract. + +Keep three layers distinct: + +- **Profile:** unlocked maps, squad variants, mastery records and cosmetic honors persist. +- **Expedition:** gold, tower specializations, chosen relics, lives and temporary squad development reset. +- **Battle:** rally positions, engagements, wounds and attack cooldowns change moment to moment. + +Initially, each campaign location launches a complete expedition. A continuous journey carrying state across several battlefields is a separate, larger feature. Do not accidentally multiply the current run length by attaching multiple twelve-wave maps end to end. + +## 1. A frontier map with useful unlocks + +The campaign map should show settlements, linked roads, an explicit unlock requirement, first-clear rewards and difficulty badges. A locked location promises something specific: a different battlefield or squad option. It should not be an unexplained padlock. + +First delivery: Emberwatch and **Stoneford**, a bridge defense with fewer overlapping tower positions and authored fast/armored formations. Complete Emberwatch to open Stoneford. Use map-specific wave composition and planning geometry; a recolored copy is not enough. Keep an unlocked location available permanently. Replay any available location. + +Later candidate branches: **Glassfen**, testing limited safe rally positions and mobile supports, and **Iron Quarry**, testing separated coverage and siege pressure. These are proposals, not an approved four-map production commitment. Branching between locations should follow the two-map proof. + +Preserve access to the current tower families and six paths. Give the player the starter squad immediately when this system is introduced. Subsequent unlocks add choices rather than withholding the mechanic that makes the new game interesting. + +## 2. Warriors on the road + +Prototype one **Garrison**, limited to one per battlefield, occupying a tower foundation and costing the same run currency. It deploys three Shieldguards. The player selects the squad and places a rally marker on a reachable road segment within the Garrison's command radius. Warriors move there, engage and fight; they do not teleport. + +Initial rules to validate: + +- Each living guard can engage one ordinary enemy. Unengaged enemies can continue past: three units cannot stop an infinite column. +- Engaged enemies attack their guard. Finite health and enemy attack cadence make unsupported blocking fail. No invulnerable body wall. +- Moving the rally point releases engagements and costs travel time. A retreat order returns the squad toward its Garrison; relocating is a tactical decision, not an instant escape-and-reset exploit. +- Fallen guards return during the next planning phase. No endless mid-wave replacement loop, roster permadeath or repeated gold tax in the first prototype. +- Bosses have an explicit readable response: they cannot be fully immobilized and have a telegraphed attack dangerous to clustered troops. Validate the rule separately for Captains; do not hide immunity behind a stat. +- Starting melee attacks must not automatically consume chill/oil setup and steal the tower finisher's role. Status-consuming specialist attacks are a later explicit choice. + +The first interesting interaction already exists in our combat system: hold a group inside an Ignition field or Shatter radius, then decide whether to retreat before the guard line breaks. Support-targeting towers remove Menders while the squad contains ordinary attackers. This links troops to the current investment instead of adding a detached minigame. + +Later options, only after the starter works: Pikemen with stronger anti-Raider engagement; Runeguards that improve elemental setups; a medic with low blocking capacity. Unlock/select alternatives with explicit trade-offs. Avoid a full RTS roster and individual skill-bar micro. + +**Signature experiment — Field Standards:** a squad's rally banner marks a limited area where troops and tower reactions cooperate. First test the basic positioning benefit. Only if it needs another decision, prototype bounded reaction-earned Resolve spent on a brief brace or reposition benefit. Do not ship Resolve and Resonance Circuits together without evidence that they solve different problems. Infinite stall, reaction feedback loops and mandatory Garrison purchases are the main balance risks. + +## 3. Progression with a worthwhile chase + +Use one clearly explained persistent resource, provisionally **Renown**, earned at encounter milestones with extra first-clear rewards. Defeat retains earned progress. Awards must be idempotent: replaying a result screen or restarting after a crash cannot pay twice. Pay for progress through encounters, not raw spawned-enemy counts, which would reward farming reinforcements. + +Spend Renown on alternative squad doctrines and additional starting options. First wins open locations and challenge tiers. Mastery objectives should teach useful interactions: hold a wave with a mixed defense, defeat an escorted Captain, or complete a map with a different squad. Show progress and the next reward. Avoid objectives that require intentionally poor play or thousands of trivial kills. + +Longer optional goals can award armor appearances, banners, map medals and specialist variants. Players who enjoy a substantial completion chase can pursue these while essential tools remain available. No energy timer or daily-login requirement is needed. + +Initial pacing hypotheses to test: demonstrate the starter squad in the first battle; show meaningful mastery progress in the first session; provide the first new option within one or two completed attempts. These are test targets, not measured promises. Do not require several hours before the core strategy becomes available. + +Small permanent stat upgrades remain an optional later experiment. If used, keep a finite cap and a fresh-profile victory benchmark; separate standardized challenge records from profile power. Increasing enemy health to cancel an unlimited upgrade treadmill adds tuning cost without ensuring new decisions. + +## 4. Harder encounters players can understand + +Offer Standard, Veteran and authored challenge contracts, eventually extending into selectable threat modifiers. Keep modifiers visible before a run or wave. Examples: Raiders arrive in a second staggered push; an announced siege unit threatens a Garrison; two supports appear in separated formations. Introduce one new behavior safely before combining it with old pressures. + +Tune the ordinary expedition after adding troops: holding enemies amplifies area damage and existing slows. Compare Garrison and no-Garrison builds, not only the three earlier scripted strategies. Aim for more than one viable investment plan. Stronger play should overcome pressure without a mandatory profile-level threshold. + +Shared seed challenges could later support friendly competition. Begin with offline challenge codes and local records; online leaderboards, servers and PvP are separate product decisions. Do not infer multiplayer demand from the phrase 'competitive games.' + +## 5. Presentation and useful graphs + +The visual target is a coherent stylized 2D frontier with animated units and readable impacts. Keep Godot/C#; neither a language migration nor a 3D rewrite solves the current content problem. + +Build a polished animation sample around one squad and one battlefield: walk, idle, attack anticipation/contact/recovery, defend, stagger and fall. Give towers aim/recoil/charge and projectiles clear trails/impacts. Use consistent ground contact, shadows, scale, palette and upgrade silhouettes. Environmental motion and restrained lighting should support rather than obscure the battlefield. Add density limits and reduced-motion controls before broadening effects. Original or appropriately licensed assets need provenance. + +Gameplay timing remains authoritative in Core. Animation follows simulation state/events and must not determine hit timing. Preview attacks at 1×/2×/4× and pause, and test at smaller window sizes. No final-art quality is claimed until an actual rendered slice is reviewed. + +Post-run graphs should explain decisions: gold earned/spent by wave; damage contributions; leaks and life loss by wave; squad engagement time and casualties. Do not invent 'damage prevented' from unblocked travel time. Compare records with map, content version, seed, difficulty, profile modifiers, relics and squad attached. Store local summaries first; external analytics is unnecessary for the prototype. + +## Fit with the repository + +- `GameRoot` currently loads one content file directly; stage/relic presentation assumes twelve waves and fixed reward checkpoints. A mission catalog and configuration-driven HUD must precede new mission lengths. +- `MapDefinition` and `Route` support one immutable orthogonal path and authored foundations. A second single-route map is practical now. Multiple simultaneous entrances, freeform walls and rerouting need additional navigation/target-progress design. +- FR-01 now supplies bounded friendly combatants, melee/engagement state and commands in Core. Stable IDs and explicit tick ordering resolve deaths and release engagements. FR-02 must present these authoritative states rather than recreating combat in Godot callbacks. +- Infrastructure currently loads content and provides command witnesses; there is no profile persistence. Versioned profile writes, backup/recovery and exact-once awards are prerequisites for promising permanent unlocks. This is smaller than full mid-wave save/resume, which remains separate. +- Existing tower statistics and `WaveReport` support part of a results dashboard. Per-wave spending/damage and troop utility need new explicit recording. Avoid retaining every combat event indefinitely. +- FR-01 verification records 96 passing tests, the existing Godot smoke flow and opt-in squad/no-squad command witnesses. The older Windows ZIP and rendered captures predate squad work; squad UI and final art have not been inspected or delivered. + +## Dependency-aware implementation checklist + +P0 = first prototype, P1 = follow-on; S/M/L/XL = relative complexity. Checkboxes distinguish verified work from pending features. MVP candidate scope remains subject to prototype evidence. The human observations in EX-05 remain an evaluation gate, not a reason to freeze bounded prototypes. This sequence takes priority over the earlier Circuits-first plan. + +- [x] **FR-00 Research/design** | P0 | deps EX-04 | S | MVP planning | AC: first-party comparisons, concrete troop/map/progression rules, code constraints and testable candidate tasks recorded. +- [x] **FR-01 Road squad kernel** | P0 | deps FR-00 | L | MVP candidate | AC: one Garrison/three guards; valid rally/retreat; finite engagements; enemy melee/death/release rules; no permanent stall; pause/speed/reference determinism; unchanged earlier fixtures. Verified in Core and headless scenarios; UI/animation and balance remain FR-02. +- [ ] **FR-02 Animated squad slice** | P0 | deps FR-01 | M | MVP candidate | AC: actual selection/rally UI, reachable-position preview, readable attack/hurt/fall states, boss counter telegraph, 1×/4× and paused render inspection; useful Garrison and no-Garrison witnesses on Emberwatch. +- [ ] **FR-03 Mission catalog/Stoneford** | P0 | deps FR-00 | L | MVP candidate | AC: select either of two authored maps with distinct formations; no hardcoded twelve-wave HUD assumptions; valid route/foundations; both maps terminate and have at least two viable builds. +- [ ] **FR-04 Frontier/profile unlocks** | P0 | deps FR-03 | L | MVP candidate | AC: clear Emberwatch → visible Stoneford unlock → restart application → unlock retained; atomic versioned profile/backup recovery; repeated completion cannot repay; failure keeps earned milestone progress; resetting a run does not erase profile. +- [ ] **FR-05 Mastery/challenges** | P1 | deps FR-02, FR-04 | M | MVP candidate | AC: one alternative squad doctrine and one authored higher-difficulty modifier; visible criteria/progress/rewards; new profile can finish Standard; no raw-kill farming incentive. +- [ ] **FR-06 Results graphs** | P1 | deps FR-02, FR-04 | M | MVP candidate | AC: two local run summaries compare wave economy, damage and squad utility with full context; amounts reconcile with authoritative totals; no unbounded event history. +- [ ] **FR-07 Combined evaluation** | P0 | deps FR-02, FR-04, FR-05, FR-06 | L | MVP candidate | AC: regression/build/export checks pass; observe at least three human runs; document repeated choices, first unlock time, squad clarity, losses and desire to replay; explicit keep/change/discard decision before expanding content. + +Playable slices: A = FR-01 → FR-02 on existing Emberwatch; B = FR-03 → FR-04 with persistent destination progress; C = FR-05 → FR-06 → FR-07. FR-03 can be developed independently of the squad once its content/HUD contract is defined. Every slice must leave the previous expedition playable. + +## Open design risks + +Blocking can make frost/area damage even stronger; troop weakness must be readable rather than arbitrary. Relic dilution can make new unlocks feel like a penalty; offer pools need compatibility rules. A world map can become a cosmetic menu if its locations play alike. Repeated Renown collection can become an optimal low-risk farm. Animation and art quantity can outgrow the production budget. Resolve/Circuits can duplicate one another. Evaluate these in the small slices above before commissioning a broad roster or campaign. diff --git a/docs/GAME_DESIGN_DOCUMENT.md b/docs/GAME_DESIGN_DOCUMENT.md index 2290836..9280013 100644 --- a/docs/GAME_DESIGN_DOCUMENT.md +++ b/docs/GAME_DESIGN_DOCUMENT.md @@ -1,6 +1,6 @@ # REDESIGN: EVOLUTION — Game design -Version 0.4, 2026-10-21. Reactions, specializations and the expedition intervention are implemented; Circuits and the full-length run remain planned. Numbers below describe active `expedition.json`. The earlier six-wave `emberwatch.json` retains its own unchanged balance as a regression fixture. Numbers are design hypotheses, not inherited assignment requirements. +Version 0.5, 2026-10-21. Reactions, specializations and the expedition are playable. FR-01 squad combat is implemented in Core/headless scenarios; its player controls/animation are next in FR-02. Circuits are deferred for reassessment after the squad/map work. Numbers below describe active `expedition.json`; the earlier six-wave `emberwatch.json` retains its own balance as a regression fixture. Values are design hypotheses, not inherited assignment requirements. ## Implemented expedition: Emberwatch @@ -67,11 +67,19 @@ Overrun is a per-wave, opt-in contract, reset after clearing. Add `2 + floor(wav Wave reports retain kills, breaches, duration, total income, clear/bonus payment and contract outcome. The current result UI summarizes these; the CLI includes every wave and tower. Persistent comparison analytics remain planned. +## Road squads — Core implemented, player integration pending + +One 120-gold Garrison commits a foundation and deploys three 80-health Shieldguards. Each holds one ordinary enemy, deals modest impact damage and can retreat or rally along the road within a 230-unit travel budget. Extra enemies pass. Melee does not consume chill/oil or trigger reactions, preserving the tower finisher's role. Guards cannot heal or respawn during combat; entering planning fully heals/revives and regroups them for free. Captains can be held but defeat a full-health guard in two hits. Bellwarden keeps moving and warns before cleaving nearby guards. + +The [kernel contract](ROAD_SQUAD_KERNEL.md) owns exact values, command validation, tick ordering, recovery and event rules. The system is available through Core commands and the opt-in CLI `--squad` witness. Normal Godot play does not yet show a Garrison card, troops or cleave warnings. Do not treat the 96-test result as animation or usability verification. + +The first squad purchase experiment replaces foundation 3's tower and often loses where the preceding build wins. FR-02 must test deliberate placement/purchase timing alongside no-Garrison alternatives, add actual controls and state-driven animation, and expose the boss warning before calling the squad slice playable or balanced. + ## Full run — planned Use human observations to validate the eventual 25–40-minute pacing target. Eighteen waves/three acts was an initial hypothesis; retain the current four-stage structure if it produces stronger decisions. Expand relic diversity toward twelve, forecast two waves, add distinct contract formations and vary maps by seed. Do not pad duration with redundant waves. No hidden adaptive hard counters. -Currency creates opportunity costs between towers, branches and links. Avoid mandatory click-to-collect income. Two authored maps receive validated variations. Godot editor authoring comes first; a player map editor is optional. +Currency creates opportunity costs between towers, branches and the Garrison. Links are a later candidate if retained. Avoid mandatory click-to-collect income. Two authored maps receive validated variations. Godot editor authoring comes first; a player map editor is optional. ## Tower evolution — implemented @@ -114,7 +122,9 @@ Credit actual reaction damage and kills to the triggering tower, including after Ignition is the first temporary terrain interaction. Frozen ground, freeform walls, flooding and water/electricity are deferred. Oil currently belongs to an enemy, not a ground surface. Enemy disruption and broader terrain counterplay remain RE2-05. -## Resonance Circuits — after expedition playtesting, not implemented +## Resonance Circuits — deferred experiment, not implemented + +Reassess after FR-07 against troop positioning, relics and Field Standards/Resolve. The following numbers describe the earlier proposal, not mandatory MVP work or an approved next implementation task. Directed links: four-tile maximum, 25 gold initial cost, one outgoing/two incoming ports. Reject cycles/invalid endpoints before spending. Rewire between waves without another fee; no investment refund for rewiring. Removing towers removes their links. @@ -139,7 +149,7 @@ Menders restore 12 health to eligible allies within 105 units every 150 ticks, p **Implemented Bellwarden:** personal 45% guard and 20 armor open during a 90-tick windup before each rally. Rally every 300 ticks: two Raiders placed behind the boss, at most twelve total. At half health, enrage latches, speed rises 25%, rally interval halves and the next rally is brought closer without skipping its warning. Once reinforcements run out the personal guard/armor remain down. External Wardens can still protect it. All timers pause. No repeatable summon bounty. Kill supports, manage the fast rush, exploit exposed windows; the boss bar reports both phases. -The earlier concept of summoning supports and suppressing a circuit is superseded for this slice. Reevaluate disruption only after Circuits work; adding it is not a requirement merely because it appeared in an earlier document. +The earlier concept of summoning supports and suppressing a circuit is superseded for this slice. Reevaluate disruption against the tower/squad battlefield; it does not require implementing Circuits first. Its precise behavior remains a separate design task. ## Replayability and progression diff --git a/docs/PERFORMANCE_BASELINE.md b/docs/PERFORMANCE_BASELINE.md index b381326..ad7ee51 100644 --- a/docs/PERFORMANCE_BASELINE.md +++ b/docs/PERFORMANCE_BASELINE.md @@ -1,6 +1,21 @@ # Simulation performance baseline -## Current expedition kernel check +## Current FR-01 kernel check + +Rechecked 2026-10-21 after road squad state/commands/combat were added. The unchanged dense workload has no Garrison, so this measures shared kernel overhead rather than deployed squad performance. All six runs retain checksum `2069a65603354f4bea4bab800bc2b86050d2a4248587be48699b0e7c213c7929`. Raw report: `.artifacts/spatial-benchmark.json`. Same Debug/runtime/machine/method below; timing is diagnostic, not a controlled speedup claim. + +| Round | Query method | Mean ms/tick | Median ms/tick | p95 ms/tick | Allocated bytes/tick | +|---|---|---:|---:|---:|---:| +| 1 | Reference scan | 4.246 | 4.183 | 6.497 | 4,999 | +| 1 | Spatial grid | 1.204 | 1.170 | 2.012 | 5,058 | +| 2 | Spatial grid | 1.111 | 1.067 | 1.860 | 5,058 | +| 2 | Reference scan | 4.235 | 4.219 | 6.171 | 4,999 | +| 3 | Reference scan | 4.180 | 4.123 | 6.253 | 4,999 | +| 3 | Spatial grid | 1.064 | 1.038 | 1.755 | 5,058 | + +Enemy melee state adds 24 bytes to each newly spawned enemy in this one-spawn-per-tick workload. The squad is bounded to three members, but active squad allocation/timing is not measured by this diagnostic. It does not establish rendered performance or eliminate the later need to profile active troops/effects. A separate complete squad expedition reproduces across grid/reference queries and 144 FPS/4× as correctness evidence. + +## Historical expedition kernel check Rechecked 2026-10-21 after relics, healing and boss state were added. The existing 64-tower/1,001–2,500-enemy workload still agrees across all six grid/reference runs: checksum `2069a65603354f4bea4bab800bc2b86050d2a4248587be48699b0e7c213c7929`. Raw report: `.artifacts/expedition-benchmark.json`. Same Debug/runtime/machine/method described below; graphical capture also ran during part of this diagnostic, so timings are not a controlled before/after comparison. diff --git a/docs/REDESIGN_EVOLUTION_ROADMAP.md b/docs/REDESIGN_EVOLUTION_ROADMAP.md index c8ec6f3..e04fd08 100644 --- a/docs/REDESIGN_EVOLUTION_ROADMAP.md +++ b/docs/REDESIGN_EVOLUTION_ROADMAP.md @@ -2,6 +2,8 @@ Approved 2026-10-19; updated 2026-10-21. P0=critical, P1=required MVP, P2=optional. Complexity S/M/L/XL is relative effort, not a calendar promise. Unchecked means pending unless stated. Completion requires evidence in DEVELOPMENT_PROGRESS.md. Player feedback reprioritized the expedition loop ahead of Circuits; [EXPEDITION_REWORK.md](EXPEDITION_REWORK.md) records that decision. +**Current continuation:** implementation resumed from `856cb2d`. FR-01 is complete in Core/headless scenarios; **FR-02 animated squad controls and balance on Emberwatch are next**. Read [AGENT_HANDOFF.md](AGENT_HANDOFF.md), the [kernel contract](ROAD_SQUAD_KERNEL.md) and the [frontier checklist](FRONTIER_CAMPAIGN_PROPOSAL.md). The FR slices supersede the earlier instruction to implement Circuits immediately after EX-05. + ## Phase 0 — Audit, vision, retirement - [x] **RE0-01 Audit/baseline** | P0 | deps none | M | MVP | AC: source/assets/history/build/test inventory and confirmed defects recorded. @@ -25,10 +27,10 @@ Milestone / Slice A: six-wave foundation implemented and automatically verified. - [x] **RE2-01 Effect/branch/reaction definitions** | P0 | deps RE1-05 | M | MVP | AC: extend the implemented roster/spawn catalogs so effects, exclusive branches and reactions are tunable without tower-code edits; invalid values/IDs/references produce actionable errors. - [x] **RE2-02 Reactions** | P0 | deps RE2-01 | L | MVP | AC: Shatter/Ignition consumption, stacking, attribution and trigger limits tested. - [x] **RE2-03 Specialization** | P1 | deps RE2-02 | L | MVP | AC: six exclusive branches change mechanics/visual identity and preserve choices. -- [ ] **RE2-04 Circuits** | P0 | deps RE2-03, EX-05 | L | MVP | AC: valid links, charge, empowered attacks/removal/UI; no cycles or recursive generation; at least two useful layouts within the expedition economy. -- [ ] **RE2-05 Terrain/counterplay** | P1 | deps RE2-04 | M | MVP | AC: overlays and telegraphed Sapper disruption create counterable decisions without invalid routes. +- [ ] **RE2-04 Circuits** | P2 | deps RE2-03, EX-05, FR-07 | L | Stretch; deferred pending reassessment | AC if retained: valid links, charge, empowered attacks/removal/UI; no cycles or recursive generation; at least two useful layouts that add decisions distinct from relics and squad positioning. Record keep/change/discard before implementation. +- [ ] **RE2-05 Terrain/counterplay** | P1 | deps FR-02, EX-05 | M | MVP | AC: overlays and telegraphed Sapper disruption create counterable decisions without invalid routes; verify tower and squad responses. -Milestone / Slice B: expedition combines specializations, reactions and circuits. The playable expedition below is an intermediate delivery; the signature milestone remains open until Circuits and counterplay are verified. +Milestone / Slice B: expedition combines specializations, reactions and useful squad positioning with readable counterplay. The playable expedition below is an intermediate delivery; FR-07 and RE2-05 supply the remaining evidence. Circuits are an optional experiment, not a prerequisite for this milestone. ## Expedition intervention — before additional systems @@ -42,12 +44,12 @@ Milestone / Slice B0: an escalating expedition with earned build changes and rea ## Phase 3 — Depth and replayability -- [ ] **RE3-01 Run structure** | P0 | deps RE2-05, EX-05 | L | MVP | AC: full-run pacing validated toward 25–40 minutes including planning; about twelve useful relics and varied forecast contracts reproduce by seed. Partial: twelve waves/seven relics/Overruns implemented; expand only when additional decisions justify length. -- [ ] **RE3-02 Enemies/boss** | P1 | deps RE3-01 | L | MVP | AC: six distinct behavioral roles and two Bellwarden phases have visible tells, counters and behavior coverage within the final circuit economy. Partial: healing, rally/guard/enrage implemented; Sapper and broader encounter coverage pending. -- [ ] **RE3-03 Maps/authoring** | P1 | deps RE2-05 | M | MVP | AC: two maps/variations validate entrances/exits/foundations and useful circuit layouts. -- [ ] **RE3-04 Profiles** | P1 | deps RE3-01 | M | MVP | AC: challenge unlocks/alternative starting options/fresh profiles/standardized challenges; no grind needed for standard victory; permanent power bonuses require a separate balance decision. -- [ ] **RE3-05 Saves** | P0 | deps RE3-02, RE3-04 | L | MVP | AC: mid-wave load yields identical continuation including projectiles/status/boss/circuit/RNG; corrupt saves preserve current run. -- [ ] **RE3-06 Analytics** | P1 | deps RE3-05 | M | MVP | AC: tower efficiency/resources/defeats/reactions/wave results, with seed/content/difficulty/profile context. +- [ ] **RE3-01 Run structure** | P0 | deps RE2-05, EX-05, FR-07 | L | MVP | AC: full-run pacing validated toward 25–40 minutes including planning; about twelve useful relics and varied forecast contracts reproduce by seed. Partial: twelve waves/seven relics/Overruns implemented; expand only when additional decisions justify length. +- [ ] **RE3-02 Enemies/boss** | P1 | deps RE3-01 | L | MVP | AC: six distinct behavioral roles and two Bellwarden phases have visible tells, counters and behavior coverage within the tower/squad economy. Partial: healing, rally/guard/enrage implemented; Sapper and broader encounter coverage pending. +- [ ] **RE3-03 Maps/authoring** | P1 | deps FR-03, FR-04 | M | MVP | AC: two maps/variations validate entrances/exits/foundations and useful tower/squad layouts; shared authoring checks cover both. FR-03/04 supply the initial map/unlock slice; this task completes the wider authoring gate. +- [ ] **RE3-04 Profiles** | P1 | deps FR-04, FR-05 | M | MVP | AC: challenge unlocks/alternative starting options/fresh profiles/standardized challenges; no grind needed for standard victory; permanent power bonuses require a separate balance decision. Verify the FR profile prototype across the full content set. +- [ ] **RE3-05 Saves** | P0 | deps RE3-02, RE3-04 | L | MVP | AC: mid-wave load yields identical continuation including projectiles/status/boss/squad engagements/RNG and every retained gameplay system; corrupt saves preserve current run. Separate from FR-04 profile persistence. +- [ ] **RE3-06 Analytics** | P1 | deps FR-06 | M | MVP | AC: tower efficiency/resources/defeats/reactions/wave results, with seed/content/difficulty/profile context. Extend the local FR-06 summaries; mid-wave saves are not a prerequisite for result graphs. Milestone / Slice C: replayable 25–40-minute complete run. @@ -71,6 +73,8 @@ Milestone / Slice D: reproducible tested release candidate. ## Order and creative experiments -Completed: RE0-02 → RE0-03 → RE1-01 → RE1-02 → RE1-03 → RE1-04 → RE1-05 → RE2-01 → RE2-02 → RE2-03 → EX-01 → EX-02 → EX-03 → EX-04. Next EX-05 → RE2-04 → RE2-05. Keep the expedition export playable and prior three/six-wave fixtures passing at each step. RE3-03 can proceed after RE2-05; RE5-01 can overlap presentation work. +Accepted direction, 2026-10-21: [Frontier campaign and road warriors](FRONTIER_CAMPAIGN_PROPOSAL.md) records first-party references, persistent map unlocks, a small controllable squad, mastery, animation and results graphs. FR-00 research and FR-01 simulation are complete; FR-02 through FR-07 remain pending. That checklist owns their identifiers, priorities, dependencies, complexity, acceptance criteria and status. The owner resumed implementation after the documentation handoff. + +Completed: RE0-02 → RE0-03 → RE1-01 → RE1-02 → RE1-03 → RE1-04 → RE1-05 → RE2-01 → RE2-02 → RE2-03 → EX-01 → EX-02 → EX-03 → EX-04 → FR-00 → FR-01. Next playable slices: **FR-02** on Emberwatch; **FR-03 → FR-04** for Stoneford/persistent destinations; **FR-05 / FR-06 → FR-07** for mastery, graphs and combined evaluation. FR-03 can proceed independently once its content/HUD contract is defined, but playable squad integration is first. Collect EX-05 observations alongside development. Keep the expedition playable and prior three/six-wave fixtures passing at each step. FR tasks deliver portions of the broader phase gates; do not mark those gates complete without their remaining acceptance evidence. -Battlefield Memory, Evacuation Couriers and Echo Blueprints are not hidden release requirements. Limit first prototypes to three focused engineering days; retain only observable new decisions surviving readability/playtest review. Document discarded findings. +Reassess Circuits after FR-07; it no longer blocks maps, profile unlocks or the signature slice. Field Standards/Resolve, Battlefield Memory, Evacuation Couriers and Echo Blueprints are experiments, not hidden release requirements. Limit first experiments to three focused engineering days; retain only observable new decisions surviving readability/playtest review. Document discarded findings. Later regions, broad squad rosters and online competition also remain outside the first handoff milestone. diff --git a/docs/ROAD_SQUAD_KERNEL.md b/docs/ROAD_SQUAD_KERNEL.md new file mode 100644 index 0000000..711a3fc --- /dev/null +++ b/docs/ROAD_SQUAD_KERNEL.md @@ -0,0 +1,75 @@ +# FR-01 — road squad kernel + +Implemented 2026-10-21 from `856cb2d` on `Ege-redevelop`. This is the simulation milestone. Normal Godot play still has three tower cards; Garrison selection, rally controls, animations and visible melee warnings are **FR-02**, not implemented here. + +## Commands and content + +`GameDefinition.Garrison` is an optional, separately validated structure, not a projectile tower. `EnemyDefinition.Melee` defines retaliation explicitly for every enemy in a squad-enabled mission. The older three/six-wave fixtures omit these fields. `expedition.json` supplies the provisional values below without changing existing tower, wave, reward or enemy movement values. + +- `PlaceGarrison(foundation)`: spend 120 run gold, occupy one foundation and create three guards with stable IDs. One Garrison for the entire run; no sale/rebuild command in this prototype. Towers and Garrison cannot share a foundation. Invalid placement spends nothing and emits no event. +- `RallySquad(position)`: accept a finite point on the authored road centerline. Command reach is the foundation-to-road access distance plus route travel to the marker, at most 230 world units. It is not a circle that permits shortcuts across a winding route. The nearest road projection is the fixed entrance; ties choose earlier progress. `IsSquadRallyReachable` exposes the same rule for the future preview. +- `RetreatSquad()`: release opponents and walk along the road to the entrance, then back to the building. Rally/retreat cancels pending strikes but retains cooldowns, health and casualties. Orders never teleport or heal. Repeated identical orders are rejected without mutation. + +Movement occurs during unpaused wave ticks. During planning, orders change the destination; the next wave starts deployment. The access spur is straight and the road traversal follows the immutable orthogonal route. This does not implement freeform navigation, obstacle avoidance or arbitrary rerouting. + +## Provisional combat values + +| Defender | Health | Impact damage | Speed | Reach | Attack interval / warning | +|---|---:|---:|---:|---:|---| +| Each Shieldguard | 80 | 8 | 100 units/s | 20 units | 60 / 15 ticks | + +| Enemy | Melee damage | Reach | Interval / warning | Blocking response | +|---|---:|---:|---|---| +| Runner | 8 | 24 | 60 / 20 ticks | One guard | +| Bulwark | 20 | 24 | 90 / 30 ticks | One guard; armor reduces guard damage | +| Warden | 10 | 24 | 60 / 20 ticks | One guard; escort shielding still applies | +| Mender | 6 | 24 | 90 / 30 ticks | One guard; existing healing remains active | +| Raider | 10 | 24 | 42 / 14 ticks | One guard; excess raiders pass | +| Captain | 40 | 28 | 90 / 30 ticks | Blockable; two hits defeat a full-health guard | +| Bellwarden | 70 | 76 | 180 / 60 ticks | Never blocked; warned cleave hits every nearby living guard | + +One second is 60 ticks. Guard/enemy damage is not scaled by the existing wave health multiplier. Boss enrage still changes the existing movement/rally behavior; it does not secretly shorten the new cleave warning. A cleave's area follows the advancing boss and samples actual guard positions at contact. Moving out of reach during the warning avoids the hit. Killing the boss before contact cancels it. + +Each stationary guard can engage one ordinary enemy. Guards only acquire opponents after reaching their rally marker; moving/retreating/fallen guards cannot block. Swept route contact prevents fast enemies tunneling through an available guard. Excess enemies pass, including when a fourth enemy crosses three occupied guards. Stable enemy/guard IDs resolve ties. Corpses immediately release both sides. + +Basic melee uses the shared armor/shield/damage/bounty resolution, with separate guard/Garrison contribution. It never enters the status/reaction pipeline: guards do not consume chill/oil, trigger Shatter, apply statuses, fork or echo. Relic attack modifiers still belong to towers. Actual damage is capped by remaining enemy health and bounty is paid once. + +No healing or resurrection occurs while a wave is active, including at the building. On entering the next planning phase, all three guards fully heal/revive and regroup at the building for free. IDs, accumulated damage, kills, casualties and engagement ticks persist. The rally marker and retreat order persist. Victory/defeat releases engagements but does not revive units. These are explicit prototype recovery rules, not a save system. + +## Simulation and presentation contract + +Tick order: due spawns → guard travel → existing enemy preparation/status expiry and swept engagement/movement → spatial/escort rebuild → towers/projectiles/echoes/areas → guard melee → enemy melee → existing enemy healing/summons → leaks and outcome → planning recovery if applicable. + +Tower/effect damage can kill an opponent before its due retaliation. Guard damage also precedes enemy retaliation. Both windup and cooldown are integer tick state, frozen by pause. Repositioning cancels a windup but cannot reset its cooldown. Wave completion still depends only on pending spawns and living enemies, never on fallen or traveling guards. + +`GarrisonState.Guards` exposes position/previous position, travel state, health, engagement, attack target/contact tick and cooldown. `EnemyState` exposes engaged guard, melee target/contact tick and cooldown. New events cover building, rally/retreat, engagements/releases, both windups, guard hits/falls and recovery. Ordinary enemy `Hit` events from guards have `EffectId = "melee"`. FR-02 must render these states/events; animation must never decide hit timing. + +Checksums include squad placement/orders, positions, health, IDs, engagement pairs, attack timers and contributions. Content without a Garrison retains the prior checksum representation. No persistence format or cross-version checksum compatibility is promised for the active expedition. + +## Verification and balance evidence + +- `dev.cmd test`: **96 passed**, including 20 new squad cases; zero build warnings/errors. Cases cover atomic commands, route reach/corners, fast contact/capacity, deaths, recovery, exact bounty/credit, setup preservation, Captain attrition, boss escape, pause, different speeds/render rates and grid/reference reproducibility. A complete seed-42 frost squad expedition reproduces across direct ticks, reference queries and 144 FPS/4×. +- `dev.cmd smoke`: existing twelve-wave Godot UI flow passes. The sandbox printed a root certificate-store diagnostic; this is recorded rather than treated as a clean engine log. This check covers the existing UI, not squad controls or artwork. +- Existing no-squad frost/fire/steel witnesses still win seeds 1/7/42 with the preceding life totals. Three-wave fixture: 3,004 ticks, 36 kills, no leaks. Six-wave evolution: 9,060 ticks, 151 kills, no leaks. +- A new opt-in `--squad` witness reserves foundation 3, attempts recruitment from the planning phase before wave 3, then follows the existing purchase/relic priorities while skipping that foundation's tower. It uses ordinary commands and is never enabled in normal play. + +After `dev.cmd test`, reproduce the experiment: + +```powershell +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --balance --squad +dotnet Redesign-Evolution/SimRunner/bin/Debug/net8.0/Redesign.SimRunner.dll --strategy frost --seed 42 --squad +``` + +| Strategy | Seed 1 | Seed 7 | Seed 42 | +|---|---|---|---| +| Frost + squad | Win, 5 lives | Lose, wave 6 | Win, 6 lives | +| Fire + squad | Lose, wave 12 | Win, 7 lives | Lose, wave 12 | +| Steel + squad | Lose, wave 6 | Lose, wave 6 | Lose, wave 6 | + +All 18 squad-batch scenarios terminate, including basic/hold/none controls. Squad damage, kills, casualties and summed guard engagement ticks appear in the CLI report; engagement time is not a measurement of damage prevented. Raw local reports: `.artifacts/squad-balance.jsonl` and `.artifacts/squad-no-garrison-balance.jsonl`. + +This witness spends money earlier and removes a tower slot; it does not isolate the value of blocking or establish an optimal squad layout. The frequent losses identify purchase timing, location and survivability as FR-02 balance questions. Do not claim general balance or enjoyment from the three winning cases. Keep strong no-Garrison alternatives and compare deliberate squad strategies before increasing permanent power or broadening the roster. + +## Next: FR-02 + +Add the Garrison card/selection and occupied-foundation rendering, road-marker reach preview, rally/retreat controls and paused orders. Derive walk, anticipation, attack, defend, hurt and fall animation from Core. Show boss cleave reach/warning distinctly from its existing rally windup. Explain permanent foundation commitment and planning recovery. Extend the actual UI smoke harness, inspect 1×/2×/4× and pause, then tune and compare useful Garrison/no-Garrison builds. Export only after that coherent playable slice; the existing Windows ZIP predates FR-01.