From de44a488bb88fd6abd827da74f0efadfb570b3a2 Mon Sep 17 00:00:00 2001 From: Prime Date: Fri, 27 Mar 2026 13:10:34 +0000 Subject: [PATCH] Add SOR ability system reference snapshot and change draft --- proposed_changes_sor_game_abilities.md | 626 ++++ .../SOR.Game/Abilities/AbilityContext.cs | 92 + reference/SOR.Game/Abilities/AbilitySystem.cs | 2533 +++++++++++++++++ .../Abilities/EffectPolymorphicConverter.cs | 100 + .../Models/AbilityAnimationDefinition.cs | 56 + .../Abilities/Models/AbilityDefinition.cs | 80 + reference/SOR.Game/Abilities/Models/Action.cs | 136 + .../SOR.Game/Abilities/Models/Conditions.cs | 130 + .../Abilities/Models/DurationModel.cs | 47 + .../SOR.Game/Abilities/Models/Effects.cs | 252 ++ .../SOR.Game/Abilities/Models/Filters.cs | 134 + .../Abilities/Models/PolyTypeAttribute.cs | 16 + .../SOR.Game/Abilities/Models/Triggers.cs | 148 + 13 files changed, 4350 insertions(+) create mode 100644 proposed_changes_sor_game_abilities.md create mode 100644 reference/SOR.Game/Abilities/AbilityContext.cs create mode 100644 reference/SOR.Game/Abilities/AbilitySystem.cs create mode 100644 reference/SOR.Game/Abilities/EffectPolymorphicConverter.cs create mode 100644 reference/SOR.Game/Abilities/Models/AbilityAnimationDefinition.cs create mode 100644 reference/SOR.Game/Abilities/Models/AbilityDefinition.cs create mode 100644 reference/SOR.Game/Abilities/Models/Action.cs create mode 100644 reference/SOR.Game/Abilities/Models/Conditions.cs create mode 100644 reference/SOR.Game/Abilities/Models/DurationModel.cs create mode 100644 reference/SOR.Game/Abilities/Models/Effects.cs create mode 100644 reference/SOR.Game/Abilities/Models/Filters.cs create mode 100644 reference/SOR.Game/Abilities/Models/PolyTypeAttribute.cs create mode 100644 reference/SOR.Game/Abilities/Models/Triggers.cs diff --git a/proposed_changes_sor_game_abilities.md b/proposed_changes_sor_game_abilities.md new file mode 100644 index 0000000..9d63156 --- /dev/null +++ b/proposed_changes_sor_game_abilities.md @@ -0,0 +1,626 @@ +# Proposed Changes for `SOR.Game/Abilities` + +This document is meant to sit beside the copied reference snapshot in: + +- `reference/SOR.Game/Abilities/` + +It is a practical draft of what should be added or changed in the **current** ability system based on: +- the deck conversion audits in `decks-r1/` +- the cross-deck gap synthesis +- the freshly pulled current source from `SOR/Server/src/SOR.Game/Abilities` + +The goal is not to redesign everything. +The goal is to make a **targeted set of additions** that unlocks a lot more card text cleanly. + +--- + +# Design principles + +1. **Prefer additive changes over rewrites** + - the current system is already strong + - we should extend the model, not tear it up + +2. **Keep JSON authoring coherent** + - new conditions/effects/triggers should look like they belong beside the existing ones + +3. **Favor generally useful primitives** + - e.g. `RepositionUnitEffect` is better than a bespoke “move one friendly unit adjacent to marsh tile” special case + +4. **Preserve reversibility where possible** + - temporary effects should continue to use tracked durations and undo logic + +5. **Support deck conversion first** + - the audited decks are a good real-world test suite + +--- + +# Priority 1 — highest-value additions + +## 1. Trigger frequency caps for Triggered abilities + +## Problem +Current `UsesPerTurn` exists on `Active` only. +That makes these common lines awkward or impossible: +- once per turn +- first time each turn +- first friendly unit each turn + +This came up repeatedly across deck audits. + +## Proposed model change +### File +- `reference/SOR.Game/Abilities/Models/AbilityDefinition.cs` + +### Add +```csharp +// ── Triggered only / shared runtime limiter ───────────────────────────── +/// +/// Maximum times this ability may resolve per turn. +/// 0 or null = unlimited. +/// Intended primarily for Triggered abilities. +/// +public int? TriggerLimitPerTurn { get; set; } +``` + +Optionally, if you want a more semantic flag: +```csharp +public bool FirstTimeEachTurn { get; set; } +``` +but I think `TriggerLimitPerTurn = 1` is cleaner and more general. + +## Engine work +### File +- `AbilitySystem.cs` + +Need per-turn runtime tracking keyed by something like: +- source instance id +- ability name or ability index +- turn number + +Pseudo-shape: +```csharp +Dictionary<(Guid SourceInstanceId, string AbilityKey, int TurnNumber), int> TriggerCounts +``` + +Before resolving a triggered ability: +- look up count +- if `TriggerLimitPerTurn` reached, skip +- otherwise resolve, then increment + +## Why this is high value +This unlocks a huge amount of card text with very little authoring complexity. + +--- + +## 2. First-class `RepositionUnitEffect` + +## Problem +The engine has: +- `PushUnit` +- `PullUnit` +- `DisplaceUnit` +- `GrantMovementControl` + +But many designs want: +- “move target unit 1 tile” +- “another friendly unit may move 1 tile” +- “move into or adjacent to a target tile” + +Push/pull are not the same thing. +Granting MP is only an approximation. + +## Proposed model change +### File +- `Models/Effects.cs` + +### Add polytype + effect +```csharp +[PolyType(typeof(RepositionUnitEffect), "RepositionUnit")] +``` + +```csharp +public sealed class RepositionUnitEffect : Effect +{ + /// + /// Maximum number of tiles the unit may be repositioned. + /// Most first-pass use cases are 1. + /// + public int Tiles { get; set; } = 1; + + /// + /// When true, destination must be adjacent to the source unit. + /// + public bool AdjacentToSource { get; set; } + + /// + /// Optional reference to a previously selected tile target, + /// e.g. "Action1.Target". Useful for “into or adjacent to that tile”. + /// + public string? RelativeToTargetRef { get; set; } + + /// + /// If set, destination must be adjacent to the tile/entity referenced by RelativeToTargetRef. + /// + public bool AdjacentToRelativeTarget { get; set; } + + /// + /// If set, destination may be exactly the referenced tile. + /// + public bool AllowRelativeTargetTile { get; set; } + + /// + /// Optional additional tile legality filters for destination selection. + /// + public Filter[]? DestinationTileFilters { get; set; } +} +``` + +## Engine work +### File +- `AbilitySystem.cs` + +Needs: +1. resolve the unit target +2. compute legal destination tiles +3. if client target selection is required, validate chosen destination +4. move unit directly without consuming normal MP unless intended otherwise +5. fire appropriate move-related triggers if reposition should count as movement + +## Important decision +Decide whether reposition: +- counts as movement for `OnUnitMove` +- triggers “moves onto Marsh” effects + +My recommendation: +- **yes**, unless you deliberately add a flag like `CountsAsMovement = false` + +That will make card text feel more intuitive. + +--- + +## 3. Replacement/prevention timing + +## Problem +The system currently has good post-event triggers, but weak pre-resolution hooks. +That blocks text like: +- if it would die, prevent that death and set health to 1 +- prevent the next damage +- prevent damage this action + +## Proposed additions +### File +- `Models/Triggers.cs` + +Add: +```csharp +[PolyType(typeof(BeforeUnitDeathTrigger), "BeforeUnitDeath")] +[PolyType(typeof(BeforeDamageAppliedTrigger), "BeforeDamageApplied")] +``` + +```csharp +public sealed class BeforeUnitDeathTrigger : TriggerEvent +{ + public string UnitType { get; set; } = "Unit"; + public string Ownership { get; set; } = "Any"; + public Filter? Filter { get; set; } +} + +public sealed class BeforeDamageAppliedTrigger : TriggerEvent +{ + public string SourceOwnership { get; set; } = "Any"; + public string TargetOwnership { get; set; } = "Any"; + public Filter? Filter { get; set; } +} +``` + +### File +- `Models/Effects.cs` + +Add: +```csharp +[PolyType(typeof(PreventDeathEffect), "PreventDeath")] +[PolyType(typeof(PreventNextDamageEffect), "PreventNextDamage")] +[PolyType(typeof(SetHealthMinimumEffect), "SetHealthMinimum")] +``` + +```csharp +public sealed class PreventDeathEffect : Effect { } + +public sealed class PreventNextDamageEffect : Effect +{ + public ValueExpr? MaxAmount { get; set; } +} + +public sealed class SetHealthMinimumEffect : Effect +{ + public int Minimum { get; set; } = 1; +} +``` + +## Engine work +This is the trickiest part. + +You need a pre-resolution pathway where: +- impending lethal damage / death is recognized +- triggered prevention abilities can fire +- damage/death resolution can be altered or canceled + +A practical first pass: +1. before finalizing death, emit `BeforeUnitDeath` +2. allow effects to set a unit-level transient marker like `PreventDeathThisResolution` +3. if set, suppress death and optionally apply `SetHealthMinimum` + +For damage prevention: +1. before applying damage, emit `BeforeDamageApplied` +2. collect prevention effects / caps +3. reduce or cancel the damage payload +4. emit `OnDamagePrevented` if relevant + +## Why this matters +This is what unlocks the most iconic “mercy / covenant / rescue / shield” cards. + +--- + +## 4. Destination-aware movement context + +## Problem +A lot of cards want to know: +- where a unit moved from +- where it moved to +- whether it moved onto a terrain type +- whether it moved from or into an affinity + +Right now movement triggers are not rich enough. + +## Proposed change +### File +- `AbilityContext.cs` + +Extend movement trigger event data with something like: +```csharp +public sealed class TriggerEventData +{ + // existing fields... + public Coord? PreviousTile { get; set; } + public Coord? DestinationTile { get; set; } +} +``` + +Or richer: +```csharp +public Affinity? PreviousTileAffinity { get; set; } +public Affinity? DestinationTileAffinity { get; set; } +``` + +### File +- `Models/Conditions.cs` + +Add: +```csharp +[PolyType(typeof(DestinationTileAffinityIsCondition), "DestinationTileAffinityIs")] +[PolyType(typeof(PreviousTileAffinityIsCondition), "PreviousTileAffinityIs")] +[PolyType(typeof(MovedFromOrIntoAffinityCondition), "MovedFromOrIntoAffinity")] +``` + +Example shapes: +```csharp +public sealed class DestinationTileAffinityIsCondition : Condition +{ + public Affinity Affinity { get; set; } +} + +public sealed class PreviousTileAffinityIsCondition : Condition +{ + public Affinity Affinity { get; set; } +} + +public sealed class MovedFromOrIntoAffinityCondition : Condition +{ + public Affinity Affinity { get; set; } +} +``` + +## Why this matters +It directly improves: +- move triggers +- reposition effects +- terrain identity gameplay + +And it avoids a pile of awkward card-specific hacks. + +--- + +# Priority 2 — strong cleanup additions + +## 5. `NotCondition` + +## Problem +You have `AND`, `OR`, `XOR` but not `NOT`. +That makes inverse card text clunky. + +## Proposed change +### File +- `Models/Conditions.cs` + +Add: +```csharp +[PolyType(typeof(NotCondition), "NOT")] +``` + +```csharp +public sealed class NotCondition : Condition +{ + public Condition Condition { get; set; } = null!; +} +``` + +## Engine work +Add evaluation support in condition resolver. + +## Why it matters +Tiny change, big templating payoff. + +--- + +## 6. More relational conditions and filters + +## Problem +You can target tiles adjacent to units now, which is good. +But we still need things like: +- target unit adjacent to Fort tile +- enemies adjacent to a friendly Fort unit +- unit on or adjacent to Marsh + +## Proposed additions +### File +- `Models/Conditions.cs` + +Add: +```csharp +[PolyType(typeof(IsAdjacentToTileWithAffinityCondition), "IsAdjacentToTileWithAffinity")] +[PolyType(typeof(IsOnOrAdjacentToTileWithAffinityCondition), "IsOnOrAdjacentToTileWithAffinity")] +``` + +```csharp +public sealed class IsAdjacentToTileWithAffinityCondition : Condition +{ + public Affinity Affinity { get; set; } +} + +public sealed class IsOnOrAdjacentToTileWithAffinityCondition : Condition +{ + public Affinity Affinity { get; set; } +} +``` + +### File +- `Models/Filters.cs` + +Add: +```csharp +[PolyType(typeof(IsAdjacentToUnitMatchingFilter), "IsAdjacentToUnitMatching")] +[PolyType(typeof(IsAdjacentToTileMatchingFilter), "IsAdjacentToTileMatching")] +``` + +```csharp +public sealed class IsAdjacentToUnitMatchingFilter : Filter +{ + public string Ownership { get; set; } = "Any"; + public Filter[]? UnitFilters { get; set; } +} + +public sealed class IsAdjacentToTileMatchingFilter : Filter +{ + public Filter[]? TileFilters { get; set; } +} +``` + +## Why it matters +This unlocks a lot of positional deck identity without weird special-cases. + +--- + +## 7. `UntilEndOfSequence` + +## Problem +Interrupt cards and prevention windows often want: +- until this action resolves +- until end of current sequence + +End-of-turn is too broad. + +## Proposed change +### File +- `Models/DurationModel.cs` + +Add: +```csharp +UntilEndOfSequence +``` + +## Engine work +Need a clear definition of “sequence.” +I would define it as: +- one top-level action resolution block +- including all chained actions/effects inside it +- but ending before the next interrupt window / new top-level action + +## Why it matters +This makes Instinct/protection design dramatically cleaner. + +--- + +# Priority 3 — useful but can wait a bit + +## 8. Movement-state-sensitive conditions + +## Problem +Cards often want: +- can’t be blocked while moving +- gains X only during movement + +## Proposed additions +### File +- `Models/Conditions.cs` + +Add: +```csharp +[PolyType(typeof(IsCurrentlyMovingCondition), "IsCurrentlyMoving")] +``` + +```csharp +public sealed class IsCurrentlyMovingCondition : Condition { } +``` + +You may also want a movement-phase duration concept later, but I’d avoid overcomplicating this first. + +--- + +## 9. Source-qualified damage triggers + +## Problem +Some card text wants: +- enemies damaged by **this** +- whenever **this unit** deals damage + +`OnDamageDealt` is broad, but exact source matching is important. + +## Proposed addition +### File +- `Models/Triggers.cs` + +Extend `OnDamageDealtTrigger` with: +```csharp +public Filter? SourceFilter { get; set; } +``` + +or a direct exact-self option. + +--- + +## 10. Tile-control / tile-count conditions + +## Problem +Decks often want: +- if you control a Marsh tile +- if you control 3+ Grove tiles + +## Proposed addition +### File +- `Models/Conditions.cs` + +Add something like: +```csharp +[PolyType(typeof(ControlledTileCountWithAffinityCondition), "ControlledTileCountWithAffinity")] +``` + +```csharp +public sealed class ControlledTileCountWithAffinityCondition : Condition +{ + public Affinity Affinity { get; set; } + public Comparator Comparator { get; set; } = Comparator.GreaterThanOrEqual; + public int N { get; set; } + public string Ownership { get; set; } = "Owner"; +} +``` + +Need to define “control” clearly. Likely: +- occupied by your unit +- or in your starting side / claimed side if such system exists + +If “control” is not fully formalized yet, defer until game-side semantics are settled. + +--- + +## 11. Reveal-result references + +## Problem +Future designs may want: +- reveal top card; if it is X, do Y + +## Proposed addition +Expose reveal results in action context for chained actions. + +This is useful, but not as urgent as the others. + +--- + +# Current features that should be kept and leaned into + +These are already solid and should remain the backbone: +- terrain-conditioned passives +- aura entry/leave triggers +- push/pull displacement +- tile affinity mutation +- draw/discard/zone actions +- ruin randomization pattern +- reversible temporary stat/flag effects +- `ApplyOnEvent` deferred effects +- `ClearOnLeave` / `LingerDuration` on auras +- `ChooseOne` support if it is indeed now functional in execution + +--- + +# Suggested concrete implementation order + +If I were actually patching the code, I would do this order: + +## Phase 1 +1. `TriggerLimitPerTurn` +2. `NotCondition` +3. `RepositionUnitEffect` +4. destination-aware movement context + conditions + +## Phase 2 +5. `BeforeUnitDeath` / `BeforeDamageApplied` +6. `PreventDeathEffect` / `PreventNextDamageEffect` +7. `UntilEndOfSequence` + +## Phase 3 +8. relational adjacency filters/conditions +9. movement-state-sensitive conditions +10. source-qualified damage triggers +11. tile-control conditions + +That order gives the biggest card-authoring payoff early. + +--- + +# Example of what this unlocks immediately + +With just: +- `TriggerLimitPerTurn` +- `RepositionUnitEffect` +- destination-aware movement conditions +- prevention timing + +…a huge amount of the audited deck text becomes native instead of templated compromises. + +Examples: +- “once per turn, when a Spirit enters aura range…” +- “move another friendly unit 1 tile” +- “if it moved onto Marsh, draw 1 then discard 1” +- “if that unit would die, prevent that death and set it to 1” +- “prevent the next damage this sequence” + +That’s a big payoff for a relatively focused tranche of engine work. + +--- + +# Final read + +The current ability system is already good. +This proposal is not about fixing a broken design. +It’s about making a strong design noticeably more expressive with a handful of additions that repeatedly showed up across real deck conversions. + +If you end up copy-pasting parts of this into the live system planning, my strongest recommendation is: + +> implement the things that remove the most templating compromises first, not the flashiest features. + +That means: +- trigger caps +- reposition +- prevention timing +- movement destination awareness + +Those four pull the most weight. diff --git a/reference/SOR.Game/Abilities/AbilityContext.cs b/reference/SOR.Game/Abilities/AbilityContext.cs new file mode 100644 index 0000000..b71412e --- /dev/null +++ b/reference/SOR.Game/Abilities/AbilityContext.cs @@ -0,0 +1,92 @@ +namespace SOR.Game.Abilities; + +using SOR.Game.Abilities.Models; +using SOR.Game.Grid; + +/// +/// Captures the runtime state and bookkeeping needed to evaluate a single ability activation +/// or triggered ability firing — including the source unit, owner, and any chained target results. +/// +public sealed class AbilityContext +{ + public required GameState State { get; init; } + public required string ActorId { get; init; } + + /// The unit (ArchSpirit or Spirit) that owns the ability being resolved. + public CardInstance? Source { get; init; } + + /// + /// Resolved targets keyed by action index (0-based). + /// Populated incrementally as actions resolve, enabling chained targeting. + /// Each value is a list of the resolved target objects (CardInstance, Coord, or string for playerId). + /// + public Dictionary> ResolvedTargets { get; } = new(); + + /// + /// Optional payload from the triggering event — available to Triggered ability actions. + /// + public TriggerEventData? EventData { get; init; } +} + +/// +/// Payload data from the event that caused a Triggered ability to fire. +/// Fields are populated according to the event type; unused fields are null. +/// +public sealed class TriggerEventData +{ + /// Numeric magnitude of the event (damage amount, SP gained, etc.). + public int? Amount { get; init; } + /// Instance ID of the unit/player that caused the event. + public string? SourceId { get; init; } + /// Instance ID of the unit/player the event acted upon. + public string? TargetId { get; init; } +} + +/// +/// Discriminates which kind of entity a runtime trigger event is carrying. +/// Used by AbilitySystem.FireTrigger to match against AbilityDefinition.TriggerEvent. +/// +public enum TriggerEventKind +{ + TurnStart, + TurnEnd, + Channeled, + Ascend, + Transition, + UnitMove, + UnitAttack, + UnitAbilityActivated, + DamageDealt, + UnitDeath, + UnitSentToDiscard, + SpiritSacrificed, + UnitEnterBattlefield, + UnitLeaveBattlefield, + SPGained, + SPSpent, + STGained, + STSpent, + CardDrawn, + TileAffinityChanged, + EnterAuraRange, + LeaveAuraRange, + RuinActivation, + UnitOccupyRuin, +} + +/// +/// Describes a single triggered-event occurrence, used when calling +/// . +/// +public sealed class TriggerOccurrence +{ + public required TriggerEventKind Kind { get; init; } + /// The player whose units/actions caused this event. + public required string ActorId { get; init; } + /// Optional event data (damage amount, source/target IDs, etc.). + public TriggerEventData? Data { get; init; } + /// For unit-related events: the card type string ("Spirit", "ArchSpirit", etc.). + public string? UnitType { get; init; } + /// For channeling events: the card type string ("Spirit", "Terramorpha", etc.). + public string? CardType { get; init; } +} diff --git a/reference/SOR.Game/Abilities/AbilitySystem.cs b/reference/SOR.Game/Abilities/AbilitySystem.cs new file mode 100644 index 0000000..7303f17 --- /dev/null +++ b/reference/SOR.Game/Abilities/AbilitySystem.cs @@ -0,0 +1,2533 @@ +namespace SOR.Game.Abilities; + +using System.Text.Json; +using SOR.Database.Enums; +using SOR.Game.Abilities.Models; +using SOR.Game.Grid; + +/// +/// Evaluates and resolves ability activations and triggered ability firings. +/// +/// Design: +/// • GameEngine delegates directly to the static methods here. +/// • All mutation is on GameState (pure — no DB access). +/// • Triggered abilities are fired inline during engine mutations via FireTrigger. +/// +public static class AbilitySystem +{ + // ── JSON options ─────────────────────────────────────────────────────────── + + private static readonly JsonSerializerOptions _jsonOpts = new() + { + PropertyNameCaseInsensitive = true, + Converters = + { + new System.Text.Json.Serialization.JsonStringEnumConverter(), + // Handle polymorphic deserialization when $type is not the first property. + // The default [JsonPolymorphic] behavior requires $type first for abstract + // base types; admin-tool JSON does not guarantee that ordering. + new EffectPolymorphicConverter(), + new ConditionPolymorphicConverter(), + new TriggerPolymorphicConverter(), + new FilterPolymorphicConverter(), + }, + }; + + // ── Parsing ──────────────────────────────────────────────────────────────── + + public static AbilityDefinition[] ParseAbilities(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + return JsonSerializer.Deserialize(json, _jsonOpts) ?? []; + } + + public static Models.Action[] ParseEffects(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + return JsonSerializer.Deserialize(json, _jsonOpts) ?? []; + } + + // ── Active ability activation ────────────────────────────────────────────── + + /// + /// Entry point for a player manually activating an Active ability on one of + /// their units. Validates conditions, pays cost, resolves targets and effects. + /// + public static GameState ActivateAbility( + GameState state, + string actorId, + string sourceInstanceId, + int abilityIndex, + IReadOnlyList? clientTargets) + { + var player = state.Players[actorId]; + // ArchSpirit is stored in player.ArchSpirit, not player.Field — check both. + var source = player.Field.OfType() + .FirstOrDefault(f => f.InstanceId == sourceInstanceId) + ?? (player.ArchSpirit?.InstanceId == sourceInstanceId ? player.ArchSpirit : null) + ?? throw new GameException("UNIT_NOT_FOUND"); + + if (source.IsExhausted) + throw new GameException("UNIT_EXHAUSTED"); + + if (!source.CanUseAbility) + throw new GameException("UNIT_CANNOT_USE_ABILITY"); + + var abilities = ParseAbilities(source.AbilitiesJson); + if (abilityIndex < 0 || abilityIndex >= abilities.Length) + throw new GameException("ABILITY_INDEX_OUT_OF_RANGE"); + + var def = abilities[abilityIndex]; + + if (def.Type != AbilityType.Active) + throw new GameException("ABILITY_NOT_ACTIVE"); + + if (def.Name is not null && source.DisabledAbilities?.Contains(def.Name) == true) + throw new GameException("ABILITY_DISABLED"); + + source.AbilityUsesThisTurn ??= new(); + source.AbilityUsesThisTurn.TryGetValue(abilityIndex, out int usedThisTurn); + if (usedThisTurn >= def.UsesPerTurn) + throw new GameException("ABILITY_USES_EXHAUSTED"); + + var ctx = new AbilityContext { State = state, ActorId = actorId, Source = source }; + + // Source-side activation conditions are shared with card-active execution. + if (!ValidateSourceActivationConditions(def, ctx, source)) + throw new GameException("ABILITY_CONDITION_NOT_MET"); + + if (def.Cost is { Length: > 0 }) + PayCost(def.Cost, ctx); + + source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; + + ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration); + + return state; + } + + // ── Triggered ability firing ─────────────────────────────────────────────── + + /// + /// Resolve the EffectsJson action list on a non-unit card (Repentance, Instinct, Ruin) + /// immediately when it is channeled. The card itself is the source in the context. + /// + public static GameState FireCardEffects(GameState state, string actorId, CardInstance card, + IReadOnlyList? clientTargets = null) + { + // 1. EffectsJson — backward-compatible flat action list. + // NOTE: Some content pipelines historically wrote AbilityDefinition[] into + // EffectsJson for Repentance/Instinct. When that happens, ParseEffects yields + // empty/no-op actions. We still attempt to execute active abilities from + // EffectsJson below as a compatibility path. + var actions = ParseEffects(card.EffectsJson) + .Where(a => a.Effects is { Length: > 0 }) + .ToArray(); + if (actions.Length > 0) + { + var ctx = new AbilityContext { State = state, ActorId = actorId, Source = card }; + ExecuteActions(actions, ctx, clientTargets, requireClientTargets: true); + } + + // 2. AbilitiesJson — Active abilities (e.g. Repentance / Instinct cards with targeting). + // 3. Compatibility fallback: if AbilitiesJson has no active entries, also try + // parsing active abilities from EffectsJson. + var activeDefs = ParseAbilities(card.AbilitiesJson) + .Where(d => d.Type == AbilityType.Active) + .ToList(); + + if (activeDefs.Count == 0) + { + var fallback = ParseAbilities(card.EffectsJson) + .Where(d => d.Type == AbilityType.Active) + .ToList(); + if (fallback.Count > 0) + activeDefs = fallback; + } + + foreach (var def in activeDefs) + { + var ctx = new AbilityContext { State = state, ActorId = actorId, Source = card }; + // Keep condition and duration behavior aligned with ActivateAbility. + if (!ValidateSourceActivationConditions(def, ctx, card)) + continue; + + ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true, + activationRange: def.Range, forceDuration: def.Duration); + } + + return state; + } + + private static bool ValidateSourceActivationConditions( + AbilityDefinition def, + AbilityContext ctx, + object sourceSubject) + { + if (def.ActivationConditions is not { Length: > 0 }) + return true; + + foreach (var cond in def.ActivationConditions.Where(c => c.Subject != "Target")) + if (!EvaluateCondition(cond, ctx, sourceSubject)) + return false; + + return true; + } + + /// + /// Scans every battlefield unit for Triggered abilities matching the occurrence + /// and fires each matching one. Called inline from GameEngine mutation methods. + /// + public static GameState FireTrigger(GameState state, TriggerOccurrence occurrence) + { + foreach (var (ownerId, player) in state.Players) + { + var units = player.Field.OfType().ToList(); // snapshot + foreach (var unit in units) + { + // SetCanUseAbility(false) suppresses triggered ability firing for this unit. + if (!unit.CanUseAbility) continue; + + var abilities = ParseAbilities(unit.AbilitiesJson); + for (int i = 0; i < abilities.Length; i++) + { + var def = abilities[i]; + if (def.Type != AbilityType.Triggered) continue; + if (def.TriggerEvent is null) continue; + if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId, unit)) continue; + + var ctx = new AbilityContext + { + State = state, + ActorId = ownerId, + Source = unit, + EventData = occurrence.Data, + }; + + if (def.ActivationConditions is { Length: > 0 }) + if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, unit))) + continue; + + ExecuteActions(def.Actions, ctx, clientTargets: null, forceDuration: def.Duration); + } + } + } + + // ── Check pending deferred effects ──────────────────────────────────── + var toFire = state.PendingDeferredEffects + .Where(p => + { + TriggerEvent? t; + try { t = JsonSerializer.Deserialize(p.TriggerJson, _jsonOpts); } + catch { return false; } + return t is not null && TriggerMatches(t, occurrence, state, p.OwnerAccountId); + }) + .ToList(); + + foreach (var pending in toFire) + { + state.PendingDeferredEffects.Remove(pending); + + Effect[]? deferredEffects; + try { deferredEffects = JsonSerializer.Deserialize(pending.EffectsJson, _jsonOpts); } + catch { continue; } + if (deferredEffects is null) continue; + + var tgt = FindDeferredTarget(state, pending.TargetRef); + if (tgt is null) continue; + + var dSrc = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + var dCtx = new AbilityContext { State = state, ActorId = pending.OwnerAccountId, Source = dSrc }; + foreach (var eff in deferredEffects) + ExecuteEffect(eff, tgt, DurationModel.Instant, dCtx); + } + + return state; + } + + private static object? FindDeferredTarget(GameState state, string targetRef) + { + foreach (var player in state.Players.Values) + { + var ci = (CardInstance?)( + player.Field.FirstOrDefault(c => c.InstanceId == targetRef) + ?? player.Hand.FirstOrDefault(c => c.InstanceId == targetRef) + ?? player.Deck.FirstOrDefault(c => c.InstanceId == targetRef) + ?? player.Discard.FirstOrDefault(c => c.InstanceId == targetRef)); + if (ci is not null) return ci; + if (player.AccountId == targetRef) return player; + } + return null; + } + + /// + /// At the start of each turn: for every Ruin on the battlefield whose tile is occupied + /// by a Spirit or ArchSpirit, pick ONE of the Ruin's OnRuinActivationTrigger abilities + /// at random and execute it. Then fire RuinActivation for any observer cards. + /// + public static GameState FireRuinAbilities(GameState state) + { + foreach (var (ownerId, player) in state.Players) + { + var ruins = player.Field + .OfType() + .Where(c => c.CardType == "Ruin" && c.Position.HasValue) + .ToList(); + + foreach (var ruin in ruins) + { + var tile = state.Board?.GetTile(ruin.Position!.Value); + if (tile?.OccupantId is null) continue; + + // Only fires if a Spirit or ArchSpirit is on the tile. + var occupantType = FindUnitType(state, tile.OccupantId); + if (occupantType is not ("Spirit" or "ArchSpirit" or "SpiritToken")) continue; + + var abilities = ParseAbilities(ruin.AbilitiesJson); + var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = ruin }; + + var eligible = abilities + .Where(a => a.Type == AbilityType.Triggered + && a.TriggerEvent is OnRuinActivationTrigger) + .Where(a => a.ActivationConditions is not { Length: > 0 } + || a.ActivationConditions.All(c => EvaluateCondition(c, ctx, ruin))) + .ToList(); + + if (eligible.Count == 0) continue; + + // Select exactly one ability at random. + var chosen = eligible[Random.Shared.Next(eligible.Count)]; + ExecuteActions(chosen.Actions, ctx, clientTargets: null); + + // Notify observer cards that the ruin activated. + FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.RuinActivation, + ActorId = ownerId, + Data = new TriggerEventData + { + SourceId = ruin.InstanceId, + TargetId = tile.OccupantId, + }, + }); + } + } + return state; + } + + private static string? FindUnitType(GameState state, string instanceId) + { + foreach (var player in state.Players.Values) + { + var c = player.Field.FirstOrDefault(x => x.InstanceId == instanceId) + ?? player.ArchSpirit as CardInstance; + if (c?.InstanceId == instanceId) return c.CardType; + } + return null; + } + + // ── Cost payment ────────────────────────────────────────────────────────── + + private static void PayCost(CostEntry[] costs, AbilityContext ctx) + { + var player = ctx.State.Players[ctx.ActorId]; + + foreach (var cost in costs) + { + switch (cost.Type) + { + case CostType.SpiritPoints: + if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP"); + player.CurrentSp -= cost.Amount; + break; + + case CostType.SacrificeTokens: + if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST"); + player.CurrentSt -= cost.Amount; + break; + + case CostType.DiscardFromHand: + { + var candidates = player.Hand + .Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx)) + .Take(cost.Amount).ToList(); + if (candidates.Count < cost.Amount) + throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD"); + foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); } + break; + } + + case CostType.MillTopOfDeck: + for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++) + { + var top = player.Deck[^1]; + player.Deck.RemoveAt(player.Deck.Count - 1); + player.Discard.Add(top); + } + break; + + case CostType.MillBottomOfDeck: + for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++) + { + var bottom = player.Deck[0]; + player.Deck.RemoveAt(0); + player.Discard.Add(bottom); + } + break; + + case CostType.DealDamageToOwnArchSpirit: + if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT"); + ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx); + break; + + case CostType.DealDamageToOwnSpirit: + { + var spirit = player.Field.OfType() + .FirstOrDefault(f => !f.IsLeader + && (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx))); + if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); + ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx); + break; + } + + case CostType.SendSpiritFromBattlefieldToDiscard: + { + var spirit = player.Field.OfType() + .FirstOrDefault(f => !f.IsLeader + && (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx))); + if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); + ctx.State.Board?.RemoveUnit(spirit.InstanceId); + player.Field.Remove(spirit); + player.Discard.Add(spirit); + break; + } + } + } + } + + // ── Action execution ────────────────────────────────────────────────────── + + private static void ExecuteActions( + Models.Action[] actions, + AbilityContext ctx, + IReadOnlyList? clientTargets, + bool requireClientTargets = false, + AbilityRange? activationRange = null, + HashSet? restrictTargets = null, + DurationModel? forceDuration = null) + { + for (int i = 0; i < actions.Length; i++) + ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i, + requireClientTargets, activationRange, restrictTargets, forceDuration); + } + + private static void ExecuteSingleAction( + Models.Action action, + AbilityContext ctx, + IReadOnlyList? clientTargets, + int actionIndex, + bool requireClientTargets = false, + AbilityRange? activationRange = null, + HashSet? restrictTargets = null, + DurationModel? forceDuration = null) + { + // Source-level conditions (Subject != "Target"): gate the whole action. + if (action.Conditions is { Length: > 0 }) + foreach (var cond in action.Conditions) + if (cond.Subject != "Target" && !EvaluateCondition(cond, ctx, ctx.Source!)) + return; + + var resolved = ResolveTargets( + action.Target, ctx, clientTargets, actionIndex, requireClientTargets, activationRange, restrictTargets); + ctx.ResolvedTargets[actionIndex] = resolved; + + // Target-level conditions (Subject == "Target"): filter per target. + var targetConds = action.Conditions?.Where(c => c.Subject == "Target").ToArray(); + var duration = forceDuration ?? action.Duration; + + foreach (var target in resolved) + { + if (targetConds is { Length: > 0 }) + { + // Temporarily expose current target so EvaluateCondition resolves "Target" correctly. + ctx.ResolvedTargets[actionIndex] = [target]; + bool passes = targetConds.All(c => EvaluateCondition(c, ctx, target)); + ctx.ResolvedTargets[actionIndex] = resolved; + if (!passes) continue; + } + + foreach (var effect in action.Effects) + ExecuteEffect(effect, target, duration, ctx); + } + } + + // ── Target resolution ───────────────────────────────────────────────────── + + private static List ResolveTargets( + TargetSelector selector, + AbilityContext ctx, + IReadOnlyList? clientTargets, + int actionIndex, + bool requireClientTargets = false, + AbilityRange? activationRange = null, + HashSet? restrictTargets = null) + { + var state = ctx.State; + + if (selector.Type == TargetType.Player) + { + return selector.Ownership switch + { + TargetOwnership.Owner or TargetOwnership.Self => + [state.Players[ctx.ActorId]], + TargetOwnership.Enemy => + state.Players.Values.Where(p => p.AccountId != ctx.ActorId).Cast().ToList(), + // Target: resolve the owner of the last CardInstance selected in a prior action. + // Used for abilities like Bounce (return a spirit, then refund its SP cost to its owner). + TargetOwnership.Target when + ctx.ResolvedTargets.Count > 0 && + ctx.ResolvedTargets.Values.Last().FirstOrDefault() is CardInstance lastCard && + FindCardOwner(state, lastCard.InstanceId) is { } owner => + [(object)owner], + _ => state.Players.Values.Cast().ToList(), + }; + } + + if (selector.Type == TargetType.Tile) + { + // Battlefield scope with All=true: enumerate every board tile server-side. + // The client does not (and should not) send coords for board-wide tile effects. + if (selector.Scope == TargetScope.Battlefield && selector.Count.All + && ctx.State.Board is { } board) + { + var allTiles = board.Tiles.Values + .Select(t => (object)t.Coord) + .ToList(); + if (activationRange is not null) + allTiles = FilterTargetsByAbilityRange(allTiles, ctx, activationRange); + return allTiles; + } + + if (clientTargets is null) return []; + var tiles = clientTargets + .Where(t => t.ActionIndex == actionIndex && t.Coord is not null) + .Select(t => (object)new Coord(t.Coord!.X, t.Coord!.Y)) + .ToList(); + if (activationRange is not null) + tiles = FilterTargetsByAbilityRange(tiles, ctx, activationRange); + return tiles; + } + + var candidates = BuildCandidates(selector, state, ctx.ActorId); + + // ExactSelf: narrow to the exact unit instance that owns this ability. + if (selector.Ownership == TargetOwnership.ExactSelf && ctx.Source is not null) + candidates = candidates.Where(c => c.InstanceId == ctx.Source.InstanceId).ToList(); + + // Passive apply-to-new-unit: restrict to a specific subset of candidates. + if (restrictTargets is not null) + candidates = candidates.Where(c => restrictTargets.Contains(c.InstanceId)).ToList(); + + if (selector.Filters is { Length: > 0 }) + candidates = candidates.Where(c => FiltersMatch(selector.Filters, c, ctx)).ToList(); + + HashSet clientIds = []; + if (clientTargets is not null) + { + clientIds = clientTargets + .Where(t => t.ActionIndex == actionIndex && t.InstanceId is not null) + .Select(t => t.InstanceId!).ToHashSet(); + if (clientIds.Count > 0) + candidates = candidates.Where(c => clientIds.Contains(c.InstanceId)).ToList(); + } + else if (requireClientTargets && !selector.Count.All && !selector.Count.UpTo && selector.Count.N > 0) + { + // Some ownership scopes are server-resolved and should not require client picks. + // Keep this aligned with client auto-targeting behavior. + bool serverResolvedOwnership = selector.Ownership is + TargetOwnership.Self or + TargetOwnership.ExactSelf or + TargetOwnership.Target or + TargetOwnership.Random; + + // Mandatory explicit-target action with no client selection provided — fail fast. + if (!serverResolvedOwnership) + candidates = []; + } + + if (activationRange is not null) + { + // If the client explicitly picked unit targets, validate range before filtering so the + // error is unambiguous (TARGET_OUT_OF_RANGE rather than INSUFFICIENT_TARGETS). + if (clientIds.Count > 0 && ctx.Source is FieldCard srcFc && srcFc.Position.HasValue) + { + bool anyOutOfRange = candidates + .OfType() + .Where(fc => clientIds.Contains(fc.InstanceId)) + .Any(fc => !fc.Position.HasValue || + !IsTargetInAbilityRange(ctx.State, srcFc.Position.Value, fc.Position.Value, activationRange)); + if (anyOutOfRange) + throw new GameException("TARGET_OUT_OF_RANGE"); + } + + candidates = FilterTargetsByAbilityRange(candidates.Cast().ToList(), ctx, activationRange) + .OfType() + .ToList(); + } + + if (!selector.Count.All) + { + int needed = selector.Count.N; + if (!selector.Count.UpTo && candidates.Count < needed) + { + // In passive-to-new-target mode (restrictTargets set) there is no + // player-driven target selection; zero candidates simply means this + // passive does not apply to the new unit — skip silently. + if (restrictTargets is not null) + return []; + throw new GameException("INSUFFICIENT_TARGETS"); + } + candidates = candidates.Take(needed).ToList(); + } + + return candidates.Cast().ToList(); + } + + private static List FilterTargetsByAbilityRange( + List targets, AbilityContext ctx, AbilityRange range) + { + if (ctx.Source is not FieldCard source || !source.Position.HasValue) + return []; + + return targets.Where(t => t switch + { + FieldCard fc when fc.Position.HasValue => + IsTargetInAbilityRange(ctx.State, source.Position.Value, fc.Position.Value, range), + Coord coord => + IsTargetInAbilityRange(ctx.State, source.Position.Value, coord, range), + _ => false, + }).ToList(); + } + + private static bool IsTargetInAbilityRange( + GameState state, Coord sourcePos, Coord targetPos, AbilityRange range) + { + int dist = sourcePos.ManhattanDistance(targetPos); + if (dist < range.Min || dist > range.Max) + return false; + + if (range.LinearOnly) + { + int dx = Math.Abs(targetPos.X - sourcePos.X); + int dy = Math.Abs(targetPos.Y - sourcePos.Y); + if (!(dx == 0 || dy == 0 || dx == dy)) + return false; + } + + if (range.RequiresLos) + { + var board = state.Board; + if (board is null) return false; + var occupancy = board.BuildOccupancyMap(); + occupancy.Remove(sourcePos); + if (!LineOfSight.HasLos(board, sourcePos, targetPos, occupancy)) + return false; + } + + return true; + } + + private static List BuildCandidates( + TargetSelector selector, GameState state, string actorId) + { + var all = new List(); + + IEnumerable ownerIds = selector.Ownership switch + { + TargetOwnership.Owner or TargetOwnership.Self or TargetOwnership.ExactSelf => [actorId], + TargetOwnership.Enemy => state.Players.Keys.Where(k => k != actorId), + TargetOwnership.Ally => state.Players.Keys.Where(k => k != actorId), + _ => state.Players.Keys, + }; + + foreach (var ownerId in ownerIds) + { + var p = state.Players[ownerId]; + switch (selector.Scope) + { + case TargetScope.Battlefield: + all.AddRange(p.Field); + if (p.ArchSpirit is not null) all.Add(p.ArchSpirit); + break; + case TargetScope.Hand: all.AddRange(p.Hand); break; + case TargetScope.Deck: all.AddRange(p.Deck); break; + case TargetScope.Discard: all.AddRange(p.Discard); break; + case TargetScope.AnyZone: + all.AddRange(p.Hand); all.AddRange(p.Deck); + all.AddRange(p.Field); all.AddRange(p.Discard); + if (p.ArchSpirit is not null) all.Add(p.ArchSpirit); + break; + } + } + + return selector.Type switch + { + TargetType.ArchSpirit => all.Where(c => c.CardType == "ArchSpirit").ToList(), + TargetType.Spirit => all.Where(c => c.CardType == "Spirit").ToList(), + TargetType.SpiritToken => all.Where(c => c.CardType == "SpiritToken").ToList(), + TargetType.Ruin => all.Where(c => c.CardType == "Ruin").ToList(), + TargetType.Unit => all.Where(c => + c.CardType is "ArchSpirit" or "Spirit" or "SpiritToken").ToList(), + _ => all, + }; + } + + // ── Effect execution ────────────────────────────────────────────────────── + + private static void ExecuteEffect( + Effect effect, object target, DurationModel? duration, AbilityContext ctx) + { + switch (effect) + { + // ── §5.1 Stat modification ───────────────────────────────────────── + case ModifyHealthEffect mh when target is CardInstance ci: + { + int amt = ResolveValue(mh.Amount, ctx); + if (mh.StatTarget == StatTarget.Current) + { + ci.CurrentHealth = (ci.CurrentHealth ?? 0) + amt; + if (ci.MaxHealth.HasValue) + ci.CurrentHealth = Math.Min(ci.CurrentHealth.Value, ci.MaxHealth.Value); + if (ci.CurrentHealth <= 0) KillUnit(ci, ctx, ctx.Source?.InstanceId); + } + else + { + ci.MaxHealth = (ci.MaxHealth ?? 0) + amt; + if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth; + } + TrackEffect(new ModifyHealthEffect { Amount = V(-amt), StatTarget = mh.StatTarget }, + ci.InstanceId, duration, ctx); + break; + } + case ModifyDefenseEffect md when target is CardInstance ci: + { + int amt = ResolveValue(md.Amount, ctx); + if (md.StatTarget == StatTarget.Current) + ci.CurrentDefense = Math.Max(0, (ci.CurrentDefense ?? 0) + amt); + else + ci.MaxDefense = (ci.MaxDefense ?? 0) + amt; + TrackEffect(new ModifyDefenseEffect { Amount = V(-amt), StatTarget = md.StatTarget }, + ci.InstanceId, duration, ctx); + break; + } + case ModifyDamageEffect mdam when target is CardInstance ci: + { + int amt = ResolveValue(mdam.Amount, ctx); + ci.Damage = Math.Max(0, (ci.Damage ?? 0) + amt); + TrackEffect(new ModifyDamageEffect { Amount = V(-amt) }, ci.InstanceId, duration, ctx); + break; + } + case ModifyMPEffect mmp when target is CardInstance ci: + { + int amt = ResolveValue(mmp.Amount, ctx); + if (mmp.StatTarget == StatTarget.Current && ci is FieldCard fc) + fc.CurrentMp = Math.Max(0, fc.CurrentMp + amt); + else + ci.MaxMp = Math.Max(0, (ci.MaxMp ?? 0) + amt); + TrackEffect(new ModifyMPEffect { Amount = V(-amt), StatTarget = mmp.StatTarget }, + ci.InstanceId, duration, ctx); + break; + } + case SetMovementTypeEffect smt when target is CardInstance ci: + { + var orig = ci.MovementType; + ci.MovementType = smt.MovementType; + if (orig.HasValue) + TrackEffect(new SetMovementTypeEffect { MovementType = orig.Value }, + ci.InstanceId, duration, ctx); + break; + } + case SetAttackRangeEffect sar when target is CardInstance ci: + { + int? origMin = ci.MinAttackRange, origMax = ci.MaxAttackRange; + ci.MinAttackRange = sar.Min; ci.MaxAttackRange = sar.Max; + if (origMin.HasValue && origMax.HasValue) + TrackEffect(new SetAttackRangeEffect { Min = origMin.Value, Max = origMax.Value }, + ci.InstanceId, duration, ctx); + break; + } + case ModifyMinAttackRangeEffect mmar when target is CardInstance ci: + { + int orig = ci.MinAttackRange ?? 0; + int newVal = Math.Max(0, orig + ResolveValue(mmar.Amount, ctx)); + ci.MinAttackRange = newVal; + TrackEffect(new ModifyMinAttackRangeEffect { Amount = V(orig - newVal) }, + ci.InstanceId, duration, ctx); + break; + } + case ModifyMaxAttackRangeEffect mmax when target is CardInstance ci: + { + int orig = ci.MaxAttackRange ?? 1; + int newVal = Math.Max(0, orig + ResolveValue(mmax.Amount, ctx)); + ci.MaxAttackRange = newVal; + TrackEffect(new ModifyMaxAttackRangeEffect { Amount = V(orig - newVal) }, + ci.InstanceId, duration, ctx); + break; + } + case ModifyCostEffect mc when target is CardInstance ci: + { + if (mc.Sp.HasValue) ci.SpCost = Math.Max(0, ci.SpCost + mc.Sp.Value); + if (mc.St.HasValue) ci.StCost = Math.Max(0, ci.StCost + mc.St.Value); + TrackEffect(new ModifyCostEffect + { + Sp = mc.Sp.HasValue ? -mc.Sp.Value : null, + St = mc.St.HasValue ? -mc.St.Value : null, + }, ci.InstanceId, duration, ctx); + break; + } + case SetAffinityEffect sa when target is CardInstance ci: + { + var origAff = ci.Affinity; + ci.Affinity = ResolveAffinity(sa.Affinity, ctx).ToString(); + if (Enum.TryParse(origAff, out var parsed)) + TrackEffect(new SetAffinityEffect { Affinity = new AffinityExpr { Fixed = parsed } }, + ci.InstanceId, duration, ctx); + break; + } + case GrantAdditionalAttackEffect gaa when target is CardInstance ci: + { + ci.ExtraAttacksRemaining += gaa.N; + if (ci.ExtraAttacksRemaining < 0) ci.ExtraAttacksRemaining = 0; + TrackEffect(new GrantAdditionalAttackEffect { N = -gaa.N }, ci.InstanceId, duration, ctx); + break; + } + + // ── §5.2 Unit flags ──────────────────────────────────────────────── + case SetCanMoveEffect scm when target is CardInstance ci: + { + bool orig = ci.CanMove; ci.CanMove = scm.Value; + TrackEffect(new SetCanMoveEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanAttackEffect sca when target is CardInstance ci: + { + bool orig = ci.CanAttack; ci.CanAttack = sca.Value; + TrackEffect(new SetCanAttackEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanDefendEffect scd when target is CardInstance ci: + { + bool orig = ci.CanDefend; ci.CanDefend = scd.Value; + TrackEffect(new SetCanDefendEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeAttackedEffect scba when target is CardInstance ci: + { + bool orig = ci.CanBeAttacked; ci.CanBeAttacked = scba.Value; + TrackEffect(new SetCanBeAttackedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeBlockedEffect scbb when target is CardInstance ci: + { + bool orig = ci.CanBeBlocked; ci.CanBeBlocked = scbb.Value; + TrackEffect(new SetCanBeBlockedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeObstructedEffect scbo when target is CardInstance ci: + { + bool orig = ci.CanBeObstructed; ci.CanBeObstructed = scbo.Value; + TrackEffect(new SetCanBeObstructedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanUseAbilityEffect scua when target is CardInstance ci: + { + bool orig = ci.CanUseAbility; ci.CanUseAbility = scua.Value; + TrackEffect(new SetCanUseAbilityEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeSacrificedEffect scbs when target is CardInstance ci: + { + bool orig = ci.CanBeSacrificed; ci.CanBeSacrificed = scbs.Value; + TrackEffect(new SetCanBeSacrificedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + + // ── §5.2 Player flags ───────────────────────────────────────────── + case SetCanDrawCardsEffect scdc when target is PlayerState ps: + { + bool orig = ps.CanDrawCards; ps.CanDrawCards = scdc.Value; + TrackEffect(new SetCanDrawCardsEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetAccumulatesSPEffect sasp when target is PlayerState ps: + { + bool orig = ps.AccumulatesSP; ps.AccumulatesSP = sasp.Value; + TrackEffect(new SetAccumulatesSPEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelSpiritEffect sccsp when target is PlayerState ps: + { + bool orig = ps.CanChannelSpirit; ps.CanChannelSpirit = sccsp.Value; + TrackEffect(new SetCanChannelSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanSacrificeSpiritEffect scss when target is PlayerState ps: + { + bool orig = ps.CanSacrificeSpirit; ps.CanSacrificeSpirit = scss.Value; + TrackEffect(new SetCanSacrificeSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanAscendArchSpiritEffect scaas when target is PlayerState ps: + { + bool orig = ps.CanAscendArchSpirit; ps.CanAscendArchSpirit = scaas.Value; + TrackEffect(new SetCanAscendArchSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanTransitionArchSpiritEffect sctas when target is PlayerState ps: + { + bool orig = ps.CanTransitionArchSpirit; ps.CanTransitionArchSpirit = sctas.Value; + TrackEffect(new SetCanTransitionArchSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelRepentanceEffect sccrep when target is PlayerState ps: + { + bool orig = ps.CanChannelRepentance; ps.CanChannelRepentance = sccrep.Value; + TrackEffect(new SetCanChannelRepentanceEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelInstinctEffect sccin when target is PlayerState ps: + { + bool orig = ps.CanChannelInstinct; ps.CanChannelInstinct = sccin.Value; + TrackEffect(new SetCanChannelInstinctEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelRuinEffect sccru when target is PlayerState ps: + { + bool orig = ps.CanChannelRuin; ps.CanChannelRuin = sccru.Value; + TrackEffect(new SetCanChannelRuinEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelTerramorphaMonoEffect sctm when target is PlayerState ps: + { + bool orig = ps.CanChannelTerramorphaMono; ps.CanChannelTerramorphaMono = sctm.Value; + TrackEffect(new SetCanChannelTerramorphaMonoEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelTerramorphaDiEffect sctdi when target is PlayerState ps: + { + bool orig = ps.CanChannelTerramorphaDi; ps.CanChannelTerramorphaDi = sctdi.Value; + TrackEffect(new SetCanChannelTerramorphaDiEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + case SetCanChannelTerramorphaTriEffect scttri when target is PlayerState ps: + { + bool orig = ps.CanChannelTerramorphaTri; ps.CanChannelTerramorphaTri = scttri.Value; + TrackEffect(new SetCanChannelTerramorphaTriEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } + + // ── §5.3 Ability modification ────────────────────────────────────── + case AddAbilityEffect addab when target is CardInstance ci: + { + var existing = ParseAbilities(ci.AbilitiesJson).ToList(); + existing.Add(addab.AbilityDef); + ci.AbilitiesJson = JsonSerializer.Serialize(existing, _jsonOpts); + if (!string.IsNullOrWhiteSpace(addab.AbilityDef.Name)) + TrackEffect(new RemoveAbilityEffect { AbilityRef = addab.AbilityDef.Name }, + ci.InstanceId, duration, ctx); + break; + } + case RemoveAbilityEffect remab when target is CardInstance ci: + { + var existing = ParseAbilities(ci.AbilitiesJson).ToList(); + var removed = existing.FirstOrDefault(a => a.Name == remab.AbilityRef); + if (removed is not null) + { + existing.Remove(removed); + ci.AbilitiesJson = JsonSerializer.Serialize(existing, _jsonOpts); + TrackEffect(new AddAbilityEffect { AbilityDef = removed }, ci.InstanceId, duration, ctx); + } + break; + } + case EnableAbilityEffect enab when target is CardInstance ci: + { + ci.DisabledAbilities?.Remove(enab.AbilityRef); + TrackEffect(new DisableAbilityEffect { AbilityRef = enab.AbilityRef }, + ci.InstanceId, duration, ctx); + break; + } + case DisableAbilityEffect disab when target is CardInstance ci: + { + ci.DisabledAbilities ??= []; + if (!ci.DisabledAbilities.Contains(disab.AbilityRef)) + ci.DisabledAbilities.Add(disab.AbilityRef); + TrackEffect(new EnableAbilityEffect { AbilityRef = disab.AbilityRef }, + ci.InstanceId, duration, ctx); + break; + } + + // ── §5.4 Genus ──────────────────────────────────────────────────── + case AddGenusEffect ag when target is CardInstance ci: + { + ci.Genus ??= []; + if (!ci.Genus.Contains(ag.Tag)) ci.Genus.Add(ag.Tag); + TrackEffect(new RemoveGenusEffect { Tag = ag.Tag }, ci.InstanceId, duration, ctx); + break; + } + case RemoveGenusEffect rg when target is CardInstance ci: + { + ci.Genus?.Remove(rg.Tag); + TrackEffect(new AddGenusEffect { Tag = rg.Tag }, ci.InstanceId, duration, ctx); + break; + } + + // ── §5.5 Player resources ───────────────────────────────────────── + case ModifySPEffect msp when target is PlayerState ps: + ps.CurrentSp = Math.Max(0, ps.CurrentSp + ResolveValue(msp.Amount, ctx)); + break; + case ModifySPAccumulationEffect mspa when target is PlayerState ps: + { + int amt = ResolveValue(mspa.Amount, ctx); + ps.SpAccumulationBonus += amt; + TrackEffect(new ModifySPAccumulationEffect { Amount = V(-amt) }, ps.AccountId, duration, ctx); + break; + } + case ModifySTEffect mst when target is PlayerState ps: + ps.CurrentSt = Math.Max(0, ps.CurrentSt + ResolveValue(mst.Amount, ctx)); + break; + case ModifyCardsDrawnPerTurnEffect mcdpt when target is PlayerState ps: + { + int amt = ResolveValue(mcdpt.Amount, ctx); + ps.DrawPerTurnBonus += amt; + TrackEffect(new ModifyCardsDrawnPerTurnEffect { Amount = V(-amt) }, ps.AccountId, duration, ctx); + break; + } + + // ── §5.6 Tile modification ──────────────────────────────────────── + case SetBaseAffinity1Effect sba1 when target is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + if (tile is not null) tile.Base1 = ResolveAffinity(sba1.Affinity, ctx); + break; + } + case SetBaseAffinity2Effect sba2 when target is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + if (tile is not null) tile.Base2 = ResolveAffinity(sba2.Affinity, ctx); + break; + } + case PushAffinityEffect pa when target is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + if (tile is not null) + AffinitySystem.PushAffinity(tile, ResolveAffinity(pa.Affinity, ctx)); + break; + } + case PushFinalAffinityEffect pfa when target is Coord coord: + { + // PushFinalAffinity overrides the newer slot directly. + var tile = ctx.State.Board?.GetTile(coord); + if (tile is not null) tile.Base2 = ResolveAffinity(pfa.Affinity, ctx); + break; + } + case SetAffinityEffect sa when target is Coord coord: + { + // SetAffinity on a tile decomposes the target affinity into its canonical + // (Base1, Base2) pair so Resolve() always returns the intended affinity. + // e.g. Lake→(Void,Lake), Jungle→(Forest,Forest), Island→(Lake,Hill). + var tile = ctx.State.Board?.GetTile(coord); + if (tile is null) break; + var origBase1 = tile.Base1; + var origBase2 = tile.Base2; + var newAff = ResolveAffinity(sa.Affinity, ctx); + (tile.Base1, tile.Base2) = AffinitySystem.Decompose(newAff); + var tileRef = $"tile:{coord.X},{coord.Y}"; + TrackEffect(new SetBaseAffinity1Effect { Affinity = new AffinityExpr { Fixed = origBase1 } }, + tileRef, duration, ctx); + TrackEffect(new SetBaseAffinity2Effect { Affinity = new AffinityExpr { Fixed = origBase2 } }, + tileRef, duration, ctx); + break; + } + + // ── §5.7 Zone / card operations ─────────────────────────────────── + case DrawCardsEffect dc: + DrawCards(ResolvePlayerForEffect(dc.Player, ctx), dc.N); + break; + case DiscardCardsEffect dce: + DiscardFromHand(ResolvePlayerForEffect(dce.Player, ctx), dce.N, dce.Filters, ctx); + break; + case ReturnToHandEffect when target is CardInstance ci: + { + var owner = FindCardOwner(ctx.State, ci.InstanceId); + if (owner is not null) + { + if (owner.Field.Any(f => f.InstanceId == ci.InstanceId)) + RevokePassivesForSource(ctx.State, ci.InstanceId); + RemoveFromAllZones(owner, ci, ctx.State.Board); + owner.Hand.Add(ci); + } + break; + } + case ReturnToDeckEffect rtd when target is CardInstance ci: + { + var owner = FindCardOwner(ctx.State, ci.InstanceId); + if (owner is not null) { RemoveFromAllZones(owner, ci, ctx.State.Board); PlaceInDeck(owner, ci, rtd.Position); } + break; + } + case ReturnToBattlefieldEffect rtb when target is CardInstance ci: + { + var board = ctx.State.Board; + if (board is null) break; + + var emptyTiles = board.Tiles.Values.Where(t => t.IsEmpty).ToList(); + if (rtb.TileFilter is { Length: > 0 }) + emptyTiles = emptyTiles.Where(t => TileMatchesFilters(rtb.TileFilter, t, ctx)).ToList(); + if (emptyTiles.Count == 0) break; + + var destTile = emptyTiles[Random.Shared.Next(emptyTiles.Count)]; + var ownerPs = rtb.Controller?.ToLowerInvariant() == "enemy" + ? ctx.State.Players.Values.First(p => p.AccountId != ctx.ActorId) + : ctx.State.Players[ctx.ActorId]; + + var originalOwner = FindCardOwner(ctx.State, ci.InstanceId); + if (originalOwner is not null) RemoveFromAllZones(originalOwner, ci, board); + + FieldCard fc; + if (ci is FieldCard existingFc) + { + existingFc.Position = destTile.Coord; + existingFc.CurrentMp = existingFc.MaxMp ?? 0; + fc = existingFc; + } + else + { + fc = new FieldCard + { + InstanceId = ci.InstanceId, + CardDefinitionId = ci.CardDefinitionId, + Name = ci.Name, + CardType = ci.CardType, + Affinity = ci.Affinity, + Rarity = ci.Rarity, + SpCost = ci.SpCost, + StCost = ci.StCost, + MaxHealth = ci.MaxHealth, + CurrentHealth = ci.MaxHealth, + MaxDefense = ci.MaxDefense, + CurrentDefense = ci.MaxDefense, + Damage = ci.Damage, + CanAttack = ci.CanAttack, + CanDefend = ci.CanDefend, + CanMove = ci.CanMove, + MovementType = ci.MovementType, + MaxMp = ci.MaxMp, + MinAttackRange = ci.MinAttackRange, + MaxAttackRange = ci.MaxAttackRange, + RequiresLos = ci.RequiresLos, + AbilitiesJson = ci.AbilitiesJson, + CanBeAttacked = ci.CanBeAttacked, + CanBeBlocked = ci.CanBeBlocked, + CanBeObstructed = ci.CanBeObstructed, + CanUseAbility = ci.CanUseAbility, + CanBeSacrificed = ci.CanBeSacrificed, + Position = destTile.Coord, + CurrentMp = ci.MaxMp ?? 0, + }; + } + + ownerPs.Field.Add(fc); + board.PlaceUnit(destTile.Coord, fc.InstanceId, ownerPs.AccountId); + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitEnterBattlefield, + ActorId = ownerPs.AccountId, + UnitType = fc.CardType, + Data = new TriggerEventData { SourceId = fc.InstanceId }, + }); + EvaluateAurasOnEnter(ctx.State, fc.InstanceId); + ApplyPassivesForSource(ctx.State, fc.InstanceId, ownerPs.AccountId); + ApplyPassivesToNewTarget(ctx.State, fc.InstanceId); + break; + } + case SendToDiscardEffect when target is CardInstance ci: + { + var owner = FindCardOwner(ctx.State, ci.InstanceId); + if (owner is not null) + { + if (owner.Field.Any(f => f.InstanceId == ci.InstanceId)) + RevokePassivesForSource(ctx.State, ci.InstanceId); + RemoveFromAllZones(owner, ci, ctx.State.Board); + owner.Discard.Add(ci); + + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitSentToDiscard, + ActorId = owner.AccountId, + Data = new TriggerEventData { TargetId = ci.InstanceId, SourceId = ctx.Source?.InstanceId }, + UnitType = ci.CardType, + }); + } + break; + } + case SearchDeckEffect sde: + { + var ps = ResolvePlayerForEffect("Owner", ctx); + var found = ps.Deck + .Where(c => sde.Filters is null || FiltersMatch(sde.Filters, c, ctx)) + .Take(sde.Count).ToList(); + foreach (var card in found) + { + ps.Deck.Remove(card); + if (sde.ThenAction is not null) + { + var innerCtx = new AbilityContext + { State = ctx.State, ActorId = ctx.ActorId, Source = ctx.Source }; + foreach (var eff in sde.ThenAction.Effects) + ExecuteEffect(eff, card, sde.ThenAction.Duration, innerCtx); + } + else + { + ps.Hand.Add(card); + } + } + break; + } + case ShuffleDeckEffect sde: + { + var ps = ResolvePlayerForEffect(sde.Player, ctx); + var rng = new Random(); + for (int i = ps.Deck.Count - 1; i > 0; i--) + { + int j = rng.Next(i + 1); + (ps.Deck[i], ps.Deck[j]) = (ps.Deck[j], ps.Deck[i]); + } + break; + } + case RevealCardsEffect when target is CardInstance ci: + ci.IsRevealed = true; + break; + case PlaceOnDeckEffect pod when target is CardInstance ci: + { + var owner = FindCardOwner(ctx.State, ci.InstanceId); + if (owner is not null) + { + RemoveFromAllZones(owner, ci, ctx.State.Board); + PlaceInDeck(owner, ci, pod.Position); + } + break; + } + + // ── §5.8 Combat / damage ────────────────────────────────────────── + case DealDamageEffect dd when target is CardInstance ci: + ApplyDamageToUnit(ci, ResolveValue(dd.Amount, ctx), dd.BypassDefense, ctx); + break; + case HealEffect he when target is CardInstance ci: + ci.CurrentHealth = Math.Min(ci.MaxHealth ?? int.MaxValue, + (ci.CurrentHealth ?? 0) + ResolveValue(he.Amount, ctx)); + break; + case DealDamageToSelfEffect ddself: + if (ctx.Source is not null) + ApplyDamageToUnit(ctx.Source, ResolveValue(ddself.Amount, ctx), + ddself.BypassDefense, ctx); + break; + case DOTEffect dot when target is CardInstance ci: + TrackTick(new DealDamageEffect { Amount = V(ResolveValue(dot.Amount, ctx)), BypassDefense = dot.BypassDefense }, + ci.InstanceId, dot.Duration, ctx); + break; + case HOTEffect hot when target is CardInstance ci: + TrackTick(new HealEffect { Amount = V(ResolveValue(hot.Amount, ctx)) }, + ci.InstanceId, hot.Duration, ctx); + break; + + // ── §5.9 Displacement ───────────────────────────────────────────── + case PushUnitEffect pu when target is FieldCard fc2: + DisplaceUnit(fc2, pu.Tiles, fromSource: true, ctx); break; + case PullUnitEffect pull when target is FieldCard fc3: + DisplaceUnit(fc3, pull.Tiles, fromSource: false, ctx); break; + case DisplaceUnitEffect du when target is FieldCard fc5: + { + if (!fc5.Position.HasValue || ctx.State.Board is null) break; + var (dx, dy) = ParseDirection(du.Direction); + if (dx == 0 && dy == 0) break; + var oldPos5 = fc5.Position.Value; + var newPos5 = new Coord(oldPos5.X + dx * du.Tiles, oldPos5.Y + dy * du.Tiles); + if (!ctx.State.Board.IsInBounds(newPos5) || !ctx.State.Board.GetTile(newPos5)!.IsEmpty) break; + var duOwner = ctx.State.Players.Values + .FirstOrDefault(p => p.Field.Any(f => f.InstanceId == fc5.InstanceId)); + if (duOwner is null) break; + ctx.State.Board.RemoveUnit(fc5.InstanceId); + ctx.State.Board.PlaceUnit(newPos5, fc5.InstanceId, duOwner.AccountId); + fc5.Position = newPos5; + EvaluateAuraTransitions(ctx.State, fc5.InstanceId, oldPos5, newPos5); + break; + } + + // ── §5.10 Control ───────────────────────────────────────────────── + case TakeControlEffect when target is FieldCard fc4: + { + var originalOwner = FindCardOwner(ctx.State, fc4.InstanceId); + if (originalOwner is not null) originalOwner.Field.Remove(fc4); + ctx.State.Players[ctx.ActorId].Field.Add(fc4); + break; + } + case GrantMovementControlEffect gmc when target is FieldCard fc6: + { + fc6.CurrentMp += gmc.N; + TrackEffect(new ModifyMPEffect { Amount = V(-gmc.N), StatTarget = StatTarget.Current }, + fc6.InstanceId, duration, ctx); + break; + } + case SetFixedSacrificeReturnEffect sfsr when target is CardInstance ci: + { + int? orig = ci.FixedSacrificeReturn; + // Negative StAmount is a sentinel meaning "clear override" (used in reversals). + ci.FixedSacrificeReturn = sfsr.StAmount >= 0 ? sfsr.StAmount : (int?)null; + TrackEffect(new SetFixedSacrificeReturnEffect { StAmount = orig ?? -1 }, + ci.InstanceId, duration, ctx); + break; + } + + // ── §5.11 Token summoning ───────────────────────────────────────── + case SummonTokenEffect ste when target is Coord coord: + { + var board = ctx.State.Board; + if (board is null) break; + var tile = board.GetTile(coord); + if (tile is null || !tile.IsEmpty) break; + + // TokenDefJson is deserialized directly as CardInstance field values. + var proto = JsonSerializer.Deserialize(ste.TokenDefJson, _jsonOpts); + if (proto is null) break; + + // Enforce tile affinity: a token with a non-Void affinity may only be + // placed on a tile whose resolved affinity is compatible with the token. + if (!string.IsNullOrEmpty(proto.Affinity) && proto.Affinity != "Void" + && Enum.TryParse(proto.Affinity, out var tokenAffinity) + && !AffinitySystem.IsAffinityValid(tile, tokenAffinity)) + break; + + proto.InstanceId = Guid.NewGuid().ToString("N")[..8]; + proto.CardType = "SpiritToken"; + + var tokenField = CreateTokenFieldCard(proto, coord); + ctx.State.Players[ctx.ActorId].Field.Add(tokenField); + board.PlaceUnit(coord, tokenField.InstanceId, ctx.ActorId); + + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitEnterBattlefield, + ActorId = ctx.ActorId, + UnitType = "SpiritToken", + Data = new TriggerEventData { SourceId = tokenField.InstanceId }, + }); + EvaluateAurasOnEnter(ctx.State, tokenField.InstanceId); + ApplyPassivesForSource(ctx.State, tokenField.InstanceId, ctx.ActorId); + ApplyPassivesToNewTarget(ctx.State, tokenField.InstanceId); + break; + } + + // ── §5.12 Deferred ──────────────────────────────────────────────── + case ApplyOnEventEffect aoe: + { + string targetRef = target is CardInstance ci3 ? ci3.InstanceId + : target is PlayerState ps3 ? ps3.AccountId + : string.Empty; + if (string.IsNullOrEmpty(targetRef)) break; + ctx.State.PendingDeferredEffects.Add(new PendingDeferredEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + OwnerAccountId = ctx.ActorId, + TriggerJson = JsonSerializer.Serialize(aoe.Trigger, _jsonOpts), + TargetRef = targetRef, + EffectsJson = JsonSerializer.Serialize(aoe.Effects, _jsonOpts), + }); + break; + } + + default: + break; + } + } + + private static FieldCard CreateTokenFieldCard(CardInstance proto, Coord position) + => new() + { + InstanceId = proto.InstanceId, + Name = proto.Name, + CardType = "SpiritToken", + Affinity = proto.Affinity, + MaxHealth = proto.MaxHealth, + CurrentHealth = proto.MaxHealth, + MaxDefense = proto.MaxDefense, + CurrentDefense = proto.MaxDefense, + Damage = proto.Damage, + CanAttack = proto.CanAttack, + CanDefend = proto.CanDefend, + CanMove = proto.CanMove, + CanBeAttacked = proto.CanBeAttacked, + CanBeBlocked = proto.CanBeBlocked, + CanBeObstructed = proto.CanBeObstructed, + CanUseAbility = proto.CanUseAbility, + CanBeSacrificed = proto.CanBeSacrificed, + DisabledAbilities = proto.DisabledAbilities is null + ? null : [.. proto.DisabledAbilities], + MovementType = proto.MovementType, + MaxMp = proto.MaxMp, + CurrentMp = proto.MaxMp ?? 0, + MinAttackRange = proto.MinAttackRange, + MaxAttackRange = proto.MaxAttackRange, + RequiresLos = proto.RequiresLos, + AbilitiesJson = proto.AbilitiesJson, + Genus = proto.Genus is null ? null : [.. proto.Genus], + Art2dUrl = proto.Art2dUrl, + ModelUrl = proto.ModelUrl, + IsExhausted = false, + Position = position, + }; + + // ── Displacement helpers ────────────────────────────────────────────────── + + private static (int dx, int dy) ParseDirection(string dir) => dir.ToUpperInvariant() switch + { + "NORTH" or "N" => (0, 1), + "SOUTH" or "S" => (0, -1), + "EAST" or "E" => ( 1, 0), + "WEST" or "W" => (-1, 0), + "NORTHEAST" or "NE" => ( 1, 1), + "NORTHWEST" or "NW" => (-1, 1), + "SOUTHEAST" or "SE" => ( 1, -1), + "SOUTHWEST" or "SW" => (-1, -1), + _ => (0, 0), + }; + + /// + /// Applies affinity-based filter matching to a board tile. + /// Non-affinity filters are silently accepted (they apply to cards, not tiles). + /// + private static bool TileMatchesFilters(Filter[] filters, Tile tile, AbilityContext ctx) + { + foreach (var f in filters) + { + if (f is AffinityMatchesFilter amf) + { + var resolved = AffinitySystem.Resolve(tile.Base1, tile.Base2); + if (!Enum.TryParse(amf.Affinity.ToString(), out var expected) + || resolved != expected) return false; + } + } + return true; + } + + // ── Damage helper ───────────────────────────────────────────────────────── + + private static void ApplyDamageToUnit( + CardInstance unit, int rawAmount, bool bypassDefense, AbilityContext ctx) + { + int net = bypassDefense + ? rawAmount + : Math.Max(0, rawAmount - (unit.CurrentDefense ?? 0)); + unit.CurrentHealth = (unit.CurrentHealth ?? 0) - net; + if (unit.CurrentHealth <= 0) KillUnit(unit, ctx, ctx.Source?.InstanceId); + } + + private static void KillUnit(CardInstance unit, AbilityContext ctx, string? killerInstanceId = null) + { + var owner = FindCardOwner(ctx.State, unit.InstanceId); + if (owner is null) return; + + // Cancel deferred effects whose source is this unit. + ctx.State.PendingDeferredEffects.RemoveAll(p => p.SourceInstanceId == unit.InstanceId); + + // Fire leave-aura triggers before removing from board. + EvaluateAurasOnLeave(ctx.State, unit.InstanceId); + RevokePassivesForSource(ctx.State, unit.InstanceId); + if (unit.CardType == "Ruin") + ctx.State.Board?.RemoveRuin(unit.InstanceId); + else + ctx.State.Board?.RemoveUnit(unit.InstanceId); + RemoveFromAllZones(owner, unit, board: null); // board already handled above + unit.CurrentHealth = 0; + owner.Discard.Add(unit); + + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitDeath, + ActorId = ctx.ActorId, + Data = new TriggerEventData { TargetId = unit.InstanceId }, + UnitType = unit.CardType, + }); + + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitSentToDiscard, + ActorId = owner.AccountId, + Data = new TriggerEventData { TargetId = unit.InstanceId, SourceId = killerInstanceId }, + UnitType = unit.CardType, + }); + } + + // ── Displacement helper ─────────────────────────────────────────────────── + + private static void DisplaceUnit( + FieldCard unit, int tiles, bool fromSource, AbilityContext ctx) + { + if (!unit.Position.HasValue || ctx.Source is not FieldCard srcFc + || !srcFc.Position.HasValue || ctx.State.Board is null) + return; + + var srcPos = srcFc.Position.Value; + var unitPos = unit.Position.Value; + int dx = unitPos.X - srcPos.X; + int dy = unitPos.Y - srcPos.Y; + if (dx == 0 && dy == 0) return; + + int stepX = Math.Sign(dx); + int stepY = Math.Sign(dy); + if (!fromSource) { stepX = -stepX; stepY = -stepY; } + + var newPos = new Coord(unitPos.X + stepX * tiles, unitPos.Y + stepY * tiles); + var board = ctx.State.Board; + + if (!board.IsInBounds(newPos) || !board.GetTile(newPos)!.IsEmpty) return; + + var ownerEntry = ctx.State.Players.Values + .FirstOrDefault(p => p.Field.Any(f => f.InstanceId == unit.InstanceId)); + if (ownerEntry is null) return; + + board.RemoveUnit(unit.InstanceId); + board.PlaceUnit(newPos, unit.InstanceId, ownerEntry.AccountId); + unit.Position = newPos; + } + + // ── Zone helpers ────────────────────────────────────────────────────────── + + private static void DrawCards(PlayerState player, int n) + { + for (int i = 0; i < n && player.Deck.Count > 0; i++) + { + var top = player.Deck[^1]; + player.Deck.RemoveAt(player.Deck.Count - 1); + player.Hand.Add(top); + } + } + + private static void DiscardFromHand( + PlayerState player, int n, Filter[]? filters, AbilityContext ctx) + { + var toDiscard = player.Hand + .Where(c => filters is null || FiltersMatch(filters, c, ctx)) + .Take(n).ToList(); + foreach (var c in toDiscard) { player.Hand.Remove(c); player.Discard.Add(c); } + } + + private static void PlaceInDeck(PlayerState player, CardInstance card, string position) + { + switch (position.ToLowerInvariant()) + { + case "bottom": player.Deck.Insert(0, card); break; + case "random": + int idx = new Random().Next(player.Deck.Count + 1); + player.Deck.Insert(idx, card); break; + default: player.Deck.Add(card); break; + } + } + + private static void RemoveFromAllZones(PlayerState player, CardInstance card, Board? board) + { + if (board is not null) + { + board.RemoveUnit(card.InstanceId); + if (card.CardType == "Ruin") board.RemoveRuin(card.InstanceId); + } + player.Hand.Remove(card); + player.Deck.Remove(card); + player.Field.Remove(card); + player.Discard.Remove(card); + } + + private static PlayerState? FindCardOwner(GameState state, string instanceId) + { + foreach (var player in state.Players.Values) + { + if (player.Hand.Any(c => c.InstanceId == instanceId)) return player; + if (player.Deck.Any(c => c.InstanceId == instanceId)) return player; + if (player.Field.Any(c => c.InstanceId == instanceId)) return player; + if (player.Discard.Any(c => c.InstanceId == instanceId)) return player; + } + return null; + } + + private static PlayerState ResolvePlayerForEffect(string playerRef, AbilityContext ctx) + => playerRef.ToLowerInvariant() switch + { + "enemy" or "opponent" => + ctx.State.Players.Values.First(p => p.AccountId != ctx.ActorId), + _ => ctx.State.Players[ctx.ActorId], + }; + + // ── Condition evaluation ────────────────────────────────────────────────── + + public static bool EvaluateCondition( + Condition condition, AbilityContext ctx, object subject) + { + if (condition.Subject == "Target" && ctx.ResolvedTargets.Count > 0) + subject = ctx.ResolvedTargets.Values.Last().FirstOrDefault() ?? subject; + + var player = ctx.State.Players[ctx.ActorId]; + + switch (condition) + { + case AndCondition and: + return and.Conditions.All(c => EvaluateCondition(c, ctx, subject)); + case OrCondition or: + return or.Conditions.Any(c => EvaluateCondition(c, ctx, subject)); + case XorCondition xor: + return xor.Conditions.Count(c => EvaluateCondition(c, ctx, subject)) == 1; + + case HealthBelowCondition hb when subject is CardInstance ci: + return (ci.CurrentHealth ?? 0) < hb.N; + case HealthAboveCondition ha when subject is CardInstance ci: + return (ci.CurrentHealth ?? 0) > ha.N; + case DefenseIsCondition di when subject is CardInstance ci: + return (ci.CurrentDefense ?? 0) == di.N; + case HasGenusCondition hg when subject is CardInstance ci: + return ci.Genus?.Contains(hg.Tag) == true; + case HasAbilityCondition hab when subject is CardInstance ci: + return ParseAbilities(ci.AbilitiesJson).Any(a => a.Name == hab.AbilityRef); + case IsOnTileWithAffinityCondition iotwa when subject is FieldCard fc + && fc.Position.HasValue && ctx.State.Board is not null: + { + var tile = ctx.State.Board.GetTile(fc.Position.Value); + return tile is not null + && AffinitySystem.IsAffinityValid(tile, iotwa.Affinity); + } + case MovementTypeIsCondition mti when subject is CardInstance ci: + return ci.MovementType == mti.MovementType; + + case SPAtLeastCondition spal: return player.CurrentSp >= spal.N; + case SPAtMostCondition spam: return player.CurrentSp <= spam.N; + case STAtLeastCondition stal: return player.CurrentSt >= stal.N; + case STAtMostCondition stam: return player.CurrentSt <= stam.N; + case HandSizeAtLeastCondition hsal: return player.Hand.Count >= hsal.N; + case HandSizeAtMostCondition hsam: return player.Hand.Count <= hsam.N; + case DeckSizeAtLeastCondition dsal: return player.Deck.Count >= dsal.N; + case DiscardSizeAtLeastCondition dis: return player.Discard.Count >= dis.N; + + case IsOwnTurnCondition: + return ctx.State.ActivePlayerAccountId == ctx.ActorId; + case IsOpponentTurnCondition: + return ctx.State.ActivePlayerAccountId != ctx.ActorId; + case IsAllyTurnCondition: + return ctx.State.ActivePlayerAccountId == ctx.ActorId; + case IsActivePlayerTurnCondition iaptc: + return iaptc.Ownership.ToLowerInvariant() == "owner" + ? ctx.State.ActivePlayerAccountId == ctx.ActorId + : ctx.State.ActivePlayerAccountId != ctx.ActorId; + + case UnitCountOnBattlefieldCondition ucob: + { + IEnumerable pool = + ucob.Ownership.ToLowerInvariant() == "enemy" + ? ctx.State.Players.Values.Where(p => p.AccountId != ctx.ActorId) + .SelectMany(p => p.Field) + : player.Field; + + if (ucob.UnitType != "Unit") + pool = pool.Where(c => c.CardType == ucob.UnitType); + + int count = pool.Count(); + return ucob.Comparator switch + { + Comparator.Equal => count == ucob.N, + Comparator.NotEqual => count != ucob.N, + Comparator.LessThan => count < ucob.N, + Comparator.LessThanOrEqual => count <= ucob.N, + Comparator.GreaterThan => count > ucob.N, + Comparator.GreaterThanOrEqual => count >= ucob.N, + _ => false, + }; + } + + // ── Tile conditions (§6.3) ─────────────────────────────────────── + case TileIsOccupiedCondition tioc when subject is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + if (tile is null || tile.IsEmpty) return false; + if (tioc.UnitType is null or "Unit") return true; + return FindUnitType(ctx.State, tile.OccupantId!) == tioc.UnitType; + } + case TileIsUnoccupiedCondition when subject is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + return tile is not null && tile.IsEmpty; + } + case TileAffinityMatchesCondition tamc when subject is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + return tile is not null + && AffinitySystem.Resolve(tile.Base1, tile.Base2) == tamc.Affinity; + } + case TileAffinityMatchesCondition tamc when subject is FieldCard fc && fc.Position.HasValue: + { + var tile = ctx.State.Board?.GetTile(fc.Position.Value); + return tile is not null + && AffinitySystem.Resolve(tile.Base1, tile.Base2) == tamc.Affinity; + } + + default: + return true; + } + } + + // ── Filter evaluation ───────────────────────────────────────────────────── + + private static bool FiltersMatch(Filter[] filters, CardInstance card, AbilityContext ctx) + => filters.All(f => FilterMatches(f, card, ctx)); + + private static bool FilterMatches(Filter filter, CardInstance card, AbilityContext ctx) + => filter switch + { + GenusContainsFilter gcf => card.Genus?.Contains(gcf.Tag) == true, + CardTypeIsFilter ctif => card.CardType == ctif.CardType.ToString(), + AffinityMatchesFilter amf => card.Affinity == amf.Affinity.ToString(), + HasFlagFilter hff => hff.Flag switch + { + "IsLeader" => card.IsLeader, + "IsExhausted" => card.IsExhausted, + "CanMove" => card.CanMove, + "CanAttack" => card.CanAttack, + _ => false, + }, + TierIsFilter tif => card.Tier == tif.Tier, + // IsSelf: definition-level match (any instance of the same card definition). + IsSelfFilter => ctx.Source is not null && card.CardDefinitionId == ctx.Source.CardDefinitionId, + // IsExactSelf: instance-level match (only this specific unit on the battlefield). + IsExactSelfFilter => ctx.Source is not null && card.InstanceId == ctx.Source.InstanceId, + HealthBelowFilter hbf => (card.CurrentHealth ?? 0) < hbf.N, + HealthAboveFilter haf => (card.CurrentHealth ?? 0) > haf.N, + IsAdjacentToSourceFilter => + ctx.Source is FieldCard srcAdj && srcAdj.Position.HasValue && + card is FieldCard adjTgt && adjTgt.Position.HasValue && + srcAdj.Position.Value.IsOrthogonallyAdjacentTo(adjTgt.Position.Value), + WithinRangeFilter wrf => + ctx.Source is FieldCard srcWr && srcWr.Position.HasValue && + card is FieldCard wrTgt && wrTgt.Position.HasValue && + srcWr.Position.Value.ManhattanDistance(wrTgt.Position.Value) >= wrf.Min && + srcWr.Position.Value.ManhattanDistance(wrTgt.Position.Value) <= wrf.Max, + _ => true, + }; + + // ── Trigger matching ────────────────────────────────────────────────────── + + /// + /// The specific battlefield unit whose trigger is being evaluated. + /// Required for the "ExactSelf" ownership scope — fire only when this unit + /// is the source of the event (occ.Data.SourceId == evaluatingUnit.InstanceId). + /// + private static bool TriggerMatches( + TriggerEvent trigger, TriggerOccurrence occurrence, GameState state, string ownerId, + FieldCard? evaluatingUnit = null) + { + var uid = evaluatingUnit?.InstanceId; + return trigger switch + { + OnTurnStartTrigger t => + occurrence.Kind == TriggerEventKind.TurnStart + && Own(t.Player, occurrence, ownerId, state, uid), + OnTurnEndTrigger t => + occurrence.Kind == TriggerEventKind.TurnEnd + && Own(t.Player, occurrence, ownerId, state, uid), + OnUnitDeathTrigger t => + occurrence.Kind == TriggerEventKind.UnitDeath + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state, uid), + // Ownership = victim's side ("Enemy" = opponent spirit was discarded). + // CausedBy = killer scope; "ExactSelf" = this specific unit caused the discard. + OnUnitSentToDiscardTrigger t => + occurrence.Kind == TriggerEventKind.UnitSentToDiscard + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state, uid) + && (t.CausedBy is null || Own(t.CausedBy, occurrence, ownerId, state, uid)), + OnDamageDealtTrigger => + occurrence.Kind == TriggerEventKind.DamageDealt, + OnUnitEnterBattlefieldTrigger t => + occurrence.Kind == TriggerEventKind.UnitEnterBattlefield + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnUnitLeaveBattlefieldTrigger t => + occurrence.Kind == TriggerEventKind.UnitLeaveBattlefield + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnSPGainedTrigger t => + occurrence.Kind == TriggerEventKind.SPGained + && Own(t.Player, occurrence, ownerId, state, uid), + OnSPSpentTrigger t => + occurrence.Kind == TriggerEventKind.SPSpent + && Own(t.Player, occurrence, ownerId, state, uid), + OnSTGainedTrigger t => + occurrence.Kind == TriggerEventKind.STGained + && Own(t.Player, occurrence, ownerId, state, uid), + OnSTSpentTrigger t => + occurrence.Kind == TriggerEventKind.STSpent + && Own(t.Player, occurrence, ownerId, state, uid), + OnCardDrawnTrigger t => + occurrence.Kind == TriggerEventKind.CardDrawn + && Own(t.Player, occurrence, ownerId, state, uid), + OnUnitMoveTrigger t => + occurrence.Kind == TriggerEventKind.UnitMove + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnUnitAttackTrigger t => + occurrence.Kind == TriggerEventKind.UnitAttack + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnSpiritSacrificedTrigger t => + occurrence.Kind == TriggerEventKind.SpiritSacrificed + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnAscendTrigger t => + occurrence.Kind == TriggerEventKind.Ascend + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnTransitionTrigger t => + occurrence.Kind == TriggerEventKind.Transition + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnChanneledTrigger t => + occurrence.Kind == TriggerEventKind.Channeled + && CardType(t.CardType, occurrence.CardType) + && Own(t.Ownership, occurrence, ownerId, state, uid), + OnEnterAuraRangeTrigger eat => + occurrence.Kind == TriggerEventKind.EnterAuraRange + && Own(eat.AuraOwnership, occurrence, ownerId, state, uid) + && UnitOwnerMatches(eat.UnitOwnership, occurrence.Data?.TargetId, state, ownerId), + OnLeaveAuraRangeTrigger lat => + occurrence.Kind == TriggerEventKind.LeaveAuraRange + && Own(lat.AuraOwnership, occurrence, ownerId, state, uid) + && UnitOwnerMatches(lat.UnitOwnership, occurrence.Data?.TargetId, state, ownerId), + OnRuinActivationTrigger rat => + occurrence.Kind == TriggerEventKind.RuinActivation + && Own(rat.RuinOwnership, occurrence, ownerId, state, uid) + && (rat.OccupantOwnership is null + || UnitOwnerMatches(rat.OccupantOwnership, occurrence.Data?.TargetId, state, ownerId)), + OnUnitOccupyRuinTrigger uor => + occurrence.Kind == TriggerEventKind.UnitOccupyRuin + && Own(uor.UnitOwnership, occurrence, ownerId, state, uid), + _ => false, + }; + } + + /// + /// Instance ID of the unit whose trigger is being evaluated. + /// Only used for the "ExactSelf" scope: the trigger fires only when this unit + /// is the specific unit that caused the event (occ.Data.SourceId == evalUnitId). + /// + private static bool Own(string? scope, TriggerOccurrence occ, string unitOwnerId, GameState state, + string? evalUnitId = null) + => (scope?.ToLowerInvariant()) switch + { + null or "any" => true, + // "own"/"self"/"owner" and "ally" both use team-aware ally check so that + // in Teams / MultiTeam modes, triggered abilities fire for all teammates. + "own" or "self" or "owner" => state.AreAllies(occ.ActorId, unitOwnerId), + "ally" => state.AreAllies(occ.ActorId, unitOwnerId), + "enemy" => !state.AreAllies(occ.ActorId, unitOwnerId), + // ExactSelf: fires only for the specific unit that performed the action. + // Requires occ.Data.SourceId to carry the acting unit's instance ID. + "exactself" => evalUnitId is not null && occ.Data?.SourceId == evalUnitId, + _ => true, + }; + + private static bool UnitOwnerMatches( + string scope, string? unitInstanceId, GameState state, string referenceOwnerId) + { + if (scope.ToLowerInvariant() == "any" || unitInstanceId is null) return true; + foreach (var (ownerId, player) in state.Players) + if (player.Field.Any(c => c.InstanceId == unitInstanceId)) + return scope.ToLowerInvariant() switch + { + "ally" or "owner" => ownerId == referenceOwnerId, + "enemy" => ownerId != referenceOwnerId, + _ => true, + }; + return true; + } + + private static bool UnitType(string? required, string? actual) + => required is null or "Unit" or "Any" || required == actual; + + private static bool CardType(string? required, string? actual) + => required is null or "Any" || required == actual; + + // ── Value / affinity resolution ─────────────────────────────────────────── + + private static int ResolveValue(ValueExpr expr, AbilityContext ctx) + { + if (expr.Fixed.HasValue) return expr.Fixed.Value; + if (expr.Ref is null) return 0; + var parts = expr.Ref.Split('.'); + var p0 = parts[0]; + var p1 = parts.Length > 1 ? parts[1] : ""; + var p2 = parts.Length > 2 ? parts[2] : ""; + + // "Self.*" — source unit's properties. + if (p0 == "Self") + return p1 switch + { + "Damage" => ctx.Source?.Damage ?? 0, + "Health" => ctx.Source?.CurrentHealth ?? 0, + "Defense" => ctx.Source?.CurrentDefense ?? 0, + "MP" => (ctx.Source as FieldCard)?.CurrentMp ?? 0, + "SpCost" => ctx.Source?.SpCost ?? 0, + "StCost" => ctx.Source?.StCost ?? 0, + _ => 0, + }; + + // "EventData.*" — data from the triggering event. + if (p0 == "EventData") + return p1 == "Amount" ? ctx.EventData?.Amount ?? 0 : 0; + + // "Target.*" — first resolved target of the most-recently-resolved action. + if (p0 == "Target") + { + var target = ctx.ResolvedTargets.Count > 0 + ? ctx.ResolvedTargets.Values.Last().FirstOrDefault() + : null; + return ResolveTargetProp(target, p1); + } + + // "ActionN.Target.*" — first resolved target of action N (cross-action reference). + if (p0.StartsWith("Action") && p1 == "Target" + && int.TryParse(p0[6..], out int actionIdx) + && ctx.ResolvedTargets.TryGetValue(actionIdx, out var tgts)) + return ResolveTargetProp(tgts.FirstOrDefault(), p2); + + return 0; + } + + private static int ResolveTargetProp(object? target, string prop) + { + if (target is not CardInstance ci) return 0; + return prop switch + { + "Damage" => ci.Damage ?? 0, + "Health" => ci.CurrentHealth ?? 0, + "Defense" => ci.CurrentDefense ?? 0, + "MP" => (ci as FieldCard)?.CurrentMp ?? 0, + "SpCost" => ci.SpCost, + "StCost" => ci.StCost, + _ => 0, + }; + } + + private static Affinity ResolveAffinity(AffinityExpr expr, AbilityContext ctx) + { + if (expr.Fixed.HasValue) return expr.Fixed.Value; + if (expr.Ref is null) return Affinity.Void; + var parts = expr.Ref.Split('.'); + return (parts[0], parts.Length > 1 ? parts[1] : "") switch + { + ("Self", "Affinity") when ctx.Source is not null => + Enum.TryParse(ctx.Source.Affinity, out var a) ? a : Affinity.Void, + _ => Affinity.Void, + }; + } + + // ── Duration tracking ────────────────────────────────────────────────────── + + private static ValueExpr V(int n) => new() { Fixed = n }; + + /// Internal metadata envelope stored in ActiveEffect.DurationJson. + private sealed class TrackedDuration + { + public DurationModel Duration { get; set; } = new(); + public string OwnerAccountId { get; set; } = string.Empty; + /// True for DOT/HOT tick effects (apply each turn); false for reversal effects. + public bool IsTick { get; set; } + } + + /// + /// Stores a reversal effect to be applied when the duration expires. + /// No-op for Instant or PermanentInMatch durations. + /// + private static void TrackEffect( + Effect reversal, + string targetRef, + DurationModel? duration, + AbilityContext ctx) + { + if (duration is null + || duration.Type is DurationType.Instant or DurationType.PermanentInMatch) + return; + + ctx.State.ActiveEffects.Add(new ActiveEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? "", + TargetRef = targetRef, + EffectJson = JsonSerializer.Serialize(reversal, _jsonOpts), + DurationJson = JsonSerializer.Serialize(new TrackedDuration + { + Duration = duration, + OwnerAccountId = ctx.ActorId, + }, _jsonOpts), + TurnsRemaining = duration.N ?? 0, + }); + } + + /// + /// Stores a tick effect (DOT/HOT) to be applied each turn for the duration. + /// + private static void TrackTick( + Effect tickEffect, + string targetRef, + DurationModel duration, + AbilityContext ctx) + { + if (duration.Type is DurationType.Instant or DurationType.PermanentInMatch) + return; + + ctx.State.ActiveEffects.Add(new ActiveEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? "", + TargetRef = targetRef, + EffectJson = JsonSerializer.Serialize(tickEffect, _jsonOpts), + DurationJson = JsonSerializer.Serialize(new TrackedDuration + { + Duration = duration, + OwnerAccountId = ctx.ActorId, + IsTick = true, + }, _jsonOpts), + TurnsRemaining = duration.N ?? 0, + }); + } + + /// + /// Fires DOT/HOT tick effects for the given player's turn. + /// Call at TurnEnd before expiry processing. + /// + public static GameState TickActiveEffects(GameState state, string activePlayerId) + { + foreach (var ae in state.ActiveEffects.ToList()) + { + TrackedDuration? td; + try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } + catch { continue; } + if (td?.IsTick != true) continue; + + Effect? eff; + try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); } + catch { continue; } + if (eff is null) continue; + + var tgt = state.Players.Values + .SelectMany(p => p.Field) + .FirstOrDefault(c => c.InstanceId == ae.TargetRef); + if (tgt is null) continue; + + var src = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId); + + ExecuteEffect(eff, tgt, DurationModel.Instant, new AbilityContext + { + State = state, + ActorId = td.OwnerAccountId, + Source = src, + }); + } + return state; + } + + /// + /// Expires duration-tracked effects at a turn boundary. + /// Call with =true at end of 's + /// turn, and false at start of 's turn (after player switch). + /// + public static GameState ExpireActiveEffects( + GameState state, + string currentPlayerId, + bool isEndOfTurn) + { + var toRemove = new List(); + foreach (var ae in state.ActiveEffects) + { + TrackedDuration? td; + try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } + catch { continue; } + if (td is null) continue; + + var dur = td.Duration; + switch (dur.Type) + { + case DurationType.UntilEndOfTurn: + if (isEndOfTurn + && (dur.PlayerScope is null + || MatchPlayerScope(dur.PlayerScope, currentPlayerId, td.OwnerAccountId))) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + break; + + case DurationType.UntilStartOfOwnerTurn: + case DurationType.UntilStartOfSourceOwnerTurn: + if (!isEndOfTurn && currentPlayerId == td.OwnerAccountId) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + break; + + case DurationType.ForNTurns: + if (isEndOfTurn) + { + ae.TurnsRemaining--; + if (ae.TurnsRemaining <= 0) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + } + break; + + case DurationType.WhileCondition: + if (dur.Condition is not null) + { + var src = state.Players.Values + .SelectMany(p => p.Field) + .FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId); + var condCtx = new AbilityContext + { + State = state, + ActorId = td.OwnerAccountId, + Source = src, + }; + if (!EvaluateCondition(dur.Condition, condCtx, src ?? (object)state)) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + } + break; + } + } + foreach (var ae in toRemove) state.ActiveEffects.Remove(ae); + return state; + } + + private static bool MatchPlayerScope( + string scope, string currentPlayerId, string ownerAccountId) + => scope.ToLowerInvariant() switch + { + "owner" or "self" => currentPlayerId == ownerAccountId, + "enemy" => currentPlayerId != ownerAccountId, + _ => true, + }; + + private static void ApplyReversal(GameState state, ActiveEffect ae, string ownerAccountId) + { + Effect? eff; + try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); } + catch { return; } + if (eff is null) return; + + // Find target by instanceId (any zone) or by accountId (player). + object? tgt = null; + foreach (var p in state.Players.Values) + { + tgt = (CardInstance?)( + p.Field.FirstOrDefault(c => c.InstanceId == ae.TargetRef) + ?? p.Hand.FirstOrDefault(c => c.InstanceId == ae.TargetRef) + ?? p.Deck.FirstOrDefault(c => c.InstanceId == ae.TargetRef) + ?? p.Discard.FirstOrDefault(c => c.InstanceId == ae.TargetRef)); + if (tgt is not null) break; + if (p.AccountId == ae.TargetRef) { tgt = p; break; } + } + // Tile target: reference format is "tile:X,Y". + if (tgt is null && ae.TargetRef.StartsWith("tile:")) + { + var parts = ae.TargetRef[5..].Split(','); + if (parts.Length == 2 + && int.TryParse(parts[0], out var tx) + && int.TryParse(parts[1], out var ty)) + tgt = new Coord(tx, ty); + } + if (tgt is null) return; + + var src = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId); + + // Execute with Instant duration so the reversal does not itself get tracked. + ExecuteEffect(eff, tgt, DurationModel.Instant, new AbilityContext + { + State = state, + ActorId = ownerAccountId, + Source = src, + }); + } + + // ── Passive ability application / revocation ───────────────────────────── + + /// + /// Executes all abilities for + /// against all current battlefield units. Effects are tracked with + /// so they are reversed when the source dies + /// or leaves. Call after placing the unit on the board. + /// + public static void ApplyPassivesForSource(GameState state, string sourceUnitId, string ownerId) + { + var source = state.Players.Values + .SelectMany(p => p.Field.OfType()) + .FirstOrDefault(f => f.InstanceId == sourceUnitId); + if (source is null) return; + + var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = source }; + var fallback = new DurationModel { Type = DurationType.WhileSourceOnBattlefield }; + foreach (var def in ParseAbilities(source.AbilitiesJson).Where(d => d.Type == AbilityType.Passive)) + { + // Honour ability-level activation conditions (e.g. IsOnTileWithAffinity). + if (def.ActivationConditions is { Length: > 0 } && + !def.ActivationConditions.All(c => EvaluateCondition(c, ctx, source))) + continue; + + ExecuteActions(def.Actions, ctx, clientTargets: null, + forceDuration: def.Duration ?? fallback); + } + } + + /// + /// Applies all existing passive abilities from every battlefield unit to . + /// Restricts targeting to the new unit so already-buffed units are not double-applied. + /// Call after for the new unit. + /// + public static void ApplyPassivesToNewTarget(GameState state, string newUnitId) + { + var restrict = new HashSet { newUnitId }; + var fallback = new DurationModel { Type = DurationType.WhileSourceOnBattlefield }; + foreach (var (ownerId, player) in state.Players) + foreach (var sourceUnit in player.Field.OfType() + .Where(f => f.InstanceId != newUnitId).ToList()) + { + var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = sourceUnit }; + foreach (var def in ParseAbilities(sourceUnit.AbilitiesJson).Where(d => d.Type == AbilityType.Passive)) + { + // Respect activation conditions evaluated against the source unit. + if (def.ActivationConditions is { Length: > 0 } && + !def.ActivationConditions.All(c => EvaluateCondition(c, ctx, sourceUnit))) + continue; + + ExecuteActions(def.Actions, ctx, clientTargets: null, + restrictTargets: restrict, forceDuration: def.Duration ?? fallback); + } + } + } + + /// + /// Reverses all active effects whose + /// source is . Call before removing a unit from the board. + /// + public static void RevokePassivesForSource(GameState state, string sourceUnitId) + { + var toRevoke = state.ActiveEffects + .Where(ae => ae.SourceInstanceId == sourceUnitId) + .Where(ae => + { + try + { + var td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); + return td?.Duration?.Type == DurationType.WhileSourceOnBattlefield; + } + catch { return false; } + }) + .ToList(); + + foreach (var ae in toRevoke) + { + TrackedDuration? td = null; + try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } catch { } + if (td is not null) ApplyReversal(state, ae, td.OwnerAccountId); + state.ActiveEffects.Remove(ae); + } + } + + /// + /// Revokes and reapplies every passive that carries , + /// keeping condition-gated buffs in sync with the current game state. + /// Call after any action that could change condition outcomes (unit movement, + /// tile affinity change, ability activation, etc.). + /// Units without conditional passives are skipped at zero cost. + /// + public static void ReEvaluateConditionalPassives(GameState state) + { + foreach (var (ownerId, player) in state.Players) + { + foreach (var unit in player.Field.OfType().ToList()) + { + bool hasConditional = ParseAbilities(unit.AbilitiesJson) + .Any(d => d.Type == AbilityType.Passive && d.ActivationConditions is { Length: > 0 }); + if (!hasConditional) continue; + + // Full revoke-then-reapply so stat modifiers stay correct regardless + // of which side of a condition boundary the unit currently sits on. + RevokePassivesForSource(state, unit.InstanceId); + ApplyPassivesForSource(state, unit.InstanceId, ownerId); + } + } + } + + // ── Aura range evaluation ───────────────────────────────────────────────── + + /// + /// Fires OnEnterAuraRange / OnLeaveAuraRange triggers when a unit moves from + /// to . + /// Handles both the moving unit crossing into/out of stationary auras, and the + /// moving unit's own auras sweeping over stationary units. + /// Call after updating the unit's position on the board. + /// + public static GameState EvaluateAuraTransitions( + GameState state, + string movingUnitId, + Coord from, + Coord to) + { + // Part 1: stationary aura-bearing units vs. moving unit's position change. + foreach (var (auraOwnerId, player) in state.Players) + foreach (var auraUnit in player.Field.OfType() + .Where(f => f.Position.HasValue && f.InstanceId != movingUnitId).ToList()) + { + foreach (var def in ParseAbilities(auraUnit.AbilitiesJson) + .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) + { + var auraPos = auraUnit.Position!.Value; + int min = def.AuraRange!.Min, max = def.AuraRange.Max; + FireAuraTransition(state, auraOwnerId, auraUnit, def, movingUnitId, + wasIn: from.ManhattanDistance(auraPos) >= min && from.ManhattanDistance(auraPos) <= max, + isIn: to.ManhattanDistance(auraPos) >= min && to.ManhattanDistance(auraPos) <= max); + } + } + + // Part 2: moving unit's own auras vs. stationary units. + var movingUnit = state.Players.Values + .SelectMany(p => p.Field.OfType()) + .FirstOrDefault(f => f.InstanceId == movingUnitId); + if (movingUnit is null) return state; + + string? movingOwnerId = null; + foreach (var (oid, pl) in state.Players) + if (pl.Field.Any(c => c.InstanceId == movingUnitId)) { movingOwnerId = oid; break; } + if (movingOwnerId is null) return state; + + foreach (var def in ParseAbilities(movingUnit.AbilitiesJson) + .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) + { + int min = def.AuraRange!.Min, max = def.AuraRange.Max; + foreach (var (_, pl) in state.Players) + foreach (var other in pl.Field.OfType() + .Where(f => f.Position.HasValue && f.InstanceId != movingUnitId).ToList()) + { + var otherPos = other.Position!.Value; + FireAuraTransition(state, movingOwnerId, movingUnit, def, other.InstanceId, + wasIn: from.ManhattanDistance(otherPos) >= min && from.ManhattanDistance(otherPos) <= max, + isIn: to.ManhattanDistance(otherPos) >= min && to.ManhattanDistance(otherPos) <= max); + } + } + + return state; + } + + /// + /// Fires OnEnterAuraRange triggers for a unit newly placed on the battlefield. + /// Handles both existing auras covering the new unit and the new unit's own auras + /// covering existing units. + /// Call after placing the unit at its initial position. + /// + public static GameState EvaluateAurasOnEnter(GameState state, string newUnitId) + { + var newUnit = state.Players.Values + .SelectMany(p => p.Field.OfType()) + .FirstOrDefault(f => f.InstanceId == newUnitId); + if (newUnit?.Position is null) return state; + var newPos = newUnit.Position.Value; + + // Part 1: existing aura units — check if new unit entered their range. + foreach (var (auraOwnerId, player) in state.Players) + foreach (var auraUnit in player.Field.OfType() + .Where(f => f.Position.HasValue && f.InstanceId != newUnitId).ToList()) + { + foreach (var def in ParseAbilities(auraUnit.AbilitiesJson) + .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) + { + int dist = newPos.ManhattanDistance(auraUnit.Position!.Value); + if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max) + FireAuraTransition(state, auraOwnerId, auraUnit, def, newUnitId, wasIn: false, isIn: true); + } + } + + // Part 2: new unit's own auras — check all existing units. + string? newUnitOwnerId = null; + foreach (var (oid, pl) in state.Players) + if (pl.Field.Any(c => c.InstanceId == newUnitId)) { newUnitOwnerId = oid; break; } + if (newUnitOwnerId is null) return state; + + foreach (var def in ParseAbilities(newUnit.AbilitiesJson) + .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) + { + foreach (var (_, pl) in state.Players) + foreach (var other in pl.Field.OfType() + .Where(f => f.Position.HasValue && f.InstanceId != newUnitId).ToList()) + { + int dist = newPos.ManhattanDistance(other.Position!.Value); + if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max) + FireAuraTransition(state, newUnitOwnerId, newUnit, def, other.InstanceId, wasIn: false, isIn: true); + } + } + + return state; + } + + /// + /// Fires OnLeaveAuraRange triggers for a unit about to leave the battlefield. + /// Handles both existing auras and the leaving unit's own auras. + /// Call before removing the unit from the board. + /// + public static GameState EvaluateAurasOnLeave(GameState state, string leavingUnitId) + { + var leavingUnit = state.Players.Values + .SelectMany(p => p.Field.OfType()) + .FirstOrDefault(f => f.InstanceId == leavingUnitId); + if (leavingUnit?.Position is null) return state; + var leavingPos = leavingUnit.Position.Value; + + // Part 1: existing aura units — check if leaving unit was in their range. + foreach (var (auraOwnerId, player) in state.Players) + foreach (var auraUnit in player.Field.OfType() + .Where(f => f.Position.HasValue && f.InstanceId != leavingUnitId).ToList()) + { + foreach (var def in ParseAbilities(auraUnit.AbilitiesJson) + .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) + { + int dist = leavingPos.ManhattanDistance(auraUnit.Position!.Value); + if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max) + FireAuraTransition(state, auraOwnerId, auraUnit, def, leavingUnitId, wasIn: true, isIn: false); + } + } + + // Part 2: leaving unit's own auras — fire LeaveAuraRange for each in-range unit. + string? leavingOwnerId = null; + foreach (var (oid, pl) in state.Players) + if (pl.Field.Any(c => c.InstanceId == leavingUnitId)) { leavingOwnerId = oid; break; } + if (leavingOwnerId is null) return state; + + foreach (var def in ParseAbilities(leavingUnit.AbilitiesJson) + .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) + { + foreach (var (_, pl) in state.Players) + foreach (var other in pl.Field.OfType() + .Where(f => f.Position.HasValue && f.InstanceId != leavingUnitId).ToList()) + { + int dist = leavingPos.ManhattanDistance(other.Position!.Value); + if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max) + FireAuraTransition(state, leavingOwnerId, leavingUnit, def, other.InstanceId, wasIn: true, isIn: false); + } + } + + return state; + } + + /// + /// Executes the aura ability's own Actions on when it enters + /// range. Uses .Duration if set, otherwise WhileSourceOnBattlefield. + /// + private static void ApplyAuraEffects( + GameState state, + string auraOwnerId, + FieldCard auraUnit, + AbilityDefinition def, + string targetUnitId) + { + if (def.Actions is not { Length: > 0 }) return; + + // Honour aura-level activation conditions (e.g. IsOnTileWithAffinity of the aura source). + var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit }; + if (def.ActivationConditions is { Length: > 0 } && + !def.ActivationConditions.All(c => EvaluateCondition(c, ctx, auraUnit))) + return; + + var fallback = new DurationModel { Type = DurationType.WhileSourceOnBattlefield }; + ExecuteActions(def.Actions, ctx, clientTargets: null, + restrictTargets: new HashSet { targetUnitId }, + forceDuration: def.Duration ?? fallback); + } + + /// + /// Handles the leave-range side-effects of an aura. + /// If is set, switches tracked effects to that + /// duration instead of revoking them. If is set, + /// immediately reverts and removes the effects. Otherwise does nothing (effects expire normally). + /// + private static void HandleAuraLeave( + GameState state, + FieldCard auraUnit, + AbilityDefinition def, + string targetUnitId, + string auraOwnerId) + { + if (def.Actions is not { Length: > 0 }) return; + + var matching = state.ActiveEffects + .Where(ae => ae.SourceInstanceId == auraUnit.InstanceId && ae.TargetRef == targetUnitId) + .ToList(); + if (matching.Count == 0) return; + + if (def.LingerDuration is not null) + { + // Switch the tracked effects to the linger duration so they outlive the aura range. + foreach (var ae in matching) + { + ae.DurationJson = JsonSerializer.Serialize( + new TrackedDuration { Duration = def.LingerDuration, OwnerAccountId = auraOwnerId }, + _jsonOpts); + ae.TurnsRemaining = def.LingerDuration.N ?? 0; + } + } + else if (def.ClearOnLeave) + { + foreach (var ae in matching) + { + TrackedDuration? td = null; + try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } catch { } + if (td is not null && !td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + state.ActiveEffects.Remove(ae); + } + } + } + + private static void FireAuraTransition( + GameState state, + string auraOwnerId, + FieldCard auraUnit, + AbilityDefinition def, + string targetUnitId, + bool wasIn, + bool isIn) + { + if (!wasIn && isIn) + { + FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.EnterAuraRange, + ActorId = auraOwnerId, + Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = targetUnitId }, + }); + ApplyAuraEffects(state, auraOwnerId, auraUnit, def, targetUnitId); + } + else if (wasIn && !isIn) + { + FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.LeaveAuraRange, + ActorId = auraOwnerId, + Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = targetUnitId }, + }); + HandleAuraLeave(state, auraUnit, def, targetUnitId, auraOwnerId); + } + } +} diff --git a/reference/SOR.Game/Abilities/EffectPolymorphicConverter.cs b/reference/SOR.Game/Abilities/EffectPolymorphicConverter.cs new file mode 100644 index 0000000..3a605ee --- /dev/null +++ b/reference/SOR.Game/Abilities/EffectPolymorphicConverter.cs @@ -0,0 +1,100 @@ +namespace SOR.Game.Abilities; + +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using SOR.Game.Abilities.Models; + +/// +/// Generic base converter that fixes polymorphic deserialization when the +/// $type discriminator is not the first property in a JSON object. +/// +/// System.Text.Json requires $type to appear first for abstract base +/// classes. Card-definition JSON authored in the admin tool does not guarantee +/// that ordering. This converter buffers the entire JSON object, finds +/// $type at any position, looks up the concrete type from the +/// map on , +/// then deserializes via the default converter. +/// +/// CanConvert returns true only for the exact base type +/// — not for concrete derived types — so there is no +/// infinite recursion when the default converter processes derived-type properties. +/// +internal abstract class PolymorphicAbilityConverter : JsonConverter where T : class +{ + // Static fields are per closed type T — each T gets its own map. + private static readonly Dictionary s_typeMap; + private static readonly Dictionary s_reverseMap; + + static PolymorphicAbilityConverter() + { + s_typeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + s_reverseMap = new Dictionary(); + + foreach (var attr in typeof(T).GetCustomAttributes()) + { + s_typeMap[attr.Discriminator] = attr.DerivedType; + // First [PolyType] for a given concrete type wins for writing (canonical discriminator). + // Additional attributes register read-only aliases for backwards compatibility. + s_reverseMap.TryAdd(attr.DerivedType, attr.Discriminator); + } + } + + /// + /// Only intercept the abstract base itself. + /// Concrete derived types fall through to the default serializer. + /// + public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(T); + + public override T? Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + using var doc = JsonDocument.ParseValue(ref reader); + var root = doc.RootElement; + + if (!root.TryGetProperty("$type", out var discriminatorProp)) + throw new JsonException($"{typeof(T).Name} object is missing the '$type' discriminator."); + + var discriminator = discriminatorProp.GetString() + ?? throw new JsonException($"{typeof(T).Name} '$type' discriminator is null."); + + if (!s_typeMap.TryGetValue(discriminator, out var concreteType)) + throw new JsonException($"Unknown {typeof(T).Name} '$type': '{discriminator}'."); + + // CanConvert returns false for concrete derived types, so no infinite recursion. + return (T?)root.Deserialize(concreteType, options); + } + + public override void Write( + Utf8JsonWriter writer, + T value, + JsonSerializerOptions options) + { + var concreteType = value.GetType(); + if (!s_reverseMap.TryGetValue(concreteType, out var discriminator)) + throw new JsonException($"No '$type' discriminator registered for {concreteType.Name}."); + + // Serialize the concrete object (CanConvert=false for it → no recursion). + using var mem = new System.IO.MemoryStream(); + using (var inner = new Utf8JsonWriter(mem)) + JsonSerializer.Serialize(inner, value, concreteType, options); + + using var doc = JsonDocument.Parse(mem.ToArray()); + + // Write with $type first so round-trip JSON is always well-formed. + writer.WriteStartObject(); + writer.WriteString("$type", discriminator); + foreach (var prop in doc.RootElement.EnumerateObject()) + prop.WriteTo(writer); + writer.WriteEndObject(); + } +} + +// ── Concrete converters ─────────────────────────────────────────────────────── + +internal sealed class EffectPolymorphicConverter : PolymorphicAbilityConverter { } +internal sealed class ConditionPolymorphicConverter : PolymorphicAbilityConverter { } +internal sealed class TriggerPolymorphicConverter : PolymorphicAbilityConverter{ } +internal sealed class FilterPolymorphicConverter : PolymorphicAbilityConverter { } diff --git a/reference/SOR.Game/Abilities/Models/AbilityAnimationDefinition.cs b/reference/SOR.Game/Abilities/Models/AbilityAnimationDefinition.cs new file mode 100644 index 0000000..b318715 --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/AbilityAnimationDefinition.cs @@ -0,0 +1,56 @@ +namespace SOR.Game.Abilities.Models; + +/// The visual presentation style for an ability animation. +public enum AbilityAnimationType +{ + /// A projectile that arcs from caster to target. + Projectile, + /// A projectile that travels in a straight line from caster to target. + LinearProjectile, + /// A projectile that follows a parabolic arc from caster to target. + ArcProjectile, + /// A radial aura effect centered on the caster or target. + Aura, +} + +/// Where the animation effect VFX is rendered. +public enum AbilityAnimationEffect +{ + /// Effect plays on the ability's source unit. + Self, + /// Effect plays on each selected target. + Target, + /// Effect plays on a subset of affected units. + Some, + /// Effect covers the entire board (e.g. board-wide clear). + All, +} + +/// +/// Client-side animation and sound metadata for an ability. +/// Stored inside AbilityDefinition.Animation (JSONB). +/// Not used by server game logic — purely for the client renderer and audio system. +/// +public sealed class AbilityAnimationDefinition +{ + public AbilityAnimationType Type { get; set; } = AbilityAnimationType.Projectile; + public AbilityAnimationEffect Effect { get; set; } = AbilityAnimationEffect.Target; + + /// CDN URL to the animation asset (particle effect, sprite sheet, etc.). + public string? AssetUrl { get; set; } + + /// Scale width multiplier for the effect (1.0 = default size). + public float Width { get; set; } = 1f; + + /// Scale height multiplier for the effect (1.0 = default size). + public float Height { get; set; } = 1f; + + /// Duration of the animation in seconds. + public float Duration { get; set; } = 1f; + + /// CDN URL to the sound played when the ability is cast/activated. + public string? CastSoundUrl { get; set; } + + /// CDN URL to the sound played on impact/effect resolution. + public string? ImpactSoundUrl { get; set; } +} diff --git a/reference/SOR.Game/Abilities/Models/AbilityDefinition.cs b/reference/SOR.Game/Abilities/Models/AbilityDefinition.cs new file mode 100644 index 0000000..f8ec3ea --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/AbilityDefinition.cs @@ -0,0 +1,80 @@ +namespace SOR.Game.Abilities.Models; + +/// Ability type determines activation model and required fields. +public enum AbilityType +{ + /// Manually activated by the controlling player. Costs optional range and UsesPerTurn. + Active, + /// Always active while the unit is in play and conditions are met. No activation, no cost. + Passive, + /// Always-on area effect anchored to a unit's position. Evaluated per-turn and on unit entry. + Aura, + /// Automatically fires when a matching TriggerEvent occurs. + Triggered, +} + +/// +/// The top-level definition of a unit ability or card effect. +/// Stored as JSONB in CardDefinition.AbilitiesJson (array) and CardDefinition.EffectsJson. +/// +/// All four ability types share the Action/Effect/Condition model. +/// Type-specific fields are non-null only for the relevant type. +/// +public sealed class AbilityDefinition +{ + public AbilityType Type { get; set; } + public Condition[]? ActivationConditions { get; set; } + public Action[] Actions { get; set; } = []; + + // ── Active only ────────────────────────────────────────────────────────── + public CostEntry[]? Cost { get; set; } + public AbilityRange? Range { get; set; } + /// How many times this Active ability may be used per turn (default 1). + public int UsesPerTurn { get; set; } = 1; + + // ── Aura only ──────────────────────────────────────────────────────────── + public AbilityRange? AuraRange { get; set; } + /// + /// When true, effects applied by this aura to a unit are reverted immediately when that + /// unit leaves range. Default false: effects expire at their configured Duration. + /// Ignored when is set. + /// + public bool ClearOnLeave { get; set; } + /// + /// If set, effects switch to this duration when a unit leaves range instead of + /// being reverted immediately. Takes precedence over . + /// Null means effects expire at their own configured Duration. + /// + public DurationModel? LingerDuration { get; set; } + + // ── Triggered only ─────────────────────────────────────────────────────── + /// The event that fires this ability. Must be set for Triggered type. + public TriggerEvent? TriggerEvent { get; set; } + + /// + /// Optional display name shown in the admin tool and client ability list. + /// Not required for game logic. + /// + public string? Name { get; set; } + + /// + /// Plain-English description of what this ability does. + /// Used in the admin ability builder. Not used by game logic. + /// + public string? Description { get; set; } + + /// + /// Optional ability-level duration that overrides per-action Duration for every effect + /// this ability produces. When null, each Action's own Duration is used instead. + /// + /// For Passive abilities this defaults to WhileSourceOnBattlefield when left null; + /// set it explicitly to choose a different lifespan (e.g. UntilEndOfTurn). + /// + public DurationModel? Duration { get; set; } + + /// + /// Optional client-side animation and sound metadata. + /// Not used by server game logic. Null means the client uses its default effect. + /// + public AbilityAnimationDefinition? Animation { get; set; } +} diff --git a/reference/SOR.Game/Abilities/Models/Action.cs b/reference/SOR.Game/Abilities/Models/Action.cs new file mode 100644 index 0000000..7d0a2eb --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/Action.cs @@ -0,0 +1,136 @@ +namespace SOR.Game.Abilities.Models; + +// ── Value expression ────────────────────────────────────────────────────────── + +/// +/// An integer value that may be a fixed constant or a dynamic runtime reference. +/// Dynamic references (§4.5) use dot-path notation, e.g.: +/// "EventData.Amount", "Self.Damage", "Action1.Target.Defense" +/// +public sealed class ValueExpr +{ + public int? Fixed { get; set; } + public string? Ref { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + public bool IsDynamic => Ref is not null; + + public static implicit operator ValueExpr(int n) => new() { Fixed = n }; +} + +/// +/// An affinity value that may be fixed or a dynamic reference. +/// E.g.: "Self.Affinity", "Action1.Target.Affinity". +/// +public sealed class AffinityExpr +{ + public SOR.Database.Enums.Affinity? Fixed { get; set; } + public string? Ref { get; set; } +} + +// ── Target selector ─────────────────────────────────────────────────────────── + +public enum TargetScope { Hand, Deck, Discard, Battlefield, Player, AnyZone } +public enum TargetType { Unit, ArchSpirit, Spirit, SpiritToken, Ruin, Tile, Card, Player } +public enum TargetOwnership { Self, ExactSelf, Owner, Ally, Enemy, Any, Random, Target } + +public sealed class TargetCount +{ + /// Exact number of targets; or the maximum when UpTo=true. + public int N { get; set; } = 1; + /// Player may select fewer than N valid targets. + public bool UpTo { get; set; } + /// Target all valid entities (N is ignored). + public bool All { get; set; } +} + +/// +/// Defines how targets are resolved for a single Action. +/// Scope + Type + Ownership narrow the pool; Filters refine further. +/// +public sealed class TargetSelector +{ + public TargetScope Scope { get; set; } + public TargetType Type { get; set; } + public TargetOwnership Ownership { get; set; } + public TargetCount Count { get; set; } = new(); + public Filter[]? Filters { get; set; } +} + +// ── Action ──────────────────────────────────────────────────────────────────── + +/// +/// The atomic unit of targeting and effect delivery within an ability. +/// All effects within one action share the same target and duration. +/// Actions within an ability resolve sequentially; a prior action's resolved +/// target is accessible in subsequent actions via chained targeting filters. +/// +public sealed class Action +{ + public TargetSelector Target { get; set; } = new(); + public Condition[]? Conditions { get; set; } + public Effect[] Effects { get; set; } = []; + public DurationModel? Duration { get; set; } +} + +// ── ChooseOne ───────────────────────────────────────────────────────────────── + +/// +/// Presents the controlling player with a set of mutually exclusive action branches. +/// Exactly one branch is selected and its actions resolve; other branches are skipped. +/// ChooseOne may appear anywhere an Action[] is accepted. +/// +public sealed class ChooseOne +{ + public Branch[] Branches { get; set; } = []; +} + +public sealed class Branch +{ + public string Label { get; set; } = string.Empty; + public Action[] Actions { get; set; } = []; +} + +// ── Cost entry ──────────────────────────────────────────────────────────────── + +public enum CostType +{ + SpiritPoints, + SacrificeTokens, + DiscardFromHand, + MillTopOfDeck, + MillBottomOfDeck, + SendSpiritFromBattlefieldToDiscard, + DealDamageToOwnArchSpirit, + DealDamageToOwnSpirit, +} + +/// +/// A single cost element for an Active ability. +/// Multiple CostEntry items must all be paid simultaneously before the ability resolves. +/// +public sealed class CostEntry +{ + public CostType Type { get; set; } + public int Amount { get; set; } = 1; + /// Optional filter for targeted costs (e.g. "Discard a Spirit card from hand"). + public Filter[]? Filters { get; set; } +} + +// ── Ability range ───────────────────────────────────────────────────────────── + +public sealed class AbilityRange +{ + public int Min { get; set; } = 1; + public int Max { get; set; } = 1; + /// + /// When true, the engine validates that a clear line of sight exists between the + /// caster and the target tile/unit before allowing the ability to be used. + /// + public bool RequiresLos { get; set; } = false; + /// + /// When true, only targets that lie on a straight cardinal or diagonal line from + /// the caster are valid (e.g. Push, Pull, beam-style abilities). + /// + public bool LinearOnly { get; set; } = false; +} diff --git a/reference/SOR.Game/Abilities/Models/Conditions.cs b/reference/SOR.Game/Abilities/Models/Conditions.cs new file mode 100644 index 0000000..186c563 --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/Conditions.cs @@ -0,0 +1,130 @@ +namespace SOR.Game.Abilities.Models; + +using SOR.Database.Enums; + +// ── Condition base ──────────────────────────────────────────────────────────── + +/// +/// A boolean predicate evaluated against a subject entity. +/// The default subject is Self (the source unit or ability owner). +/// Override with Subject = "Target" to evaluate against the current action's resolved target. +/// +// Composite +[PolyType(typeof(AndCondition), "AND")] +[PolyType(typeof(OrCondition), "OR")] +[PolyType(typeof(XorCondition), "XOR")] +// Unit (§6.1) +[PolyType(typeof(HealthBelowCondition), "HealthBelow")] +[PolyType(typeof(HealthAboveCondition), "HealthAbove")] +[PolyType(typeof(DefenseIsCondition), "DefenseIs")] +[PolyType(typeof(HasGenusCondition), "HasGenus")] +[PolyType(typeof(HasAbilityCondition), "HasAbility")] +[PolyType(typeof(IsOnTileWithAffinityCondition), "IsOnTileWithAffinity")] +[PolyType(typeof(IsAdjacentToCondition), "IsAdjacentTo")] +[PolyType(typeof(WithinRangeOfCondition), "WithinRangeOf")] +[PolyType(typeof(MovementTypeIsCondition), "MovementTypeIs")] +// Player (§6.2) +[PolyType(typeof(SPAtLeastCondition), "SPAtLeast")] +[PolyType(typeof(SPAtMostCondition), "SPAtMost")] +[PolyType(typeof(STAtLeastCondition), "STAtLeast")] +[PolyType(typeof(STAtMostCondition), "STAtMost")] +[PolyType(typeof(HandSizeAtLeastCondition), "HandSizeAtLeast")] +[PolyType(typeof(HandSizeAtMostCondition), "HandSizeAtMost")] +[PolyType(typeof(DeckSizeAtLeastCondition), "DeckSizeAtLeast")] +[PolyType(typeof(DiscardSizeAtLeastCondition), "DiscardSizeAtLeast")] +// Tile (§6.3) +[PolyType(typeof(TileAffinityMatchesCondition), "TileAffinityMatches")] +[PolyType(typeof(TileIsOccupiedCondition), "TileIsOccupied")] +[PolyType(typeof(TileIsUnoccupiedCondition), "TileIsUnoccupied")] +// Turn/timing (§6.4) +[PolyType(typeof(IsOwnTurnCondition), "IsOwnTurn")] +[PolyType(typeof(IsOpponentTurnCondition), "IsOpponentTurn")] +[PolyType(typeof(IsAllyTurnCondition), "IsAllyTurn")] +[PolyType(typeof(IsActivePlayerTurnCondition), "IsActivePlayerTurn")] +// Battlefield (§6.5) +[PolyType(typeof(UnitCountOnBattlefieldCondition), "UnitCountOnBattlefield")] +[PolyType(typeof(CardInZoneCondition), "CardInZone")] +public abstract class Condition +{ + /// + /// Which entity to evaluate this condition against. + /// "Self" (default) = the source unit / ability owner. + /// "Target" = the current action's resolved target. + /// + public string Subject { get; set; } = "Self"; +} + +// ── Composite conditions ────────────────────────────────────────────────────── + +public sealed class AndCondition : Condition { public Condition[] Conditions { get; set; } = []; } +public sealed class OrCondition : Condition { public Condition[] Conditions { get; set; } = []; } +public sealed class XorCondition : Condition { public Condition[] Conditions { get; set; } = []; } + +// ── Unit conditions (§6.1) ──────────────────────────────────────────────────── + +public sealed class HealthBelowCondition : Condition { public int N { get; set; } } +public sealed class HealthAboveCondition : Condition { public int N { get; set; } } +public sealed class DefenseIsCondition : Condition { public int N { get; set; } } +public sealed class HasGenusCondition : Condition { public string Tag { get; set; } = string.Empty; } +/// Unit must have an ability with the given reference name. +public sealed class HasAbilityCondition : Condition { public string AbilityRef { get; set; } = string.Empty; } +public sealed class IsOnTileWithAffinityCondition : Condition { public Affinity Affinity { get; set; } } + +public sealed class IsAdjacentToCondition : Condition +{ + public string UnitType { get; set; } = "Unit"; + public string Ownership { get; set; } = "Any"; +} + +public sealed class WithinRangeOfCondition : Condition +{ + /// Reference to another action's target, e.g. "Action1.Target". + public string Target { get; set; } = string.Empty; + public int Min { get; set; } = 1; + public int Max { get; set; } = 1; +} + +public sealed class MovementTypeIsCondition : Condition { public MovementType MovementType { get; set; } } + +// ── Player conditions (§6.2) ────────────────────────────────────────────────── + +public sealed class SPAtLeastCondition : Condition { public int N { get; set; } } +public sealed class SPAtMostCondition : Condition { public int N { get; set; } } +public sealed class STAtLeastCondition : Condition { public int N { get; set; } } +public sealed class STAtMostCondition : Condition { public int N { get; set; } } +public sealed class HandSizeAtLeastCondition : Condition { public int N { get; set; } } +public sealed class HandSizeAtMostCondition : Condition { public int N { get; set; } } +public sealed class DeckSizeAtLeastCondition : Condition { public int N { get; set; } } +public sealed class DiscardSizeAtLeastCondition : Condition { public int N { get; set; } } + +// ── Tile conditions (§6.3) ──────────────────────────────────────────────────── + +public sealed class TileAffinityMatchesCondition : Condition { public Affinity Affinity { get; set; } } +public sealed class TileIsOccupiedCondition : Condition { public string? UnitType { get; set; } } +public sealed class TileIsUnoccupiedCondition : Condition { } + +// ── Turn/timing conditions (§6.4) ──────────────────────────────────────────── + +public sealed class IsOwnTurnCondition : Condition { } +public sealed class IsOpponentTurnCondition : Condition { } +public sealed class IsAllyTurnCondition : Condition { } +public sealed class IsActivePlayerTurnCondition : Condition { public string Ownership { get; set; } = "Owner"; } + +// ── Battlefield conditions (§6.5) ───────────────────────────────────────────── + +public enum Comparator { Equal, NotEqual, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual } + +public sealed class UnitCountOnBattlefieldCondition : Condition +{ + public string Ownership { get; set; } = "Enemy"; + public string UnitType { get; set; } = "Unit"; + public Comparator Comparator { get; set; } = Comparator.GreaterThanOrEqual; + public int N { get; set; } +} + +public sealed class CardInZoneCondition : Condition +{ + /// Reference to a specific card instance ID or definition ID. + public string CardRef { get; set; } = string.Empty; + public string Zone { get; set; } = "Hand"; +} diff --git a/reference/SOR.Game/Abilities/Models/DurationModel.cs b/reference/SOR.Game/Abilities/Models/DurationModel.cs new file mode 100644 index 0000000..0d7db9b --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/DurationModel.cs @@ -0,0 +1,47 @@ +namespace SOR.Game.Abilities.Models; + +/// How long an applied effect persists. +public enum DurationType +{ + /// One-time change; no ongoing tracking required. + Instant, + /// Expires at the end of the current active player's turn. + UntilEndOfTurn, + /// Expires at the start of the ability-owner's next turn. + UntilStartOfOwnerTurn, + /// Expires at the start of the source unit's owner's next turn. + UntilStartOfSourceOwnerTurn, + /// Expires after exactly N turns have elapsed. + ForNTurns, + /// Active while a condition evaluates to true; expires when it becomes false. + WhileCondition, + /// Active while the ability's source unit is on the battlefield; revoked on leave/death. + WhileSourceOnBattlefield, + /// Persists for the entire match; never expires. + PermanentInMatch, +} + +/// +/// Duration descriptor attached to every Action in the ability model. +/// Governs how long the action's effects remain active. +/// +public sealed class DurationModel +{ + public DurationType Type { get; set; } = DurationType.Instant; + + /// Turn count for . + public int? N { get; set; } + + /// Condition evaluated each turn for . + public Condition? Condition { get; set; } + + /// + /// Optional ownership scope for timing anchors. + /// E.g., "Owner" scopes "UntilEndOfTurn" to the ability-owner's turn end specifically. + /// + public string? PlayerScope { get; set; } + + public static DurationModel Instant => new() { Type = DurationType.Instant }; + public static DurationModel Permanent => new() { Type = DurationType.PermanentInMatch }; + public static DurationModel EndOfTurn => new() { Type = DurationType.UntilEndOfTurn }; +} diff --git a/reference/SOR.Game/Abilities/Models/Effects.cs b/reference/SOR.Game/Abilities/Models/Effects.cs new file mode 100644 index 0000000..2f3c7a1 --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/Effects.cs @@ -0,0 +1,252 @@ +namespace SOR.Game.Abilities.Models; + +using System.Text.Json.Serialization; +using SOR.Database.Enums; + +// ── Effect base ─────────────────────────────────────────────────────────────── + +/// +/// The atomic unit of game-state mutation delivered to a resolved target. +/// All effects share a DurationModel (from their containing Action). +/// +// §5.1 Stat modification +[PolyType(typeof(ModifyHealthEffect), "ModifyHealth")] +[PolyType(typeof(ModifyDefenseEffect), "ModifyDefense")] +[PolyType(typeof(ModifyDamageEffect), "ModifyDamage")] +[PolyType(typeof(ModifyMPEffect), "ModifyMP")] +[PolyType(typeof(SetMovementTypeEffect), "SetMovementType")] +[PolyType(typeof(SetAttackRangeEffect), "SetAttackRange")] +[PolyType(typeof(ModifyMinAttackRangeEffect), "ModifyMinAttackRange")] +[PolyType(typeof(ModifyMaxAttackRangeEffect), "ModifyMaxAttackRange")] +[PolyType(typeof(ModifyCostEffect), "ModifyCost")] +[PolyType(typeof(SetAffinityEffect), "SetAffinity")] +[PolyType(typeof(GrantAdditionalAttackEffect), "GrantAdditionalAttack")] +[PolyType(typeof(SetStatModMultiplierEffect), "SetStatModMultiplier")] +// §5.2 Flag modification — unit +[PolyType(typeof(SetCanMoveEffect), "SetCanMove")] +[PolyType(typeof(SetCanAttackEffect), "SetCanAttack")] +[PolyType(typeof(SetCanDefendEffect), "SetCanDefend")] +[PolyType(typeof(SetCanBeAttackedEffect), "SetCanBeAttacked")] +[PolyType(typeof(SetCanBeBlockedEffect), "SetCanBeBlocked")] +[PolyType(typeof(SetCanBeObstructedEffect), "SetCanBeObstructed")] +[PolyType(typeof(SetCanUseAbilityEffect), "SetCanUseAbility")] +[PolyType(typeof(SetCanBeSacrificedEffect), "SetCanBeSacrificed")] +// §5.2 Flag modification — player +[PolyType(typeof(SetCanDrawCardsEffect), "SetCanDrawCards")] +[PolyType(typeof(SetAccumulatesSPEffect), "SetAccumulatesSP")] +[PolyType(typeof(SetCanChannelSpiritEffect), "SetCanChannelSpirit")] +[PolyType(typeof(SetCanSacrificeSpiritEffect), "SetCanSacrificeSpirit")] +[PolyType(typeof(SetCanAscendArchSpiritEffect), "SetCanAscendArchSpirit")] +[PolyType(typeof(SetCanTransitionArchSpiritEffect), "SetCanTransitionArchSpirit")] +[PolyType(typeof(SetCanChannelRepentanceEffect), "SetCanChannelRepentance")] +[PolyType(typeof(SetCanChannelInstinctEffect), "SetCanChannelInstinct")] +[PolyType(typeof(SetCanChannelRuinEffect), "SetCanChannelRuin")] +[PolyType(typeof(SetCanChannelTerramorphaMonoEffect), "SetCanChannelTerramorphaMono")] +[PolyType(typeof(SetCanChannelTerramorphaDiEffect), "SetCanChannelTerramorphaDi")] +[PolyType(typeof(SetCanChannelTerramorphaTriEffect), "SetCanChannelTerramorphaTri")] +// §5.3 Ability modification +[PolyType(typeof(AddAbilityEffect), "AddAbility")] +[PolyType(typeof(RemoveAbilityEffect), "RemoveAbility")] +[PolyType(typeof(EnableAbilityEffect), "EnableAbility")] +[PolyType(typeof(DisableAbilityEffect),"DisableAbility")] +// §5.4 Genus modification +[PolyType(typeof(AddGenusEffect), "AddGenus")] +[PolyType(typeof(RemoveGenusEffect), "RemoveGenus")] +// §5.5 Player resource modification +[PolyType(typeof(ModifySPEffect), "ModifySP")] +[PolyType(typeof(ModifySPAccumulationEffect), "ModifySPAccumulation")] +[PolyType(typeof(ModifySTEffect), "ModifyST")] +[PolyType(typeof(ModifyCardsDrawnPerTurnEffect), "ModifyCardsDrawnPerTurn")] +// §5.6 Tile modification +[PolyType(typeof(SetBaseAffinity1Effect), "SetBaseAffinity1")] +[PolyType(typeof(SetBaseAffinity2Effect), "SetBaseAffinity2")] +[PolyType(typeof(PushAffinityEffect), "PushAffinity")] +[PolyType(typeof(PushFinalAffinityEffect), "PushFinalAffinity")] +// §5.7 Zone / card operations +[PolyType(typeof(DrawCardsEffect), "DrawCards")] +[PolyType(typeof(DiscardCardsEffect), "DiscardCards")] +[PolyType(typeof(ReturnToHandEffect), "ReturnToHand")] +[PolyType(typeof(ReturnToDeckEffect), "ReturnToDeck")] +[PolyType(typeof(ReturnToBattlefieldEffect), "ReturnToBattlefield")] +[PolyType(typeof(SendToDiscardEffect), "SendToDiscard")] +[PolyType(typeof(SearchDeckEffect), "SearchDeck")] +[PolyType(typeof(ShuffleDeckEffect), "ShuffleDeck")] +[PolyType(typeof(RevealCardsEffect), "RevealCards")] +[PolyType(typeof(PlaceOnDeckEffect), "PlaceOnDeck")] +[PolyType(typeof(ChannelCardEffect), "ChannelCard")] +// §5.8 Combat / damage +[PolyType(typeof(DealDamageEffect), "DealDamage")] +[PolyType(typeof(HealEffect), "Heal")] +[PolyType(typeof(DealDamageToSelfEffect), "DealDamageToSelf")] +[PolyType(typeof(DOTEffect), "DOT")] +[PolyType(typeof(HOTEffect), "HOT")] +// §5.9 Displacement +[PolyType(typeof(PushUnitEffect), "PushUnit")] +[PolyType(typeof(PullUnitEffect), "PullUnit")] +[PolyType(typeof(DisplaceUnitEffect), "DisplaceUnit")] +// §5.10 Control +[PolyType(typeof(TakeControlEffect), "TakeControl")] +[PolyType(typeof(GrantMovementControlEffect), "GrantMovementControl")] +[PolyType(typeof(SetFixedSacrificeReturnEffect),"SetFixedSacrificeReturn")] +// §5.11 Token +[PolyType(typeof(SummonTokenEffect), "SummonToken")] +// §5.12 Deferred +[PolyType(typeof(ApplyOnEventEffect), "ApplyOnEvent")] +public abstract class Effect { } + +// ── §5.1 Stat modification ──────────────────────────────────────────────────── + +public enum StatTarget { Current, Max } + +public sealed class ModifyHealthEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } +public sealed class ModifyDefenseEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } +public sealed class ModifyDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyMPEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } + +public sealed class SetMovementTypeEffect : Effect { public MovementType MovementType { get; set; } } +public sealed class SetAttackRangeEffect : Effect { public int Min { get; set; } public int Max { get; set; } } +public sealed class ModifyMinAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyMaxAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyCostEffect : Effect { public int? Sp { get; set; } public int? St { get; set; } } +public sealed class SetAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class GrantAdditionalAttackEffect : Effect { public int N { get; set; } = 1; } +public sealed class SetStatModMultiplierEffect : Effect { public string Stat { get; set; } = string.Empty; public double Multiplier { get; set; } = 1.0; } + +// ── §5.2 Flag modification — unit ───────────────────────────────────────────── + +public sealed class SetCanMoveEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanAttackEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanDefendEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeAttackedEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeBlockedEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeObstructedEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanUseAbilityEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeSacrificedEffect : Effect { public bool Value { get; set; } } + +// ── §5.2 Flag modification — player ─────────────────────────────────────────── + +public sealed class SetCanDrawCardsEffect : Effect { public bool Value { get; set; } } +public sealed class SetAccumulatesSPEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanSacrificeSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanAscendArchSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanTransitionArchSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelRepentanceEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelInstinctEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelRuinEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelTerramorphaMonoEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelTerramorphaDiEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelTerramorphaTriEffect : Effect { public bool Value { get; set; } } + +// ── §5.3 Ability modification ───────────────────────────────────────────────── + +public sealed class AddAbilityEffect : Effect { public AbilityDefinition AbilityDef { get; set; } = new(); } +/// AbilityRef is the ability name (matches AbilityDefinition.Name). +public sealed class RemoveAbilityEffect : Effect { public string AbilityRef { get; set; } = string.Empty; } +public sealed class EnableAbilityEffect : Effect { public string AbilityRef { get; set; } = string.Empty; } +public sealed class DisableAbilityEffect: Effect { public string AbilityRef { get; set; } = string.Empty; } + +// ── §5.4 Genus modification ─────────────────────────────────────────────────── + +public sealed class AddGenusEffect : Effect { public string Tag { get; set; } = string.Empty; } +public sealed class RemoveGenusEffect : Effect { public string Tag { get; set; } = string.Empty; } + +// ── §5.5 Player resource modification ───────────────────────────────────────── + +public sealed class ModifySPEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifySPAccumulationEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifySTEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyCardsDrawnPerTurnEffect: Effect { public ValueExpr Amount { get; set; } = new(); } + +// ── §5.6 Tile modification ──────────────────────────────────────────────────── + +public sealed class SetBaseAffinity1Effect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class SetBaseAffinity2Effect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class PushAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class PushFinalAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } + +// ── §5.7 Zone / card operations ─────────────────────────────────────────────── + +public sealed class DrawCardsEffect : Effect { public int N { get; set; } = 1; public string Player { get; set; } = "Owner"; } +public sealed class DiscardCardsEffect : Effect { public int N { get; set; } = 1; public string Player { get; set; } = "Owner"; public Filter[]? Filters { get; set; } } +public sealed class ReturnToHandEffect : Effect { } // target is the card (from action target) +public sealed class ReturnToDeckEffect : Effect { public string Position { get; set; } = "top"; } // top | bottom | random +public sealed class ReturnToBattlefieldEffect : Effect { public string? Controller { get; set; } public Filter[]? TileFilter { get; set; } } +public sealed class SendToDiscardEffect: Effect { } +public sealed class SearchDeckEffect : Effect +{ + public Filter[]? Filters { get; set; } + public int Count { get; set; } = 1; + /// Action applied to each found card (SearchResult references current card). + public Action? ThenAction { get; set; } +} +public sealed class ShuffleDeckEffect : Effect { public string Player { get; set; } = "Owner"; } +public sealed class RevealCardsEffect : Effect { public int N { get; set; } = 1; public string ToOwnership { get; set; } = "Any"; } +public sealed class PlaceOnDeckEffect : Effect { public string Position { get; set; } = "top"; } +public sealed class ChannelCardEffect : Effect +{ + public bool PayCost { get; set; } = true; + public double? CostMultiplier { get; set; } +} + +// ── §5.8 Combat / damage ────────────────────────────────────────────────────── + +public sealed class DealDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); public bool BypassDefense { get; set; } } +public sealed class HealEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class DealDamageToSelfEffect : Effect { public ValueExpr Amount { get; set; } = new(); public bool BypassDefense { get; set; } } +public sealed class DOTEffect : Effect { public ValueExpr Amount { get; set; } = new(); public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; public bool BypassDefense { get; set; } } +public sealed class HOTEffect : Effect { public ValueExpr Amount { get; set; } = new(); public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; } + +// ── §5.9 Displacement ───────────────────────────────────────────────────────── + +public sealed class PushUnitEffect : Effect +{ + public int Tiles { get; set; } = 1; + /// + /// Direct HP damage dealt to the pushed unit if it cannot complete the full push + /// (blocked by a boundary or another unit). 0 = no knockback damage. + /// + public int BlockedDamage { get; set; } = 0; +} + +public sealed class PullUnitEffect : Effect +{ + public int Tiles { get; set; } = 1; + /// + /// Direct HP damage dealt to the pulled unit if it cannot complete the full pull + /// (blocked by a boundary or another unit). 0 = no knockback damage. + /// + public int BlockedDamage { get; set; } = 0; +} +public sealed class DisplaceUnitEffect : Effect { public int Tiles { get; set; } = 1; public string Direction { get; set; } = "North"; } + +// ── §5.10 Control effects ───────────────────────────────────────────────────── + +public sealed class TakeControlEffect : Effect { public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; } +public sealed class GrantMovementControlEffect : Effect { public int N { get; set; } = 1; } +/// Overrides the sacrifice formula: controller receives exactly StAmount ST instead. +public sealed class SetFixedSacrificeReturnEffect : Effect { public int StAmount { get; set; } } + +// ── §5.11 Token summoning ───────────────────────────────────────────────────── + +/// +/// Summons a SpiritToken onto a player-selected tile meeting the filter. +/// TokenDefJson is a JSONB blob matching a mini-CardDefinition for the token. +/// +public sealed class SummonTokenEffect : Effect +{ + public string TokenDefJson { get; set; } = "{}"; + public Filter[]? TileFilter { get; set; } +} + +// ── §5.12 Deferred effects ──────────────────────────────────────────────────── + +/// +/// Schedules effects to fire once the next time the specified trigger event occurs. +/// Consumed after firing. Cancelled if source leaves battlefield before event fires. +/// +public sealed class ApplyOnEventEffect : Effect +{ + public TriggerEvent Trigger { get; set; } = null!; + public Effect[] Effects { get; set; } = []; +} diff --git a/reference/SOR.Game/Abilities/Models/Filters.cs b/reference/SOR.Game/Abilities/Models/Filters.cs new file mode 100644 index 0000000..ecb1581 --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/Filters.cs @@ -0,0 +1,134 @@ +namespace SOR.Game.Abilities.Models; + +using SOR.Database.Enums; + +// ── Filter base ─────────────────────────────────────────────────────────────── + +/// +/// Narrows which entities a TargetSelector or condition matches. +/// Unit/card filters apply to spirits and ArchSpirits; tile filters to board tiles. +/// +// ── Unit / card filters ────────────────────────────────────────────────────── +[PolyType(typeof(GenusContainsFilter), "GenusContains")] +[PolyType(typeof(AffinityMatchesFilter), "AffinityMatches")] +[PolyType(typeof(HealthBelowFilter), "HealthBelow")] +[PolyType(typeof(HealthAboveFilter), "HealthAbove")] +[PolyType(typeof(DamageRangeFilter), "DamageRange")] +[PolyType(typeof(DefenseRangeFilter), "DefenseRange")] +[PolyType(typeof(MPRangeFilter), "MPRange")] +[PolyType(typeof(HasFlagFilter), "HasFlag")] +[PolyType(typeof(TierIsFilter), "TierIs")] +[PolyType(typeof(IsAdjacentToSourceFilter), "IsAdjacentToSource")] +[PolyType(typeof(CardTypeIsFilter), "CardTypeIs")] +[PolyType(typeof(CardSPCostRangeFilter), "CardSPCostRange")] +[PolyType(typeof(CardSTCostRangeFilter), "CardSTCostRange")] +[PolyType(typeof(WithinRangeFilter), "WithinRange")] +[PolyType(typeof(IsSelfFilter), "IsSelf")] +[PolyType(typeof(IsExactSelfFilter), "IsExactSelf")] +// ── Tile filters ───────────────────────────────────────────────────────────── +[PolyType(typeof(TileAffinityMatchesFilter), "TileAffinityMatches")] +[PolyType(typeof(TileAffinityMatchesFilter), "TileAffinityMatchesFilter")] // legacy alias (typo in admin v1) +[PolyType(typeof(TileIsOccupiedFilter), "TileIsOccupied")] +[PolyType(typeof(TileIsUnoccupiedFilter), "TileIsUnoccupied")] +[PolyType(typeof(TileWithinRangeFilter), "TileWithinRange")] +[PolyType(typeof(TileIsAdjacentToUnitFilter), "TileIsAdjacentToUnit")] +[PolyType(typeof(TileIsOnPlayerSideFilter), "TileIsOnPlayerSide")] +[PolyType(typeof(TileIsInArchSpiritChannelRangeFilter), "TileIsInArchSpiritChannelRange")] +public abstract class Filter { } + +// ── Unit / card filter implementations ─────────────────────────────────────── + +/// Unit's genus array must contain the given tag. +public sealed class GenusContainsFilter : Filter +{ + public string Tag { get; set; } = string.Empty; +} + +/// Unit's affinity must match. +public sealed class AffinityMatchesFilter : Filter +{ + public Affinity Affinity { get; set; } +} + +public sealed class HealthBelowFilter : Filter { public int N { get; set; } } +public sealed class HealthAboveFilter : Filter { public int N { get; set; } } + +public sealed class DamageRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } +public sealed class DefenseRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } +public sealed class MPRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +/// +/// Unit must have the specified boolean flag set to true. +/// Flag names: CanAttack, CanMove, CanDefend, CanBeAttacked, CanBeBlocked, CanBeSacrificed, etc. +/// +public sealed class HasFlagFilter : Filter +{ + public string Flag { get; set; } = string.Empty; +} + +/// ArchSpirit must be at the specified tier number. +public sealed class TierIsFilter : Filter +{ + public int Tier { get; set; } +} + +/// Target unit must be orthogonally adjacent to the ability's source unit. +public sealed class IsAdjacentToSourceFilter : Filter { } + +public sealed class CardTypeIsFilter : Filter +{ + public CardType CardType { get; set; } +} + +public sealed class CardSPCostRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } +public sealed class CardSTCostRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +/// Unit must be within Min..Max Manhattan distance of the ability's source unit. +public sealed class WithinRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +/// +/// Matches any unit that shares the same card definition as the ability source. +/// Use for abilities that affect "all copies of this card type". +/// +public sealed class IsSelfFilter : Filter { } + +/// +/// Matches only the exact unit instance that owns this ability (by InstanceId). +/// Use this instead of IsSelf when only the specific unit on the battlefield should be affected. +/// +public sealed class IsExactSelfFilter : Filter { } + +// ── Tile filter implementations ─────────────────────────────────────────────── + +public sealed class TileAffinityMatchesFilter : Filter +{ + public Affinity Affinity { get; set; } +} + +/// Tile must be occupied; optionally restrict to a specific unit type. +public sealed class TileIsOccupiedFilter : Filter +{ + public string? UnitType { get; set; } // "Spirit" | "ArchSpirit" | "SpiritToken" | null (any) +} + +public sealed class TileIsUnoccupiedFilter : Filter { } + +public sealed class TileWithinRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +public sealed class TileIsAdjacentToUnitFilter : Filter +{ + public string Ownership { get; set; } = "Any"; // TargetOwnership as string + public Filter? UnitFilter { get; set; } +} + +/// Tile falls within the starting placement side of the specified player ownership group. +public sealed class TileIsOnPlayerSideFilter : Filter +{ + public string Ownership { get; set; } = "Owner"; +} + +/// Tile is within the active ArchSpirit's channeling range for the specified player. +public sealed class TileIsInArchSpiritChannelRangeFilter : Filter +{ + public string Ownership { get; set; } = "Owner"; +} diff --git a/reference/SOR.Game/Abilities/Models/PolyTypeAttribute.cs b/reference/SOR.Game/Abilities/Models/PolyTypeAttribute.cs new file mode 100644 index 0000000..eaa33a6 --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/PolyTypeAttribute.cs @@ -0,0 +1,16 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Maps a type-discriminator string to a concrete derived type for the custom +/// PolymorphicAbilityConverter<T>. This is intentionally NOT a +/// — using +/// that attribute (even without [JsonPolymorphic]) causes System.Text.Json to +/// activate its built-in PolymorphicTypeResolver, which conflicts with our +/// custom converter. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] +internal sealed class PolyTypeAttribute(Type derivedType, string discriminator) : Attribute +{ + public Type DerivedType { get; } = derivedType; + public string Discriminator { get; } = discriminator; +} diff --git a/reference/SOR.Game/Abilities/Models/Triggers.cs b/reference/SOR.Game/Abilities/Models/Triggers.cs new file mode 100644 index 0000000..e4b585c --- /dev/null +++ b/reference/SOR.Game/Abilities/Models/Triggers.cs @@ -0,0 +1,148 @@ +namespace SOR.Game.Abilities.Models; + + +// ── TriggerEvent base ───────────────────────────────────────────────────────── + +/// +/// Specifies the game event that causes a Triggered ability to fire. +/// Every event supports an optional ownership scope applied to the acting entity +/// and most accept an optional filter for further narrowing. +/// +// §8.1 Turn phase +[PolyType(typeof(OnTurnStartTrigger), "OnTurnStart")] +[PolyType(typeof(OnTurnEndTrigger), "OnTurnEnd")] +// §8.2 Channeling +[PolyType(typeof(OnChanneledTrigger), "OnChanneled")] +// §8.3 ArchSpirit tier actions +[PolyType(typeof(OnAscendTrigger), "OnAscend")] +[PolyType(typeof(OnTransitionTrigger), "OnTransition")] +// §8.4 Unit actions +[PolyType(typeof(OnUnitMoveTrigger), "OnUnitMove")] +[PolyType(typeof(OnUnitAttackTrigger), "OnUnitAttack")] +[PolyType(typeof(OnUnitAbilityActivatedTrigger), "OnUnitAbilityActivated")] +[PolyType(typeof(OnUnitMPSpentTrigger), "OnUnitMPSpent")] +// §8.5 Damage and healing +[PolyType(typeof(OnDamageDealtTrigger), "OnDamageDealt")] +[PolyType(typeof(OnDamagePreventedTrigger), "OnDamagePrevented")] +[PolyType(typeof(OnHealedTrigger), "OnHealed")] +// §8.6 Unit lifecycle +[PolyType(typeof(OnUnitEnterBattlefieldTrigger), "OnUnitEnterBattlefield")] +[PolyType(typeof(OnUnitLeaveBattlefieldTrigger), "OnUnitLeaveBattlefield")] +[PolyType(typeof(OnUnitDeathTrigger), "OnUnitDeath")] +[PolyType(typeof(OnUnitSentToDiscardTrigger), "OnUnitSentToDiscard")] +[PolyType(typeof(OnSpiritSacrificedTrigger), "OnSpiritSacrificed")] +[PolyType(typeof(OnTokenSummonedTrigger), "OnTokenSummoned")] +// §8.7 Unit state changes +[PolyType(typeof(OnStatModifiedTrigger), "OnStatModified")] +[PolyType(typeof(OnAbilityAddedTrigger), "OnAbilityAdded")] +[PolyType(typeof(OnAbilityRemovedTrigger), "OnAbilityRemoved")] +[PolyType(typeof(OnGenusChangedTrigger), "OnGenusChanged")] +// §8.8 Ruin +[PolyType(typeof(OnRuinActivationTrigger), "OnRuinActivation")] +[PolyType(typeof(OnUnitOccupyRuinTrigger), "OnUnitOccupyRuin")] +// §8.9 Tile +[PolyType(typeof(OnTileAffinityChangedTrigger), "OnTileAffinityChanged")] +// §8.10 Player resources +[PolyType(typeof(OnSPGainedTrigger), "OnSPGained")] +[PolyType(typeof(OnSPSpentTrigger), "OnSPSpent")] +[PolyType(typeof(OnSTGainedTrigger), "OnSTGained")] +[PolyType(typeof(OnSTSpentTrigger), "OnSTSpent")] +// §8.11 Card zone events +[PolyType(typeof(OnCardDrawnTrigger), "OnCardDrawn")] +[PolyType(typeof(OnCardDiscardedTrigger), "OnCardDiscarded")] +[PolyType(typeof(OnCardReturnedToHandTrigger), "OnCardReturnedToHand")] +[PolyType(typeof(OnCardReturnedToDeckTrigger), "OnCardReturnedToDeck")] +[PolyType(typeof(OnDeckShuffledTrigger), "OnDeckShuffled")] +[PolyType(typeof(OnCardsRevealedTrigger), "OnCardsRevealed")] +// §8.12 Effect and targeting lifecycle +[PolyType(typeof(OnTargetedByAbilityTrigger), "OnTargetedByAbility")] +[PolyType(typeof(OnEffectAppliedTrigger), "OnEffectApplied")] +[PolyType(typeof(OnEnterAuraRangeTrigger), "OnEnterAuraRange")] +[PolyType(typeof(OnLeaveAuraRangeTrigger), "OnLeaveAuraRange")] +public abstract class TriggerEvent { } + +// ── §8.1 Turn phase ─────────────────────────────────────────────────────────── + +public sealed class OnTurnStartTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; } +public sealed class OnTurnEndTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; } + +// ── §8.2 Channeling ─────────────────────────────────────────────────────────── + +public sealed class OnChanneledTrigger : TriggerEvent +{ + public string CardType { get; set; } = "Spirit"; + public string Ownership { get; set; } = "Owner"; + public Filter? Filter { get; set; } +} + +// ── §8.3 ArchSpirit tier actions ────────────────────────────────────────────── + +public sealed class OnAscendTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; } +public sealed class OnTransitionTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; } + +// ── §8.4 Unit actions ───────────────────────────────────────────────────────── + +public sealed class OnUnitMoveTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnUnitAttackTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnUnitAbilityActivatedTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnUnitMPSpentTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } public int? Amount { get; set; } } + +// ── §8.5 Damage and healing ─────────────────────────────────────────────────── + +public sealed class OnDamageDealtTrigger : TriggerEvent +{ + public string SourceOwnership { get; set; } = "Any"; + public string TargetOwnership { get; set; } = "Any"; + public string DamageType { get; set; } = "Any"; // "HP" | "Defense" | "Any" + public int? Amount { get; set; } +} +public sealed class OnDamagePreventedTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnHealedTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } public int? Amount { get; set; } } + +// ── §8.6 Unit lifecycle ─────────────────────────────────────────────────────── + +public sealed class OnUnitEnterBattlefieldTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnUnitLeaveBattlefieldTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnUnitDeathTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnUnitSentToDiscardTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } public string? CausedBy { get; set; } } +public sealed class OnSpiritSacrificedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnTokenSummonedTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } + +// ── §8.7 Unit state changes ─────────────────────────────────────────────────── + +public sealed class OnStatModifiedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } public string? Stat { get; set; } } +public sealed class OnAbilityAddedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnAbilityRemovedTrigger: TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnGenusChangedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } + +// ── §8.8 Ruin ──────────────────────────────────────────────────────────────── + +public sealed class OnRuinActivationTrigger : TriggerEvent { public string RuinOwnership { get; set; } = "Any"; public string? OccupantOwnership { get; set; } } +public sealed class OnUnitOccupyRuinTrigger : TriggerEvent { public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } + +// ── §8.9 Tile ──────────────────────────────────────────────────────────────── + +public sealed class OnTileAffinityChangedTrigger : TriggerEvent { public Filter? Filter { get; set; } } + +// ── §8.10 Player resources ──────────────────────────────────────────────────── + +public sealed class OnSPGainedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } +public sealed class OnSPSpentTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } +public sealed class OnSTGainedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } +public sealed class OnSTSpentTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } + +// ── §8.11 Card zone events ──────────────────────────────────────────────────── + +public sealed class OnCardDrawnTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnCardDiscardedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } public string? Cause { get; set; } } +public sealed class OnCardReturnedToHandTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnCardReturnedToDeckTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnDeckShuffledTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; } +public sealed class OnCardsRevealedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } + +// ── §8.12 Effect and targeting lifecycle ────────────────────────────────────── + +public sealed class OnTargetedByAbilityTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Owner"; public string SourceOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnEffectAppliedTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Owner"; public string SourceOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnEnterAuraRangeTrigger : TriggerEvent { public string AuraOwnership { get; set; } = "Owner"; public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnLeaveAuraRangeTrigger : TriggerEvent { public string AuraOwnership { get; set; } = "Owner"; public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } }