Repository navigation
Weapon Attack Resolution Pattern
How the Weapon Attack phase resolves declared attacks across all units and players. The pattern keeps WeaponAttackResolutionPhase thin — an orchestrator that flattens the attack space, runs gates, delegates resolution, and finalizes results.
The phase is decomposed into three distinct layers, mirroring the Movement phase's separation of concerns:
-
Phase (orchestrator) — flattens the attack space with
BuildAttackQueue(), runs optional gates, delegates to the resolver, and publishes commands. - IWeaponAttackResolver — mandatory sequential dice/damage pipeline (to-hit → direction → LOS/cover → hit location). Every attack passes through the same steps.
-
IAttackResolutionGate — optional pre-attack skip conditions (chain-of-responsibility). Currently only
AttackerPartialCoverGate.
None of these is a literal copy of IMovementInterruptHandler. The movement handler chain is optional any-may-fire (each handler independently decides whether its hazard applies). The weapon resolution pipeline is mandatory and fixed-order — to-hit, direction, LOS, hit location, damage — every attack, always. These are structurally different problems that share a thin‑phase approach, not a common interface.
WeaponAttackResolutionPhase (thin orchestrator)
│
├─ BuildAttackQueue() ← flatten players → units → weapons
│
├─ IAttackResolutionGate[] ← movement-like chain (optional skips)
│ AttackerPartialCoverGate
│
├─ IWeaponAttackResolver ← mandatory pipeline (dice + damage)
│
├─ FinalizeAttackResolution() ← apply damage, publish commands,
│ hull breach, crits, consciousness
│
└─ CalculateEndOfPhasePsrs() ← accumulated PSR checks at phase end
private readonly record struct AttackQueueItem(
IPlayer Player,
IUnit Attacker,
Weapon? Weapon,
IUnit? TargetUnit,
WeaponTargetData WeaponTargetData,
LocationSlotAssignment PrimaryAssignment
);Produced once by BuildAttackQueue(). Contains everything needed to resolve a single weapon shot. The queue is built in initiative order (player order from Game.InitiativeOrder, then each player's units, then each unit's DeclaredWeaponTargets).
Walks _playersInOrder, then each player's units in _unitsWithTargets, then each unit's DeclaredWeaponTargets. The flattened unit list (allUnits) is materialised once at the top of the method rather than recomputed per weapon target. For each weapon target it resolves the mounted Weapon (via unit.GetMountedComponentAtLocation<Weapon>) and the target IUnit (via allUnits). The result is a flat List<AttackQueueItem> that the main loop iterates.
public interface IWeaponAttackResolver
{
AttackResolutionData ResolveAttack(
IUnit attacker,
IUnit target,
Weapon weapon,
WeaponTargetData weaponTargetData,
IBattleMap battleMap);
}A self-contained, stateless service (constructor-injected IRulesProvider, IDiceRoller, IDamageTransferCalculator, IToHitCalculator). Every attack goes through its single public method, which runs:
-
To-hit —
IToHitCalculator.GetToHitNumber, thenIDiceRoller.Roll2D6. -
Miss — returns early with
IsHit = false. -
Direction —
IUnit.GetAttackDirection(firing arc →HitDirection). -
LOS / partial cover —
battleMap.GetLineOfSight+IRulesProvider.HasPartialCover. -
Hit location —
DetermineHitLocationfor standard weapons,ResolveClusterWeaponHitfor clusters (LRMs, SRMs, etc.).
Private helpers DetermineHitLocation and ResolveClusterWeaponHit are tested through the public API or via direct reflection in resolver-specific tests. The attack direction comes from the shared IUnit.GetAttackDirection extension, so the weapon resolver and the physical attack resolver agree on the column of the hit location table.
public interface IAttackResolutionGate
{
bool ShouldSkip(IUnit attacker, IUnit target, Weapon weapon,
LocationSlotAssignment primaryAssignment, IBattleMap battleMap,
IRulesProvider rulesProvider, ILogger logger);
}A chain-of-responsibility that mirrors IMovementInterruptHandler.Check. Each gate inspects the attack context and returns true to skip resolution (with logging), false to proceed. Currently registered in the phase:
private readonly IReadOnlyList<IAttackResolutionGate> _attackResolutionGates =
[
new AttackerPartialCoverGate()
];AttackerPartialCoverGate implements the leg-weapon partial-cover skip: it reverses LOS (target → attacker) and checks HasPartialCover combined with CanPartBeCovered(primaryAssignment.Location).
Stays in the phase because it touches phase-local state (_accumulatedDamageData) and publishes commands. Each call:
- Applies damage to the target via
target.ApplyDamage(...). - Handles external heat if present.
- Publishes a
WeaponAttackResolutionCommand(broadcasts the resolution to clients). - Calculates and publishes hull breach (via
Game.HullBreachCalculator). - Calculates and publishes critical hits (via
Game.CriticalHitsCalculator). - Runs
ProcessConsciousnessRollsForUnit. - Accumulates component hits and destroyed parts into
_accumulatedDamageDatafor the end-of-phase PSR check.
After all attacks resolve, iterates accumulated damage data and runs Game.FallProcessor.ProcessPotentialFall for each mech that took damage during the phase. This enforces the BattleTech rule that PSRs from accumulated damage are rolled at phase end, not per attack.
Enter()
│
├─ Clear _accumulatedDamageData
├─ Build _playersInOrder from Game.InitiativeOrder
├─ PrepareUnitsWithTargets()
│
└─ ResolveAllAttacks()
│
├─ Guard: Game.BattleMap == null → throw
│
├─ BuildAttackQueue() → List<AttackQueueItem>
│
├─ foreach item in queue:
│ │
│ ├─ Guards: weapon != null, target has Position, attacker has Position
│ │
│ ├─ Gates: foreach gate in _attackResolutionGates
│ │ └─ gate.ShouldSkip(...) → true → skip this item
│ │
│ ├─ Resolve: _resolver.ResolveAttack(...) → AttackResolutionData
│ │
│ └─ Finalize: FinalizeAttackResolution(player, attacker, weapon, target, data)
│
├─ CalculateEndOfPhasePsrs()
│
└─ Game.TransitionToNextPhase(Name)
Key points:
-
BuildAttackQueue()runs once. The queue is materialised eagerly, then iterated with a simpleforeach. - Gates run before resolution. If any gate returns
true, the attack is skipped (logged) and the loop advances to the next queue item. - The resolver is a black box: it receives the full context and returns a complete
AttackResolutionData. The phase never inspects intermediate pipeline state. - All post-resolution effects (damage, commands, crits, consciousness) happen in
FinalizeAttackResolution, keeping the loop body short.
-
Phase starts:
Enter()→ clears accumulated damage, builds_playersInOrder, callsPrepareUnitsWithTargets(). -
Queue built:
BuildAttackQueue()produces items. One item: Player A's Archer fires LRM-15 at Player B's Wolverine. -
Guard check: weapon is mounted (
Weaponis not null), Wolverine hasPosition, Archer hasPosition→ proceed. -
Gate check:
AttackerPartialCoverGate.ShouldSkip(...)— Archer's LRM-15 is not a leg-mounted weapon →false(do not skip). -
Resolver:
-
_toHitCalculator.GetToHitNumber→ needs 7+. - Roll: 4 + 5 = 9 → hit.
-
target.GetAttackDirection(attacker)→ Archer is in Wolverine's front arc →HitDirection.Front. - LOS check → partial cover detected; covering hex recorded.
-
ResolveClusterWeaponHit: cluster roll 8 → 12 missiles hit; 3 clusters of 5 damage resolve against hit locations (partial cover absorption applied perDetermineHitLocationwhere legs are hit).
-
-
Finalize: damage applied to Wolverine,
WeaponAttackResolutionCommandpublished, hull breach/crits/consciousness handled. - Next items: loop continues for remaining queue items.
-
Phase end:
CalculateEndOfPhasePsrs()runs; Wolverine took 30+ damage in the phase →FallProcessoremits a PSR command. -
Transition:
Game.TransitionToNextPhase(PhaseNames.Heat)
Physical attacks reuse the weapon resolution payload so the standard damage pipeline can consume them without a parallel damage implementation. The adapter boundary is explicit:
-
PhysicalAttackResolutionDatawrapsAttackResolutionDataandAttackHitLocationsData, plus the physical-specific attack type, attacking limb, damage and the piloting skill roll requirements (IReadOnlyList<PhysicalAttackPsrRequirement>). -
BaseGamedamage application consumesIsHit, the per-location damage and the attack direction. Logging observesTotalDamage, the location roll and the (empty) aimed-shot rolls. -
ExternalHeat,ClusterRollandMissilesHitare neutral placeholders in the physical path — physical attacks generate no heat, have no cluster roll and hit no missiles. A miss is reported withHitDirection.Front. - The adapter values are set in one private helper in
PhysicalAttackResolver, so the fake weapon-only fields stay in a single documented place instead of being scattered through the resolver.
Three layers of testing, mirroring the Movement phase:
| Layer | What is tested | How |
|---|---|---|
| Resolver (unit) |
ResolveAttack, DetermineHitLocation, ResolveClusterWeaponHit
|
Construct WeaponAttackResolver with mocked dependencies, call ResolveAttack or invoke private methods via reflection. Tests live in WeaponAttackResolverTests. |
| Gates (unit) | AttackerPartialCoverGate.ShouldSkip |
Construct the gate, call ShouldSkip with controlled game/map state. Tests live in AttackerPartialCoverGateTests. |
| Phase (integration) |
Enter() → full resolution flow, queue ordering, gate interaction, command publishing |
Set up ServerGame with players/units/declared targets, call Enter(), assert commands published. Tests live in WeaponAttackResolutionPhaseTests. |
- Implement
IAttackResolutionGate. Returntruewhen the attack should be skipped. - Register the handler in
WeaponAttackResolutionPhase._attackResolutionGatesat the correct position in the chain. - Write a unit test calling
ShouldSkipwith the conditions that should trigger (and should not) skip.
The pipeline inside WeaponAttackResolver is not pluggable by design (see rationale below). To add a new step:
- Add the step call inside
WeaponAttackResolver.ResolveAttackat the appropriate point in the sequence. - If the new step requires additional dependencies, add them to the constructor.
- Update
AttackResolutionDatato carry any new output if the step produces phase-visible data. - Write unit tests against
WeaponAttackResolver.ResolveAttack.
Add the logic in FinalizeAttackResolution (or extract it into a dedicated finalizer class if the consequence set grows significantly). Follow the existing pattern: mutate game state, publish commands, update _accumulatedDamageData. Write tests against phase-level Enter() or, if extracted, against the finalizer in isolation.
For future reference only: if post-hit ordering becomes fragile or additional post-hit effects are introduced, extract the discrete side-effects of FinalizeAttackResolution (apply damage/heat, publish WeaponAttackResolutionCommand, hull breach, critical hits, consciousness rolls) into IGameAction implementations under Mechanics/WeaponAttack/Actions/, executed via the canonical ProcessInterruptResult-style loop (accumulate commands from action.Process(Game), then publish in order). For this ticket, leave FinalizeAttackResolution intact in the phase, unchanged.
| Concern | Movement interrupts | Weapon resolution |
|---|---|---|
| Chain type | Optional — each handler may or may not fire per segment | Mandatory — every attack passes every step |
| Order | Any handler can stop the chain | Fixed order (to-hit → direction → LOS → location) |
| Result |
null (no fire) or MovementInterruptResult (actions + stop flag) |
Single AttackResolutionData — miss, hit, or cluster |
| Central mutation | Handlers emit IGameActions; phase runs them |
Resolver returns data; phase applies damage + commands |
The interrupt handler chain models independent hazard checks where any one may short-circuit. The weapon resolution pipeline models a sequential calculation where each step depends on the previous. These differ in control flow, result type, and composition. Using the same interface for both would produce leaky abstractions — gates that return "skip the attack" (a natural fit for IMovementInterruptHandler) are already covered by IAttackResolutionGate.
Approaches E (full IAttackResolutionStep pipeline) and F (unified cross-phase framework) from the refactoring analysis are intentionally out of scope. The current three-layer split (orchestrator → resolver → gates) provides the right balance of testability, readability, and extensibility for the foreseeable feature set. If future needs (such as AMS interception, physical attack integration, or phased resolution ordering) demand further decomposition, the pattern can be extended without breaking the existing layers.