#pragma warning disable CS0618 // AbilitySystem is the authorized reader of obsolete Actions/Cost fields for backwards-compat migration 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(), }, }; // Runtime limiter for Triggered abilities: (source instance, ability key, turn) -> count private static readonly Dictionary<(string SourceInstanceId, string AbilityKey, int Turn), int> _triggerCountsPerTurn = new(); // Per-game trigger limiter: (session+source instance, ability key) -> count; never resets mid-game private static readonly Dictionary<(string SessionAndSource, string AbilityKey), int> _triggerCountsPerGame = new(); // Transient prevention markers. private static readonly Dictionary _preventNextDamageByUnit = new(); private static readonly HashSet _preventDeathUnits = new(); // Top-level ability/action sequence depth for UntilEndOfSequence cleanup. private static int _sequenceDepth = 0; // ── JSON options (public factory for tooling) ───────────────────────────── /// Returns the same JsonSerializerOptions used by the ability engine. Used by SOR.Tools. public static JsonSerializerOptions CreateJsonOptions() => new() { PropertyNameCaseInsensitive = true, Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter(), 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"); // Pre-validate client tile targets against effect-level TileFilters BEFORE // incrementing the use count or paying any costs, so a bad pick wastes nothing. PreValidateClientTileTargets(def, clientTargets, ctx); source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex, def.Range, def.Duration); // GetEffectiveActions returns null when it emitted PendingActionGroupPick (OR/XOR, interactive). if (effectiveActions is null) return state; if (def.CostGroup is { } cg) { bool paused = PayCostGroup(cg, ctx, abilityIndex, effectiveActions, def.Range, def.Duration); if (paused) return state; } else if (def.Cost is { Length: > 0 }) { bool paused = PayCosts(def.Cost, ctx, abilityIndex, effectiveActions, def.Range, def.Duration); if (paused) return state; // waiting for client cost pick } ExecuteActions(effectiveActions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration); return state; } // ── Triggered ability firing ─────────────────────────────────────────────── /// /// Resolve the AbilitiesJson active ability list on a non-unit card (Repentance, Instinct) /// 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) { var activeDefs = ParseAbilities(card.AbilitiesJson) .Where(d => d.Type == AbilityType.Active) .ToList(); foreach (var def in activeDefs) { var ctx = new AbilityContext { State = state, ActorId = actorId, Source = card }; if (!ValidateSourceActivationConditions(def, ctx, card)) continue; var cardActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration); if (cardActions is null) continue; // paused for interactive ActionGroup pick ExecuteActions(cardActions, 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; } /// /// Checks client-supplied tile targets against any effect-level TileFilter constraints /// (e.g. ). Called before the use-count is /// incremented and before costs are paid, so a rejected pick costs the player nothing. /// private static void PreValidateClientTileTargets( AbilityDefinition def, IReadOnlyList? clientTargets, AbilityContext ctx) { if (clientTargets is null || ctx.State.Board is null) return; // Iterate the flat action list in the top-level AND group (the common case). // OR/XOR groups with pending interactive picks are handled after the pick resolves // and never reach this path with client-provided tile coords. var actions = def.ActionGroup?.Actions ?? def.Actions ?? []; for (int ai = 0; ai < actions.Length; ai++) { var action = actions[ai]; if (action.Target.Type != TargetType.Tile) continue; foreach (var effect in action.Effects) { if (effect is not SummonTokenEffect ste || ste.TileFilter is not { Length: > 0 }) continue; var ct = clientTargets.FirstOrDefault(t => t.ActionIndex == ai && t.Coord is not null); if (ct is null) continue; var coord = new Coord(ct.Coord!.X, ct.Coord!.Y); var tile = ctx.State.Board.GetTile(coord); if (tile is null || !TileMatchesFilters(ste.TileFilter, tile, ctx)) throw new GameException("INVALID_TILE"); } } } /// /// Scans every battlefield unit (and, when SourceZoneGate is set, hand/discard/deck cards) /// 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) { // Build the set of cards to scan for triggered abilities. // Always include battlefield units. Cards with SourceZoneGate including // Hand/Discard/Deck are scanned from those zones too. var scanTargets = new List<(CardInstance Card, string Zone)>(); foreach (var fc in player.Field.OfType()) scanTargets.Add((fc, "Battlefield")); foreach (var c in player.Hand) scanTargets.Add((c, "Hand")); foreach (var c in player.Discard) scanTargets.Add((c, "Discard")); foreach (var c in player.Deck) scanTargets.Add((c, "Deck")); foreach (var (card, zone) in scanTargets) { // SetCanUseAbility(false) suppresses triggered ability firing. if (card is FieldCard fc2 && !fc2.CanUseAbility) continue; var abilities = ParseAbilities(card.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; // ── SourceZoneGate ──────────────────────────────────────── // When a gate is configured, only fire when the card is in one of the // specified zones. When no gate is configured, apply the legacy rule: // only battlefield cards fire (skip non-battlefield cards). if (def.SourceZoneGate is { Length: > 0 }) { if (!def.SourceZoneGate.Contains(zone, StringComparer.OrdinalIgnoreCase)) continue; } else { // No gate → legacy: only battlefield cards trigger. if (zone != "Battlefield") continue; } if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId, card is FieldCard fc3 ? fc3 : null)) continue; // 6-D: Prevent double-firing the source Ruin's own OnRuinActivation abilities. // FireRuinAbilities already executed one chosen ability directly; the subsequent // FireTrigger call is only for observer cards. Skip the source Ruin itself. if (occurrence.Kind == TriggerEventKind.RuinActivation && def.TriggerEvent is OnRuinActivationTrigger && card.InstanceId == occurrence.Data?.SourceId) continue; var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = card, EventData = occurrence.Data, }; if (def.ActivationConditions is { Length: > 0 }) if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, card))) continue; // ── Per-turn limit ──────────────────────────────────────── if (def.TriggerLimitPerTurn is > 0) { var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}"; var key = (card.InstanceId, abilityKey, state.TurnNumber); _triggerCountsPerTurn.TryGetValue(key, out var used); if (used >= def.TriggerLimitPerTurn.Value) continue; _triggerCountsPerTurn[key] = used + 1; } // ── Per-game limit ──────────────────────────────────────── if (def.TriggerLimitPerGame is > 0) { var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}"; var gameKey = ($"{state.SessionId}:{card.InstanceId}", abilityKey); _triggerCountsPerGame.TryGetValue(gameKey, out var usedGame); if (usedGame >= def.TriggerLimitPerGame.Value) continue; _triggerCountsPerGame[gameKey] = usedGame + 1; } // If any action needs a human pick, pause and request client input. var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration) ?? []; var pickAction = Array.Find(effectiveActions, ActionNeedsClientTargets); if (pickAction is not null) { // Determine which player must actually submit the target picks. // For Chooser.Opponent/Ally, route the request to the non-activating player. string chooserActorId = pickAction.Target.Chooser switch { TargetChooser.Opponent => state.GetEnemyIds(ownerId).FirstOrDefault() ?? ownerId, TargetChooser.Ally => state.Players.Values .FirstOrDefault(p => p.AccountId != ownerId && state.AreAllies(p.AccountId, ownerId)) ?.AccountId ?? ownerId, _ => ownerId, // Self or default }; state.PendingTriggeredTarget = new PendingTriggeredTarget { ActorId = ownerId, ChooserActorId = chooserActorId, SourceInstanceId = card.InstanceId, AbilityName = def.Name ?? "Triggered Ability", ActionsJson = JsonSerializer.Serialize(effectiveActions, _jsonOpts), RangeJson = def.Range is not null ? JsonSerializer.Serialize(def.Range, _jsonOpts) : null, ForceDurationJson = def.Duration is not null ? JsonSerializer.Serialize(def.Duration, _jsonOpts) : null, }; // Return immediately — only one pending request at a time. return state; } ExecuteActions(effectiveActions, 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); 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 }; // Pre-seed the deferred target as action-0 resolved target so chained // actions inside the deferred tree can reference it. var tgt = FindDeferredTarget(state, pending.TargetRef); if (tgt is not null) dCtx.ResolvedTargets[0] = [tgt]; // Prefer ActionGroupJson (full recursive tree) over legacy flat ActionsJson. if (pending.ActionGroupJson is not null) { Models.ActionGroup? ag; try { ag = JsonSerializer.Deserialize(pending.ActionGroupJson, _jsonOpts); } catch { continue; } if (ag is null) continue; var resolved = ResolveActionGroup(ag, dCtx, abilityIndex: 0, range: null, forceDuration: null, continuationActions: []); if (resolved is not null) ExecuteActions(resolved, dCtx, clientTargets: null, requireClientTargets: false); } else { Models.Action[]? deferredActions; try { deferredActions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts); } catch { continue; } if (deferredActions is null || deferredActions.Length == 0) continue; ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false); } } 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; // Skip if this ruin is disabled by DisableRuinForDurationEffect. if (tile.RuinDisabledUntilTurn > 0 && state.TurnNumber <= tile.RuinDisabledUntilTurn) 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)]; var chosenActions = GetEffectiveActions(chosen, ctx, abilityIndex: 0, chosen.Range, chosen.Duration); if (chosenActions is not null) ExecuteActions(chosenActions, 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 ────────────────────────────────────────────────────────── /// /// Pays all costs in that can be auto-resolved. /// When an interactive pick-mode cost is encountered, stores /// on .State and returns true (caller must stop and return state). /// Returns false when all costs are paid without pausing. /// private static bool PayCosts( CostEntry[] costs, AbilityContext ctx, int abilityIndex, Models.Action[] pendingActions, AbilityRange? range, DurationModel? forceDuration) { var player = ctx.State.Players[ctx.ActorId]; for (int ci = 0; ci < costs.Length; ci++) { var cost = costs[ci]; // Interactive costs: pause for player pick. if (cost.PickMode is CostPickMode.SelfPick or CostPickMode.EnemySeePick or CostPickMode.EnemyRandomPick or CostPickMode.EnemyPick) { // Only DiscardFromHand / SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit // support interactive pick. Auto-resolve all others even if PickMode is set. if (cost.Type is CostType.DiscardFromHand or CostType.SendSpiritFromBattlefieldToDiscard or CostType.DealDamageToOwnSpirit) { // Determine who picks. var pickerActorId = cost.PickMode is CostPickMode.SelfPick ? ctx.ActorId : ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId; // Remaining costs after this one. var remaining = costs.Skip(ci + 1).ToArray(); // Compute candidates: the actor's eligible cards for this cost type. IEnumerable rawCandidates = cost.Type switch { CostType.DiscardFromHand => player.Hand, CostType.SendSpiritFromBattlefieldToDiscard => player.Field.OfType().Where(f => f.CardType == "Spirit").Cast(), CostType.DealDamageToOwnSpirit => player.Field.OfType().Where(f => f.CardType == "Spirit").Cast(), _ => Enumerable.Empty() }; // Apply cost filters so only eligible cards are offered to the picker. var filteredCandidates = cost.Filters is not null && cost.Filters.Length > 0 ? rawCandidates.Where(c => FiltersMatch(cost.Filters, c, ctx)) : rawCandidates; var candidateItems = filteredCandidates .Select(c => new { instanceId = c.InstanceId, name = c.Name, cardType = c.CardType }) .ToArray(); ctx.State.PendingCostPick = new PendingCostPick { ActorId = ctx.ActorId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, AbilityIndex = abilityIndex, PickerActorId = pickerActorId, CostType = cost.Type.ToString(), Amount = cost.Amount, PickMode = cost.PickMode.ToString()!, FiltersJson = cost.Filters is not null ? JsonSerializer.Serialize(cost.Filters, _jsonOpts) : null, RemainingCostsJson = JsonSerializer.Serialize(remaining, _jsonOpts), ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts), RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null, ForceDurationJson = forceDuration is not null ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, CandidatesJson = JsonSerializer.Serialize(candidateItems), }; return true; // paused } } // Auto-resolve the cost. PaySingleCost(cost, player, ctx); } return false; // all paid } /// /// Pays a CostGroup. /// AND: recursively pays all entries and sub-groups; pauses on first interactive cost. /// OR/XOR + Random: picks one child (entry or sub-group) at random and pays it. /// OR/XOR + Self/Opponent: stores and returns true. /// Returns true when paused (caller must stop and return state). /// private static bool PayCostGroup( CostGroup group, AbilityContext ctx, int abilityIndex, Models.Action[] pendingActions, AbilityRange? range, DurationModel? forceDuration) { if (group.LogicOp == CostGroupLogicOp.And) { // Pay all leaf entries. if (group.Entries.Length > 0) { bool paused = PayCosts(group.Entries, ctx, abilityIndex, pendingActions, range, forceDuration); if (paused) return true; } // Recurse into sub-groups. foreach (var child in group.Groups) { bool paused = PayCostGroup(child, ctx, abilityIndex, pendingActions, range, forceDuration); if (paused) return true; } return false; } // OR / XOR: combined pool = leaf entry sets + nested groups int entryCount = group.Entries.Length; int groupCount = group.Groups.Length; int total = entryCount + groupCount; if (total == 0) return false; if (group.ChooserRole == "Random") { int idx = Random.Shared.Next(total); if (idx < entryCount) { PaySingleCost(group.Entries[idx], ctx.State.Players[ctx.ActorId], ctx); return false; } return PayCostGroup(group.Groups[idx - entryCount], ctx, abilityIndex, pendingActions, range, forceDuration); } // Self or Opponent: pause for interactive pick. var chooserActorId = group.ChooserRole == "Opponent" ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId : ctx.ActorId; ctx.State.PendingCostGroupPick = new PendingCostGroupPick { ActorId = ctx.ActorId, ChooserActorId = chooserActorId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, AbilityIndex = abilityIndex, CostGroupJson = JsonSerializer.Serialize(group, _jsonOpts), ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts), RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null, ForceDurationJson = forceDuration is not null ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, }; return true; // paused } /// /// Resumes execution after the chooser has responded to a game.cost_group_pick. /// public static GameState ResumeCostGroupPick( GameState state, string actorId, string requestId, int choiceIndex) { var pending = state.PendingCostGroupPick ?? throw new GameException("NO_PENDING_COST_GROUP_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); if (actorId != pending.ActorId && actorId != pending.ChooserActorId) throw new GameException("NOT_YOUR_COST_GROUP_PICK"); state.PendingCostGroupPick = null; var group = JsonSerializer.Deserialize(pending.CostGroupJson, _jsonOpts) ?? throw new GameException("INVALID_COST_GROUP_STATE"); int entryCount = group.Entries.Length; int groupCount = group.Groups.Length; int total = entryCount + groupCount; if (choiceIndex < 0 || choiceIndex >= total) throw new GameException("INVALID_COST_GROUP_CHOICE"); var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); if (source is null) return state; var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; var player = state.Players[pending.ActorId]; AbilityRange? range = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; DurationModel? forceDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; var actions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts) ?? []; if (choiceIndex < entryCount) { // Pay the chosen leaf entry. PaySingleCost(group.Entries[choiceIndex], player, ctx); } else { // Recursively pay the chosen nested group (AND-only for now; nested OR/XOR would recurse further). bool paused = PayCostGroup(group.Groups[choiceIndex - entryCount], ctx, pending.AbilityIndex, actions, range, forceDuration); if (paused) return state; } ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false, activationRange: range, forceDuration: forceDuration); return state; } private static void PaySingleCost(CostEntry cost, PlayerState player, AbilityContext ctx) { 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 pool = player.Hand .Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx)) .ToList(); if (cost.PickMode == CostPickMode.Random) pool = pool.OrderBy(_ => Random.Shared.Next()).ToList(); var candidates = pool.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; } } } /// /// Resumes an Active ability after the picker has submitted their cost-pick selections. /// Called by GameCostPickHandler. /// public static GameState ResumeCostPick( GameState state, string actorId, string requestId, IReadOnlyList selectedInstanceIds) { var pending = state.PendingCostPick ?? throw new GameException("NO_PENDING_COST_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); // Allow both the actor and the designated picker to respond. if (actorId != pending.ActorId && actorId != pending.PickerActorId) throw new GameException("NOT_YOUR_COST_PICK"); state.PendingCostPick = null; var player = state.Players[pending.ActorId]; // Resolve source early so the filter context can evaluate source-relative filters // (IsSelf, IsAdjacentToSource, etc.). Source may have left the field — that's OK; // those spatial filters simply return false and thus never apply to hand/field cost picks. var earlySource = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var filterCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = earlySource }; var pickFilters = pending.FiltersJson is not null ? JsonSerializer.Deserialize(pending.FiltersJson, _jsonOpts) : null; // Validate and pay the interactive cost using the client-selected IDs. switch (pending.CostType) { case nameof(CostType.DiscardFromHand): { var toDiscard = selectedInstanceIds .Select(id => player.Hand.FirstOrDefault(c => c.InstanceId == id)) .OfType() .Take(pending.Amount) .ToList(); if (toDiscard.Count < pending.Amount) throw new GameException("INVALID_COST_PICK_SELECTION"); if (pickFilters is not null && toDiscard.Any(c => !FiltersMatch(pickFilters, c, filterCtx))) throw new GameException("INVALID_COST_PICK_SELECTION"); foreach (var c in toDiscard) { player.Hand.Remove(c); player.Discard.Add(c); } break; } case nameof(CostType.SendSpiritFromBattlefieldToDiscard): { var picked = selectedInstanceIds.FirstOrDefault() ?? throw new GameException("INVALID_COST_PICK_SELECTION"); var spirit = player.Field.OfType() .FirstOrDefault(f => f.InstanceId == picked) ?? throw new GameException("INVALID_COST_PICK_SELECTION"); if (pickFilters is not null && !FiltersMatch(pickFilters, spirit, filterCtx)) throw new GameException("INVALID_COST_PICK_SELECTION"); state.Board?.RemoveUnit(spirit.InstanceId); player.Field.Remove(spirit); player.Discard.Add(spirit); break; } case nameof(CostType.DealDamageToOwnSpirit): { var picked = selectedInstanceIds.FirstOrDefault() ?? throw new GameException("INVALID_COST_PICK_SELECTION"); var spirit = player.Field.OfType() .FirstOrDefault(f => f.InstanceId == picked) ?? throw new GameException("INVALID_COST_PICK_SELECTION"); if (pickFilters is not null && !FiltersMatch(pickFilters, spirit, filterCtx)) throw new GameException("INVALID_COST_PICK_SELECTION"); // Temporary context for damage application. var dmgCtx = new AbilityContext { State = state, ActorId = pending.ActorId }; ApplyDamageToUnit(spirit, pending.Amount, bypassDefense: false, dmgCtx); break; } } // Find the source unit (may have left the field while waiting — skip if gone). var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); if (source is null) return state; var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; // Pay any remaining non-interactive costs. var remainingCosts = JsonSerializer.Deserialize( pending.RemainingCostsJson, _jsonOpts) ?? []; foreach (var c in remainingCosts) PaySingleCost(c, player, ctx); // Execute the ability actions. var actions = JsonSerializer.Deserialize( pending.ActionsJson, _jsonOpts) ?? []; DurationModel? forceDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; AbilityRange? range = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false, activationRange: range, forceDuration: forceDuration); return state; } /// /// Resumes execution after the chooser has responded to a game.branch_pick. /// public static GameState ResumeBranchPick( GameState state, string actorId, string requestId, int branchIndex) { var pending = state.PendingBranchPick ?? throw new GameException("NO_PENDING_BRANCH_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); if (actorId != pending.ActorId && actorId != pending.ChooserActorId) throw new GameException("NOT_YOUR_BRANCH_PICK"); if (branchIndex < 0 || branchIndex >= pending.BranchCount) throw new GameException("INVALID_BRANCH_INDEX"); state.PendingBranchPick = null; var branches = JsonSerializer.Deserialize(pending.BranchesJson, _jsonOpts) ?? []; var continuation = JsonSerializer.Deserialize( pending.ContinuationActionsJson, _jsonOpts) ?? []; AbilityRange? range = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; DurationModel? forceDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; var allActions = branches[branchIndex].Actions.Concat(continuation).ToArray(); ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false, activationRange: range, forceDuration: forceDuration); return state; } // ── ActionGroup resolution ──────────────────────────────────────────────── /// /// Returns the flat action list to execute for an ability. /// AND groups are flattened recursively (leaves + nested group leaves). /// OR/XOR + Random: picks one child (action or nested group) server-side. /// OR/XOR + Self/Opponent: emits , returns null (caller must pause). /// Falls back to for pre-Phase-1 data. /// private static Models.Action[]? GetEffectiveActions( AbilityDefinition def, AbilityContext ctx, int abilityIndex, AbilityRange? range, DurationModel? forceDuration) { if (def.ActionGroup is { } ag) return ResolveActionGroup(ag, ctx, abilityIndex, range, forceDuration, continuationActions: []); return def.Actions; // backward-compat: pre-Phase-1 rows use the flat array } /// /// Recursively resolves an ActionGroup into a flat action list. /// Returns null when the group is interactive (OR/XOR + Self/Opponent) and /// has been stored. /// private static Models.Action[]? ResolveActionGroup( ActionGroup ag, AbilityContext ctx, int abilityIndex, AbilityRange? range, DurationModel? forceDuration, Models.Action[] continuationActions) { if (ag.LogicOp == ActionGroupLogicOp.And) { // AND: run leaves then recurse into nested groups, flattening all. var all = new List(ag.Actions); for (int gi = 0; gi < ag.Groups.Length; gi++) { var childActions = ResolveActionGroup(ag.Groups[gi], ctx, abilityIndex, range, forceDuration, continuationActions); if (childActions is null) { // Child emitted PendingActionGroupPick. Patch it: // - Store preceding actions (all actions resolved so far in this AND group) // so resume can execute them BEFORE the chosen branch. // - Store remaining sibling groups. // - Leave ContinuationActionsJson untouched (it already carries the outer // continuation that was passed into this recursive call). if (ctx.State.PendingActionGroupPick is { } pend) { // An inner AND group may have already set PrecedingActionsJson. // Prepend our own `all` to whatever the inner group stored. var innerPreceding = pend.PrecedingActionsJson is not null ? JsonSerializer.Deserialize(pend.PrecedingActionsJson, _jsonOpts) ?? [] : []; pend.PrecedingActionsJson = JsonSerializer.Serialize( all.Concat(innerPreceding).ToArray(), _jsonOpts); var remaining = ag.Groups.Skip(gi + 1).ToArray(); if (remaining.Length > 0) pend.RemainingGroupsJson = JsonSerializer.Serialize(remaining, _jsonOpts); } return null; } all.AddRange(childActions); } return all.ToArray(); } // OR / XOR: combined pool = leaf actions + nested groups int leafCount = ag.Actions.Length; int groupCount = ag.Groups.Length; int total = leafCount + groupCount; if (total == 0) return []; if (ag.ChooserRole == "Random") { int idx = Random.Shared.Next(total); if (idx < leafCount) return [ag.Actions[idx]]; return ResolveActionGroup(ag.Groups[idx - leafCount], ctx, abilityIndex, range, forceDuration, continuationActions); } // Self or Opponent: pause for interactive pick. var chooserActorId = ag.ChooserRole == "Opponent" ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId : ctx.ActorId; ctx.State.PendingActionGroupPick = new PendingActionGroupPick { ActorId = ctx.ActorId, ChooserActorId = chooserActorId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, ActionGroupJson = JsonSerializer.Serialize(ag, _jsonOpts), ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts), RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null, ForceDurationJson = forceDuration is not null ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, }; return null; // paused } /// /// Resumes execution after the chooser has responded to a game.action_group_pick. /// public static GameState ResumeActionGroupPick( GameState state, string actorId, string requestId, int choiceIndex) { var pending = state.PendingActionGroupPick ?? throw new GameException("NO_PENDING_ACTION_GROUP_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); if (actorId != pending.ActorId && actorId != pending.ChooserActorId) throw new GameException("NOT_YOUR_ACTION_GROUP_PICK"); state.PendingActionGroupPick = null; var ag = JsonSerializer.Deserialize(pending.ActionGroupJson, _jsonOpts) ?? throw new GameException("INVALID_ACTION_GROUP_STATE"); int leafCount = ag.Actions.Length; int groupCount = ag.Groups.Length; int total = leafCount + groupCount; if (choiceIndex < 0 || choiceIndex >= total) throw new GameException("INVALID_ACTION_GROUP_CHOICE"); var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; var continuation = JsonSerializer.Deserialize( pending.ContinuationActionsJson, _jsonOpts) ?? []; // Actions that ran before the pause in a parent AND group. // These must execute BEFORE the chosen branch to preserve AND-group order. var preceding = pending.PrecedingActionsJson is not null ? JsonSerializer.Deserialize(pending.PrecedingActionsJson, _jsonOpts) ?? [] : System.Array.Empty(); AbilityRange? range = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; DurationModel? forceDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; Models.Action[]? chosen; if (choiceIndex < leafCount) { chosen = [ag.Actions[choiceIndex]]; } else { chosen = ResolveActionGroup(ag.Groups[choiceIndex - leafCount], ctx, abilityIndex: 0, range, forceDuration, continuation); if (chosen is null) { // Nested group triggered another pick. // Accumulate our preceding into whatever the inner group set. if (ctx.State.PendingActionGroupPick is { } innerPend && preceding.Length > 0) { var innerInner = innerPend.PrecedingActionsJson is not null ? JsonSerializer.Deserialize(innerPend.PrecedingActionsJson, _jsonOpts) ?? [] : []; innerPend.PrecedingActionsJson = JsonSerializer.Serialize( preceding.Concat(innerInner).ToArray(), _jsonOpts); } return state; } } // Process any remaining sibling groups (from a parent AND group that paused here). ActionGroup[]? remainingGroups = pending.RemainingGroupsJson is not null ? JsonSerializer.Deserialize(pending.RemainingGroupsJson, _jsonOpts) : null; if (remainingGroups is { Length: > 0 }) { var tempList = new List(chosen); for (int rgi = 0; rgi < remainingGroups.Length; rgi++) { var rgActions = ResolveActionGroup(remainingGroups[rgi], ctx, abilityIndex: 0, range, forceDuration, continuation); if (rgActions is null) { // This remaining group paused. Carry forward the full preceding context: // preceding (from parent) + tempList (chosen branch + already-resolved groups) if (ctx.State.PendingActionGroupPick is { } newPend) { var newInnerPreceding = newPend.PrecedingActionsJson is not null ? JsonSerializer.Deserialize(newPend.PrecedingActionsJson, _jsonOpts) ?? [] : []; newPend.PrecedingActionsJson = JsonSerializer.Serialize( preceding.Concat(tempList).Concat(newInnerPreceding).ToArray(), _jsonOpts); // ContinuationActionsJson is already set by the new pause. var afterThis = remainingGroups.Skip(rgi + 1).ToArray(); newPend.RemainingGroupsJson = afterThis.Length > 0 ? JsonSerializer.Serialize(afterThis, _jsonOpts) : null; } return state; } tempList.AddRange(rgActions); } chosen = tempList.ToArray(); } // Correct AND-group order: [preceding] + [chosen/remaining] + [outer continuation]. var allActions = preceding.Concat(chosen).Concat(continuation).ToArray(); ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false, activationRange: range, forceDuration: forceDuration); return state; } /// /// Resumes execution after the chooser has responded to a game.reveal_choice_pick. /// is the chooser's desired ordering of the revealed cards /// (0-based indices into ). /// Unspecified cards are placed beneath the chosen cards in their original relative order. /// public static GameState ResumeRevealChoicePick( GameState state, string actorId, string requestId, int[] orderedIndices) { var pending = state.PendingRevealChoicePick ?? throw new GameException("NO_PENDING_REVEAL_CHOICE_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); if (actorId != pending.ActorId && actorId != pending.ChooserActorId) throw new GameException("NOT_YOUR_REVEAL_CHOICE_PICK"); state.PendingRevealChoicePick = null; if (pending.EffectType == "StackDeck") { var revealed = JsonSerializer.Deserialize( pending.RevealedCardsJson, _jsonOpts) ?? []; if (!state.Players.TryGetValue(pending.TargetPlayerAccountId, out var ps)) return state; // Validate indices (deduplicate, clamp to valid range). var validIndices = orderedIndices .Where(i => i >= 0 && i < revealed.Length) .Distinct() .ToArray(); var usedSet = new HashSet(validIndices); // Unspecified cards go at the bottom of the returned block (drawn last). var bottom = Enumerable.Range(0, revealed.Length) .Where(i => !usedSet.Contains(i)) .Select(i => revealed[i]) .ToList(); // Specified cards go on top (drawn first) in the chooser's order. var top = validIndices.Select(i => revealed[i]).ToList(); // Deck is stored with index 0 = bottom; top of deck is last element. ps.Deck.AddRange(bottom); ps.Deck.AddRange(top); } // Continue execution after the chooser submits their ordering. var rrcSource = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var rrcCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = rrcSource }; DurationModel? rrcActionDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; // Apply remaining effects within the same action. ApplyIntraActionContinuation(pending.IntraActionContinuationJson, rrcActionDuration, rrcCtx); // Execute outer continuation actions. if (!rrcCtx.State.HasPendingInteraction()) { var rrcContinuation = JsonSerializer.Deserialize( pending.ContinuationActionsJson, _jsonOpts) ?? []; if (rrcContinuation.Length > 0) { AbilityRange? rrcRange = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; ExecuteActions(rrcContinuation, rrcCtx, clientTargets: null, activationRange: rrcRange, forceDuration: rrcActionDuration); } } return state; } /// /// Resumes an effect-level pause where the player must pick a specific tile /// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile). /// Called by GameTilePickHandler. /// public static GameState ResumeTilePick( GameState state, string actorId, string requestId, Coord pickedTile) { var pending = state.PendingTilePick ?? throw new GameException("NO_PENDING_TILE_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) ? pending.ActorId : pending.ChooserActorId; if (expectedChooser != actorId) throw new GameException("NOT_YOUR_TILE_PICK"); state.PendingTilePick = null; var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; switch (pending.EffectType) { case "CloneSpiritAsToken": { var spiritToClone = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.TargetInstanceId); if (spiritToClone is null || state.Board is null) break; var tile = state.Board.GetTile(pickedTile); if (tile is null || !tile.IsEmpty) throw new GameException("INVALID_TILE"); var tokenProto = new CardInstance { InstanceId = Guid.NewGuid().ToString("N")[..8], CardType = "SpiritToken", Name = spiritToClone.Name, Affinity = spiritToClone.Affinity, MaxHealth = spiritToClone.MaxHealth, CurrentHealth = spiritToClone.MaxHealth, MaxDefense = spiritToClone.MaxDefense, CurrentDefense = spiritToClone.MaxDefense, Damage = spiritToClone.Damage, CanMove = spiritToClone.CanMove, CanAttack = spiritToClone.CanAttack, CanDefend = spiritToClone.CanDefend, MovementType = spiritToClone.MovementType, AbilitiesJson = spiritToClone.AbilitiesJson, }; var tokenField = CreateTokenFieldCard(tokenProto, pickedTile); state.Players[pending.ActorId].Field.Add(tokenField); state.Board.PlaceUnit(pickedTile, tokenField.InstanceId, pending.ActorId); EvaluateAurasOnEnter(state, tokenField.InstanceId); ApplyPassivesForSource(state, tokenField.InstanceId, pending.ActorId); ApplyPassivesToNewTarget(state, tokenField.InstanceId); break; } case "ChannelCardFromZone": { if (state.Board is null) break; var board = state.Board; // Resolve card and dest player. var ccCard = state.Players.Values .SelectMany(p => p.Hand.Concat(p.Deck).Concat(p.Discard).Cast()) .FirstOrDefault(c => c.InstanceId == pending.TargetInstanceId); if (ccCard is null) break; var ccFromOwner = FindCardOwner(state, pending.TargetInstanceId); if (ccFromOwner is null) break; var ccDestOwnerId = string.IsNullOrEmpty(pending.DestPlayerAccountId) ? pending.ActorId : pending.DestPlayerAccountId; if (!state.Players.TryGetValue(ccDestOwnerId, out var ccDestPlayer)) break; var tile = board.GetTile(pickedTile); if (tile is null || !tile.IsEmpty) throw new GameException("INVALID_TILE"); var ccze = pending.EffectJson is not null ? JsonSerializer.Deserialize(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect : null; // Affinity check. if (ccze?.IgnoreAffinity != true && Enum.TryParse(ccCard.Affinity, out var tpAffinity)) { if (!AffinitySystem.IsAffinityValid(tile, tpAffinity)) throw new GameException("INVALID_AFFINITY"); } // Cost. if (ccze?.IgnoreChannelCost != true) { ccDestPlayer.CurrentSp -= ccCard.SpCost; ccDestPlayer.CurrentSt -= ccCard.StCost; } // Remove from zone. if (ccze?.KeepInZone != true) RemoveFromZone(ccFromOwner, ccze?.Zone ?? "Hand", ccCard); // Place on board. var tpField = GameEngine.ToFieldCardInternal(ccCard, pickedTile); ccDestPlayer.Field.Add(tpField); board.PlaceUnit(pickedTile, tpField.InstanceId, ccDestOwnerId); EvaluateAurasOnEnter(state, tpField.InstanceId); ApplyPassivesForSource(state, tpField.InstanceId, ccDestOwnerId); ApplyPassivesToNewTarget(state, tpField.InstanceId); FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.Channeled, ActorId = ccDestOwnerId, CardType = ccCard.CardType, Data = new TriggerEventData { SourceId = tpField.InstanceId }, }); break; } } // Apply remaining effects within the same action before the outer continuation. DurationModel? tpActionDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; ApplyIntraActionContinuation(pending.IntraActionContinuationJson, tpActionDuration, ctx); // Execute outer continuation actions. if (!ctx.State.HasPendingInteraction()) { var continuation = JsonSerializer.Deserialize( pending.ContinuationActionsJson, _jsonOpts) ?? []; if (continuation.Length > 0) { AbilityRange? range = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; ExecuteActions(continuation, ctx, clientTargets: null, activationRange: range, forceDuration: tpActionDuration); } } return state; } /// /// Resumes an effect-level pause where the player must pick another player /// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice). /// Called by GamePlayerPickHandler. /// public static GameState ResumePlayerPick( GameState state, string actorId, string requestId, string pickedPlayerId) { var pending = state.PendingPlayerPick ?? throw new GameException("NO_PENDING_PLAYER_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) ? pending.ActorId : pending.ChooserActorId; if (expectedChooser != actorId) throw new GameException("NOT_YOUR_PLAYER_PICK"); if (pending.ValidPlayerIds.Count > 0 && !pending.ValidPlayerIds.Contains(pickedPlayerId)) throw new GameException("INVALID_PLAYER_PICK"); state.PendingPlayerPick = null; var ppSource = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var ppCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = ppSource }; // Dispatch per effect type. switch (pending.EffectType) { case "ChannelCardFromZone": { if (!state.Players.TryGetValue(pickedPlayerId, out var ppDest)) break; var ppBoard = state.Board; if (ppBoard is null) break; var ppCard = state.Players.Values .SelectMany(p => p.Hand.Concat(p.Deck).Concat(p.Discard).Cast()) .FirstOrDefault(c => c.InstanceId == pending.TargetInstanceId); if (ppCard is null) break; var ppFromOwner = FindCardOwner(state, pending.TargetInstanceId); if (ppFromOwner is null) break; var ppCcze = pending.EffectJson is not null ? JsonSerializer.Deserialize(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect : null; if (ppCcze?.TargetTile == true) { // Chain into a tile pick for the chosen dest player. // Forward IntraActionContinuationJson so the tile-pick resume // continues with the same intra-action remainder. state.PendingTilePick = new PendingTilePick { ActorId = pending.ActorId, ChooserActorId = pickedPlayerId, SourceInstanceId = pending.SourceInstanceId, EffectType = "ChannelCardFromZone", TargetInstanceId = pending.TargetInstanceId, DestPlayerAccountId = pickedPlayerId, RequireEmpty = true, EffectJson = pending.EffectJson, IntraActionContinuationJson = pending.IntraActionContinuationJson, ContinuationActionsJson = pending.ContinuationActionsJson, RangeJson = pending.RangeJson, ForceDurationJson = pending.ForceDurationJson, }; return state; } // Random tile in channel range. var ppArch = ppDest.ArchSpirit; Coord? ppCoord; if (ppCcze?.IgnoreChannelRange != true && ppArch?.Position.HasValue == true) { var maxR = ppCard.MaxChannelRange ?? 2; var minR = ppCard.MinChannelRange ?? 1; ppCoord = ppBoard.Tiles.Values .Where(t => t.IsEmpty) .Where(t => { var d = ppBoard.HexSides > 0 ? HexGrid.Distance(ppArch.Position!.Value, t.Coord, ppBoard.HexSides) : ppArch.Position!.Value.ManhattanDistance(t.Coord); return d >= minR && d <= maxR; }) .Select(t => t.Coord) .OrderBy(_ => Random.Shared.Next()) .Cast() .FirstOrDefault(); } else { ppCoord = ppBoard.Tiles.Values .Where(t => t.IsEmpty) .Select(t => t.Coord) .OrderBy(_ => Random.Shared.Next()) .Cast() .FirstOrDefault(); } if (ppCoord is null) break; // Affinity check. if (ppCcze?.IgnoreAffinity != true && Enum.TryParse(ppCard.Affinity, out var ppAff)) { var ppTile = ppBoard.GetTile(ppCoord.Value); if (ppTile is null || !AffinitySystem.IsAffinityValid(ppTile, ppAff)) break; } // Cost. if (ppCcze?.IgnoreChannelCost != true) { ppDest.CurrentSp -= ppCard.SpCost; ppDest.CurrentSt -= ppCard.StCost; } // Remove from zone. if (ppCcze?.KeepInZone != true) RemoveFromZone(ppFromOwner, ppCcze?.Zone ?? "Hand", ppCard); // Place on board. var ppField = GameEngine.ToFieldCardInternal(ppCard, ppCoord.Value); ppDest.Field.Add(ppField); ppBoard.PlaceUnit(ppCoord.Value, ppField.InstanceId, pickedPlayerId); EvaluateAurasOnEnter(state, ppField.InstanceId); ApplyPassivesForSource(state, ppField.InstanceId, pickedPlayerId); ApplyPassivesToNewTarget(state, ppField.InstanceId); FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.Channeled, ActorId = pickedPlayerId, CardType = ppCard.CardType, Data = new TriggerEventData { SourceId = ppField.InstanceId }, }); break; } default: { // Generic case: store the picked player in resolved targets for continuation use. if (state.Players.TryGetValue(pickedPlayerId, out var genericPickedPlayer)) ppCtx.ResolvedTargets[0] = [(object)genericPickedPlayer]; break; } } DurationModel? ppActionDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; // Apply remaining effects within the same action before the outer continuation. ApplyIntraActionContinuation(pending.IntraActionContinuationJson, ppActionDuration, ppCtx); if (!ppCtx.State.HasPendingInteraction()) { var ppContinuation = JsonSerializer.Deserialize( pending.ContinuationActionsJson, _jsonOpts) ?? []; if (ppContinuation.Length > 0) { AbilityRange? ppRange = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; ExecuteActions(ppContinuation, ppCtx, clientTargets: null, activationRange: ppRange, forceDuration: ppActionDuration); } } return state; } /// /// Resumes an active ability that was paused because a leaf Action had /// Chooser=Opponent/Ally and needed the non-activating player to supply targets. /// Called by GameTargetPickHandler. /// public static GameState ResumeTargetPick( GameState state, string actorId, string requestId, IReadOnlyList clientTargets) { var pending = state.PendingTargetPick ?? throw new GameException("NO_PENDING_TARGET_PICK"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) ? pending.ActorId : pending.ChooserActorId; if (expectedChooser != actorId) throw new GameException("NOT_YOUR_TARGET_PICK"); state.PendingTargetPick = null; var action = JsonSerializer.Deserialize(pending.ActionJson, _jsonOpts) ?? throw new GameException("INVALID_TARGET_PICK_STATE"); var continuation = JsonSerializer.Deserialize( pending.ContinuationActionsJson, _jsonOpts) ?? []; var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; AbilityRange? range = pending.RangeJson is not null ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; DurationModel? forceDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; // Execute the paused action (now with client targets) then run the continuation. // CONTRACT: The paused action is placed at index 0 in the replayed slice, so // the client must submit targets using ActionIndex=0 regardless of the original // action index in the ability definition. The prompt payload should reflect this. var allActions = new[] { action }.Concat(continuation).ToArray(); ExecuteActions(allActions, ctx, clientTargets, requireClientTargets: true, activationRange: range, forceDuration: forceDuration); return state; } // ── 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) { _sequenceDepth++; try { for (int i = 0; i < actions.Length; i++) { ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i, requireClientTargets, activationRange, restrictTargets, forceDuration, continuationActions: actions[(i + 1)..]); // Stop iterating as soon as any interactive pause is set. if (ctx.State.HasPendingInteraction()) break; } } finally { _sequenceDepth--; if (_sequenceDepth <= 0) { _sequenceDepth = 0; ExpireEndOfSequenceEffects(ctx.State); } } } 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, Models.Action[] continuationActions = null!) { continuationActions ??= []; // ChooseOne branch selector: execute the chosen branch's actions instead. if (action.ChooseOne is { Branches.Length: > 0 }) { var chooser = action.ChooseOne; int branchIdx; if (chooser.ChooserRole == "Random") { branchIdx = Random.Shared.Next(chooser.Branches.Length); } else if (chooser.ChooserRole is "Opponent" or "Ally") { // Pause — let the non-activating player pick. var chooserActorId = chooser.ChooserRole == "Opponent" ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId : ctx.State.Players.Values .FirstOrDefault(p => p.AccountId != ctx.ActorId && ctx.State.AreAllies(p.AccountId, ctx.ActorId)) ?.AccountId ?? ctx.ActorId; ctx.State.PendingBranchPick = new PendingBranchPick { ActorId = ctx.ActorId, ChooserActorId = chooserActorId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, BranchCount = chooser.Branches.Length, BranchesJson = JsonSerializer.Serialize(chooser.Branches, _jsonOpts), ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts), RangeJson = activationRange is not null ? JsonSerializer.Serialize(activationRange, _jsonOpts) : null, ForceDurationJson = forceDuration is not null ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, }; return; // paused — caller will propagate stop } else { // Self: use client-provided BranchIndex. branchIdx = clientTargets? .FirstOrDefault(t => t.ActionIndex == actionIndex)?.BranchIndex ?? 0; branchIdx = Math.Clamp(branchIdx, 0, chooser.Branches.Length - 1); } ExecuteActions(chooser.Branches[branchIdx].Actions, ctx, clientTargets: null, requireClientTargets: false, forceDuration: forceDuration); return; } // 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; // If Chooser=Opponent/Ally and we have no client-provided targets, pause for the // non-activating player to pick. (Chooser=Random is server-resolved in ResolveTargets.) var sel = action.Target; if (sel.Chooser is TargetChooser.Opponent or TargetChooser.Ally && clientTargets is null && sel.Type != TargetType.Player && !sel.Count.All) { var tpChooser = sel.Chooser == TargetChooser.Opponent ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId : ctx.State.Players.Values .FirstOrDefault(p => p.AccountId != ctx.ActorId && ctx.State.AreAllies(p.AccountId, ctx.ActorId)) ?.AccountId ?? ctx.ActorId; ctx.State.PendingTargetPick = new PendingTargetPick { ActorId = ctx.ActorId, ChooserActorId = tpChooser, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, ActionJson = JsonSerializer.Serialize(action, _jsonOpts), ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts), RangeJson = activationRange is not null ? JsonSerializer.Serialize(activationRange, _jsonOpts) : null, ForceDurationJson = forceDuration is not null ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, }; 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; // Snapshot all targets and effects for intra-action continuation capture. ctx.CurrentActionAllEffects = action.Effects; ctx.CurrentActionTargets = [.. resolved]; ctx.CurrentActionDuration = duration; ctx.ContinuationActions = continuationActions; ctx.ActivationRange = activationRange; for (int ti = 0; ti < resolved.Count; ti++) { var target = resolved[ti]; ctx.CurrentTargetIndex = ti; 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; } for (int ei = 0; ei < action.Effects.Length; ei++) { ctx.CurrentEffectIndex = ei; ExecuteEffect(action.Effects[ei], target, duration, ctx); // Stop as soon as an effect sets an interactive pause. if (ctx.State.HasPendingInteraction()) return; } // Also stop between targets if a pause was set mid-loop. if (ctx.State.HasPendingInteraction()) return; } } // ── Triggered ability client-target detection & resume ──────────────────── /// /// Returns true when the action requires a human target pick rather than /// being fully server-auto-resolvable. Used by to /// decide whether to pause and request client input. /// Also called by GameHandlerBase to locate the first client-pick action /// for the TriggeredTargetRequestPush payload. /// internal static bool ActionNeedsClientTargets_Public(Models.Action action) => ActionNeedsClientTargets(action); private static bool ActionNeedsClientTargets(Models.Action action) { // ChooseOne always needs the player to pick a branch. if (action.ChooseOne is { Branches.Length: > 0 }) return true; var sel = action.Target; // Player-type targets are always server-resolved. if (sel.Type == TargetType.Player) return false; // "All" targets are enumerated server-side with no player choice. if (sel.Count.All) return false; // Random chooser: server resolves without client input regardless of ownership. if (sel.Chooser == TargetChooser.Random) return false; // These ownerships are auto-resolved: self, random, chained from prior action. return sel.Ownership is not ( TargetOwnership.Self or TargetOwnership.ExactSelf or TargetOwnership.Target or TargetOwnership.Random); } /// /// Resumes a triggered ability that was paused for client target input. /// Called by GameTriggeredTargetHandler once the player submits their picks. /// public static GameState ResumeTriggeredAbility( GameState state, string actorId, string requestId, IReadOnlyList clientTargets) { var pending = state.PendingTriggeredTarget ?? throw new GameException("NO_PENDING_TRIGGER"); if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); // ChooserActorId is who must respond — may be an opponent/ally for Chooser.Opponent/Ally. // Fall back to ActorId for older records that predate ChooserActorId. var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) ? pending.ActorId : pending.ChooserActorId; if (expectedChooser != actorId) throw new GameException("NOT_YOUR_TRIGGER"); // Clear before executing so any nested triggers don't see a stale request. state.PendingTriggeredTarget = null; var actions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts) ?? []; // Source unit may have left the battlefield while waiting — skip silently if so. var source = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); if (source is null) return state; var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source, }; DurationModel? forceDuration = pending.ForceDurationJson is not null ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; ExecuteActions(actions, ctx, clientTargets, requireClientTargets: true, forceDuration: forceDuration); return state; } // ── 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(); // TargetChooser.Random: server picks randomly from filtered candidates — skip client IDs. if (selector.Chooser == TargetChooser.Random) { if (activationRange is not null) { candidates = FilterTargetsByAbilityRange(candidates.Cast().ToList(), ctx, activationRange) .OfType().ToList(); } var shuffled = candidates.OrderBy(_ => Random.Shared.Next()).ToList(); int take = selector.Count.All ? shuffled.Count : Math.Min(selector.Count.N, shuffled.Count); return shuffled.Take(take).Cast().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; } /// /// Recursively flattens an AND ActionGroup into a flat action list. /// OR/XOR groups are left as single-action entries (no interactive pause from here). /// private static Models.Action[] FlattenAndGroup(ActionGroup ag) { if (ag.LogicOp != ActionGroupLogicOp.And) return ag.Actions; // OR/XOR: callers should use ResolveActionGroup; this is a fallback var all = new List(ag.Actions); foreach (var child in ag.Groups) all.AddRange(FlattenAndGroup(child)); return all.ToArray(); } 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 raw = ResolveValue(mh.Amount, ctx); if (mh.StatTarget == StatTarget.Current) { int cur = ci.CurrentHealth ?? 0; int newVal = ApplyStatOperator(cur, raw, mh.Operator); if (ci.MaxHealth.HasValue) newVal = Math.Min(newVal, ci.MaxHealth.Value); int delta = newVal - cur; ci.CurrentHealth = newVal; if (ci.CurrentHealth <= 0) KillUnit(ci, ctx, ctx.Source?.InstanceId); TrackEffect(new ModifyHealthEffect { Amount = V(-delta), StatTarget = mh.StatTarget }, ci.InstanceId, duration, ctx); } else { int cur = ci.MaxHealth ?? 0; int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mh.Operator)); int delta = newVal - cur; ci.MaxHealth = newVal; if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth; TrackEffect(new ModifyHealthEffect { Amount = V(-delta), StatTarget = mh.StatTarget }, ci.InstanceId, duration, ctx); } break; } case ModifyDefenseEffect md when target is CardInstance ci: { int raw = ResolveValue(md.Amount, ctx); if (md.StatTarget == StatTarget.Current) { int cur = ci.CurrentDefense ?? 0; int newVal = Math.Max(0, ApplyStatOperator(cur, raw, md.Operator)); int delta = newVal - cur; ci.CurrentDefense = newVal; TrackEffect(new ModifyDefenseEffect { Amount = V(-delta), StatTarget = md.StatTarget }, ci.InstanceId, duration, ctx); } else { int cur = ci.MaxDefense ?? 0; int newVal = Math.Max(0, ApplyStatOperator(cur, raw, md.Operator)); int delta = newVal - cur; ci.MaxDefense = newVal; TrackEffect(new ModifyDefenseEffect { Amount = V(-delta), StatTarget = md.StatTarget }, ci.InstanceId, duration, ctx); } break; } case ModifyDamageEffect mdam when target is CardInstance ci: { int cur = ci.Damage ?? 0; int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mdam.Amount, ctx), mdam.Operator)); int delta = newVal - cur; ci.Damage = newVal; TrackEffect(new ModifyDamageEffect { Amount = V(-delta) }, ci.InstanceId, duration, ctx); break; } case ModifyMPEffect mmp when target is CardInstance ci: { int raw = ResolveValue(mmp.Amount, ctx); if (mmp.StatTarget == StatTarget.Current && ci is FieldCard fc) { int cur = fc.CurrentMp; int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mmp.Operator)); int delta = newVal - cur; fc.CurrentMp = newVal; TrackEffect(new ModifyMPEffect { Amount = V(-delta), StatTarget = mmp.StatTarget }, ci.InstanceId, duration, ctx); } else { int cur = ci.MaxMp ?? 0; int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mmp.Operator)); int delta = newVal - cur; ci.MaxMp = newVal; TrackEffect(new ModifyMPEffect { Amount = V(-delta), 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 cur = ci.MinAttackRange ?? 0; int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mmar.Amount, ctx), mmar.Operator)); int delta = newVal - cur; ci.MinAttackRange = newVal; TrackEffect(new ModifyMinAttackRangeEffect { Amount = V(-delta) }, ci.InstanceId, duration, ctx); break; } case ModifyMaxAttackRangeEffect mmax when target is CardInstance ci: { int cur = ci.MaxAttackRange ?? 1; int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mmax.Amount, ctx), mmax.Operator)); int delta = newVal - cur; ci.MaxAttackRange = newVal; TrackEffect(new ModifyMaxAttackRangeEffect { Amount = V(-delta) }, 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.ThenGroup is not null) { // Pre-load the found card as action-0 resolved target so chained // targeting in ThenGroup can reference it via "Action0.Target". var innerCtx = new AbilityContext { State = ctx.State, ActorId = ctx.ActorId, Source = ctx.Source }; innerCtx.ResolvedTargets[0] = [card]; var groupActions = FlattenAndGroup(sde.ThenGroup); ExecuteActions(groupActions, innerCtx, clientTargets: null, requireClientTargets: false); } 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; case PreventDeathEffect when target is CardInstance ci: { _preventDeathUnits.Add(ci.InstanceId); var d = duration is null || duration.Type == DurationType.Instant ? new DurationModel { Type = DurationType.UntilEndOfSequence } : duration; TrackEffect(new ClearPreventDeathEffect(), ci.InstanceId, d, ctx); break; } case PreventNextDamageEffect pnd when target is CardInstance ci: { var cap = pnd.MaxAmount is null ? (int?)null : ResolveValue(pnd.MaxAmount, ctx); _preventNextDamageByUnit[ci.InstanceId] = cap; var d = duration is null || duration.Type == DurationType.Instant ? new DurationModel { Type = DurationType.UntilEndOfSequence } : duration; TrackEffect(new ClearPreventNextDamageEffect(), ci.InstanceId, d, ctx); break; } case ClearPreventDeathEffect when target is CardInstance ci: { _preventDeathUnits.Remove(ci.InstanceId); break; } case ClearPreventNextDamageEffect when target is CardInstance ci: { _preventNextDamageByUnit.Remove(ci.InstanceId); break; } case SetHealthMinimumEffect shm when target is CardInstance ci: { var cur = ci.CurrentHealth ?? 0; if (cur < shm.Minimum) ci.CurrentHealth = shm.Minimum; 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; MoveUnitAndEmit(fc5, duOwner.AccountId, oldPos5, newPos5, ctx); break; } case RepositionUnitEffect rpe when target is FieldCard fc7: { if (!fc7.Position.HasValue || ctx.State.Board is null) break; var owner = ctx.State.Players.Values.FirstOrDefault(p => p.Field.Any(f => f.InstanceId == fc7.InstanceId)); if (owner is null) break; var from = fc7.Position.Value; var maxDist = Math.Max(1, rpe.Tiles); var board = ctx.State.Board; var candidates = board.Tiles.Values .Where(t => t.IsEmpty) .Select(t => t.Coord) .Where(c => from.ManhattanDistance(c) <= maxDist) .ToList(); if (rpe.AdjacentToSource && ctx.Source is FieldCard src && src.Position.HasValue) candidates = candidates.Where(c => c.IsOrthogonallyAdjacentTo(src.Position!.Value)).ToList(); Coord? refCoord = null; if (!string.IsNullOrWhiteSpace(rpe.RelativeToTargetRef)) { refCoord = ResolveCoordReference(rpe.RelativeToTargetRef!, ctx); if (refCoord.HasValue) { if (rpe.AdjacentToRelativeTarget) candidates = candidates.Where(c => c.IsOrthogonallyAdjacentTo(refCoord.Value)).ToList(); if (!rpe.AllowRelativeTargetTile) candidates = candidates.Where(c => c != refCoord.Value).ToList(); } } if (rpe.DestinationTileFilters is { Length: > 0 }) candidates = candidates.Where(c => TileMatchesFilters(rpe.DestinationTileFilters, board.GetTile(c)!, ctx)).ToList(); if (candidates.Count == 0) break; var to = candidates[Random.Shared.Next(candidates.Count)]; MoveUnitAndEmit(fc7, owner.AccountId, from, to, ctx); 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 explicit TileFilter (e.g. TileAffinityMatches) — throw so the client // receives an error rather than silently swallowing a bad pick. if (ste.TileFilter is { Length: > 0 } && !TileMatchesFilters(ste.TileFilter, tile, ctx)) throw new GameException("INVALID_TILE"); // Enforce tile affinity derived from the token's own Affinity field: a token // with a non-Void affinity may only be placed on a compatible tile. if (!string.IsNullOrEmpty(proto.Affinity) && proto.Affinity != "Void" && Enum.TryParse(proto.Affinity, out var tokenAffinity) && !AffinitySystem.IsAffinityValid(tile, tokenAffinity)) throw new GameException("INVALID_TILE"); 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.13 ArchSpirit zone operations ────────────────────────────── case AscendFromZoneEffect aze when target is FieldCard arcAze && arcAze.IsLeader: { // Find the owner of the target ArchSpirit. var azeOwner = FindCardOwner(ctx.State, arcAze.InstanceId) ?? (ctx.State.Players.Values.FirstOrDefault(p => p.ArchSpirit?.InstanceId == arcAze.InstanceId)); if (azeOwner is null) break; if (arcAze.Position is null) break; var coord = arcAze.Position.Value; int currentTier = arcAze.Tier ?? 1; // Find the incoming next-tier ArchSpirit from the specified zone. var incoming = FindInZone(azeOwner, aze.Zone, c => c.CardType == "ArchSpirit" && (c.Tier ?? 1) == currentTier + 1 && c.PreviousTierId == arcAze.CardDefinitionId); if (incoming is null) break; if (!aze.IgnoreCost) { if (azeOwner.CurrentSp < incoming.SpCost || azeOwner.CurrentSt < incoming.StCost) break; // insufficient resources — skip effect azeOwner.CurrentSp -= incoming.SpCost; azeOwner.CurrentSt -= incoming.StCost; } RemoveFromZone(azeOwner, aze.Zone, incoming); EvaluateAurasOnLeave(ctx.State, arcAze.InstanceId); RevokePassivesForSource(ctx.State, arcAze.InstanceId); ctx.State.Board?.RemoveUnit(arcAze.InstanceId); azeOwner.Discard.Add(arcAze); var newArch = GameEngine.ToFieldCardInternal(incoming, coord, isLeader: true); azeOwner.ArchSpirit = newArch; ctx.State.Board?.PlaceUnit(coord, newArch.InstanceId, azeOwner.AccountId); EvaluateAurasOnEnter(ctx.State, newArch.InstanceId); ApplyPassivesForSource(ctx.State, newArch.InstanceId, azeOwner.AccountId); ApplyPassivesToNewTarget(ctx.State, newArch.InstanceId); FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.Ascend, ActorId = azeOwner.AccountId, Data = new TriggerEventData { SourceId = newArch.InstanceId }, }); break; } case TransitionFromZoneEffect tze when target is FieldCard arcTze && arcTze.IsLeader: { var tzeOwner = FindCardOwner(ctx.State, arcTze.InstanceId) ?? (ctx.State.Players.Values.FirstOrDefault(p => p.ArchSpirit?.InstanceId == arcTze.InstanceId)); if (tzeOwner is null) break; if (arcTze.Position is null) break; var coord = arcTze.Position.Value; // Find a Tier-1 ArchSpirit from the specified zone (transition = replace with T1). var incoming = FindInZone(tzeOwner, tze.Zone, c => c.CardType == "ArchSpirit" && (c.Tier ?? 1) == 1); if (incoming is null) break; if (!tze.IgnoreCost) { if (tzeOwner.CurrentSp < incoming.SpCost || tzeOwner.CurrentSt < incoming.StCost) break; tzeOwner.CurrentSp -= incoming.SpCost; tzeOwner.CurrentSt -= incoming.StCost; } RemoveFromZone(tzeOwner, tze.Zone, incoming); EvaluateAurasOnLeave(ctx.State, arcTze.InstanceId); RevokePassivesForSource(ctx.State, arcTze.InstanceId); ctx.State.Board?.RemoveUnit(arcTze.InstanceId); tzeOwner.Discard.Add(arcTze); var newArch = GameEngine.ToFieldCardInternal(incoming, coord, isLeader: true); tzeOwner.ArchSpirit = newArch; ctx.State.Board?.PlaceUnit(coord, newArch.InstanceId, tzeOwner.AccountId); EvaluateAurasOnEnter(ctx.State, newArch.InstanceId); ApplyPassivesForSource(ctx.State, newArch.InstanceId, tzeOwner.AccountId); ApplyPassivesToNewTarget(ctx.State, newArch.InstanceId); FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.Transition, ActorId = tzeOwner.AccountId, Data = new TriggerEventData { SourceId = newArch.InstanceId }, }); break; } case ModifyChannelRangeEffect mcre when target is FieldCard arcMcr && arcMcr.IsLeader: { if (mcre.MinDelta != 0) { int orig = arcMcr.MinChannelRange ?? 0; arcMcr.MinChannelRange = Math.Max(0, orig + mcre.MinDelta); TrackEffect(new ModifyChannelRangeEffect { MinDelta = -(arcMcr.MinChannelRange.Value - orig) }, arcMcr.InstanceId, duration, ctx); } if (mcre.MaxDelta != 0) { int orig = arcMcr.MaxChannelRange ?? 0; arcMcr.MaxChannelRange = Math.Max(0, orig + mcre.MaxDelta); TrackEffect(new ModifyChannelRangeEffect { MaxDelta = -(arcMcr.MaxChannelRange.Value - orig) }, arcMcr.InstanceId, duration, ctx); } break; } // ── §5.14 Ruin manipulation ──────────────────────────────────────── case RelocateRuinEffect when target is Coord destCoord: { // Source is the ruin unit; relocate it to destCoord. if (ctx.Source is not FieldCard ruinFc || ctx.State.Board is null) break; var board = ctx.State.Board; var ruinTile = board.Tiles.Values.FirstOrDefault(t => t.RuinId == ruinFc.InstanceId); if (ruinTile is null) break; var destTile = board.GetTile(destCoord); if (destTile is null || destTile.RuinId is not null) break; board.RemoveRuin(ruinFc.InstanceId); board.PlaceRuin(destCoord, ruinFc.InstanceId, ctx.ActorId); ruinFc.Position = destCoord; break; } case ActivateRuinAbilityEffect arAe when target is FieldCard ruinCard && ruinCard.CardType == "Ruin": { var ruinOwner = FindCardOwner(ctx.State, ruinCard.InstanceId); if (ruinOwner is null) break; var ruinCtx = new AbilityContext { State = ctx.State, ActorId = ruinOwner.AccountId, Source = ruinCard }; var ruinAbilities = ParseAbilities(ruinCard.AbilitiesJson); var eligible = ruinAbilities .Where(a => a.Type == AbilityType.Triggered && a.TriggerEvent is OnRuinActivationTrigger) .Where(a => a.ActivationConditions is not { Length: > 0 } || a.ActivationConditions.All(c => EvaluateCondition(c, ruinCtx, ruinCard))) .ToList(); if (eligible.Count == 0) break; AbilityDefinition chosen; if (!arAe.Random && arAe.AbilityRef is not null) chosen = eligible.FirstOrDefault(a => a.Name == arAe.AbilityRef) ?? eligible[Random.Shared.Next(eligible.Count)]; else chosen = eligible[Random.Shared.Next(eligible.Count)]; var chosenActs = GetEffectiveActions(chosen, ruinCtx, 0, chosen.Range, chosen.Duration); if (chosenActs is not null) ExecuteActions(chosenActs, ruinCtx, clientTargets: null); break; } case DisableRuinForDurationEffect drfd when target is FieldCard ruinDis && ruinDis.CardType == "Ruin": { if (ruinDis.Position.HasValue && ctx.State.Board is not null) { var ruinDisTile = ctx.State.Board.GetTile(ruinDis.Position.Value); if (ruinDisTile is not null) { int disableTurns = drfd.Duration.Type switch { DurationType.ForNTurns => drfd.Duration.N ?? 1, _ => 1, }; ruinDisTile.RuinDisabledUntilTurn = ctx.State.TurnNumber + disableTurns; } } break; } // ── §5.15 Enhanced channeling ────────────────────────────────────── case ChannelCardFromZoneEffect ccze when target is CardInstance ciCcze: { var ccOwner = FindCardOwner(ctx.State, ciCcze.InstanceId); if (ccOwner is null) break; var board = ctx.State.Board; if (board is null) break; // Determine destination player. PlayerState? ccDestPlayer = ccze.UnderControlOf switch { "Target" => ccOwner, "Opponent" => ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() is { } ccEid ? ctx.State.Players.GetValueOrDefault(ccEid) : null, "Ally" => ctx.State.Players.Values.FirstOrDefault(p => p.AccountId != ctx.ActorId && ctx.State.AreAllies(p.AccountId, ctx.ActorId)), "Random" => ctx.State.Players.Values.OrderBy(_ => Random.Shared.Next()).FirstOrDefault(), "Choice" => null, _ => ctx.State.Players.GetValueOrDefault(ctx.ActorId), // "Self" }; if (ccze.UnderControlOf == "Choice" && ccDestPlayer is null) { // Pause: ask the actor to choose which player controls the card. ctx.State.PendingPlayerPick = new PendingPlayerPick { ActorId = ctx.ActorId, ChooserActorId = ctx.ActorId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, EffectType = "ChannelCardFromZone", TargetInstanceId = ciCcze.InstanceId, ValidPlayerIds = ctx.State.Players.Keys.ToList(), EffectJson = JsonSerializer.Serialize((Effect)ccze, _jsonOpts), IntraActionContinuationJson = BuildIntraActionContinuationJson(ciCcze, ctx), ContinuationActionsJson = JsonSerializer.Serialize(ctx.ContinuationActions, _jsonOpts), RangeJson = ctx.ActivationRange is not null ? JsonSerializer.Serialize(ctx.ActivationRange, _jsonOpts) : null, ForceDurationJson = duration is not null ? JsonSerializer.Serialize(duration, _jsonOpts) : null, }; return; } if (ccDestPlayer is null) break; // Destination tile. if (ccze.TargetTile) { ctx.State.PendingTilePick = new PendingTilePick { ActorId = ctx.ActorId, ChooserActorId = ccDestPlayer.AccountId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, EffectType = "ChannelCardFromZone", TargetInstanceId = ciCcze.InstanceId, DestPlayerAccountId = ccDestPlayer.AccountId, RequireEmpty = true, EffectJson = JsonSerializer.Serialize((Effect)ccze, _jsonOpts), IntraActionContinuationJson = BuildIntraActionContinuationJson(ciCcze, ctx), ContinuationActionsJson = JsonSerializer.Serialize(ctx.ContinuationActions, _jsonOpts), RangeJson = ctx.ActivationRange is not null ? JsonSerializer.Serialize(ctx.ActivationRange, _jsonOpts) : null, ForceDurationJson = duration is not null ? JsonSerializer.Serialize(duration, _jsonOpts) : null, }; return; } // Random tile in channel range (or anywhere if IgnoreChannelRange). var ccArch = ccDestPlayer.ArchSpirit; Coord? ccDestCoord; if (!ccze.IgnoreChannelRange && ccArch?.Position.HasValue == true) { var maxR = ciCcze.MaxChannelRange ?? 2; var minR = ciCcze.MinChannelRange ?? 1; ccDestCoord = board.Tiles.Values .Where(t => t.IsEmpty) .Where(t => { var d = board.HexSides > 0 ? HexGrid.Distance(ccArch.Position!.Value, t.Coord, board.HexSides) : ccArch.Position!.Value.ManhattanDistance(t.Coord); return d >= minR && d <= maxR; }) .Select(t => t.Coord) .OrderBy(_ => Random.Shared.Next()) .Cast() .FirstOrDefault(); } else { ccDestCoord = board.Tiles.Values .Where(t => t.IsEmpty) .Select(t => t.Coord) .OrderBy(_ => Random.Shared.Next()) .Cast() .FirstOrDefault(); } if (ccDestCoord is null) break; // Affinity check. if (!ccze.IgnoreAffinity && Enum.TryParse(ciCcze.Affinity, out var ccAffinity)) { var ccTile = board.GetTile(ccDestCoord.Value); if (ccTile is null || !AffinitySystem.IsAffinityValid(ccTile, ccAffinity)) break; } // Cost. if (!ccze.IgnoreChannelCost) { ccDestPlayer.CurrentSp -= ciCcze.SpCost; ccDestPlayer.CurrentSt -= ciCcze.StCost; } // Remove from zone. if (!ccze.KeepInZone) RemoveFromZone(ccOwner, ccze.Zone, ciCcze); // Place on board. var ccField = GameEngine.ToFieldCardInternal(ciCcze, ccDestCoord.Value); ccDestPlayer.Field.Add(ccField); board.PlaceUnit(ccDestCoord.Value, ccField.InstanceId, ccDestPlayer.AccountId); // Auras / passives. EvaluateAurasOnEnter(ctx.State, ccField.InstanceId); ApplyPassivesForSource(ctx.State, ccField.InstanceId, ccDestPlayer.AccountId); ApplyPassivesToNewTarget(ctx.State, ccField.InstanceId); // Trigger. FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.Channeled, ActorId = ccDestPlayer.AccountId, CardType = ciCcze.CardType, Data = new TriggerEventData { SourceId = ccField.InstanceId }, }); break; } // ── §5.16 Token / spirit operations ─────────────────────────────── case CloneSpiritAsTokenEffect cste when target is FieldCard spiritToClone: { if (ctx.State.Board is null || !spiritToClone.Position.HasValue) break; var board = ctx.State.Board; // Find a suitable destination tile. Coord? dest = cste.DestinationScope switch { "TargetTile" when ctx.ResolvedTargets.Count > 0 && ctx.ResolvedTargets.Values.SelectMany(x => x).OfType().FirstOrDefault() is { } resolvedCoord => resolvedCoord, "TargetTile" => null, // no coord yet — will pause below "RandomInChannelRange" when ctx.Source is FieldCard srcFc && srcFc.Position.HasValue => board.Tiles.Values .Where(t => t.IsEmpty && t.Coord.ManhattanDistance(srcFc.Position.Value) <= (ctx.Source as CardInstance)?.MaxChannelRange.GetValueOrDefault(2)) .Select(t => t.Coord) .OrderBy(_ => Random.Shared.Next()) .Cast() .FirstOrDefault(), _ => // NeighborTile (default) board.Tiles.Values .Where(t => t.IsEmpty && t.Coord.IsOrthogonallyAdjacentTo(spiritToClone.Position.Value)) .Select(t => t.Coord) .OrderBy(_ => Random.Shared.Next()) .Cast() .FirstOrDefault(), }; if (dest is null) { // TargetTile: no resolved coord — pause for player to pick a destination tile. if (cste.DestinationScope == "TargetTile") { ctx.State.PendingTilePick = new PendingTilePick { ActorId = ctx.ActorId, ChooserActorId = ctx.ActorId, SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, EffectType = "CloneSpiritAsToken", TargetInstanceId = spiritToClone.InstanceId, RequireEmpty = true, IntraActionContinuationJson = BuildIntraActionContinuationJson(spiritToClone, ctx), ContinuationActionsJson = JsonSerializer.Serialize(ctx.ContinuationActions, _jsonOpts), RangeJson = ctx.ActivationRange is not null ? JsonSerializer.Serialize(ctx.ActivationRange, _jsonOpts) : null, ForceDurationJson = duration is not null ? JsonSerializer.Serialize(duration, _jsonOpts) : null, }; } break; } var tokenProto = new CardInstance { InstanceId = Guid.NewGuid().ToString("N")[..8], CardType = "SpiritToken", Name = spiritToClone.Name, Affinity = spiritToClone.Affinity, MaxHealth = spiritToClone.MaxHealth, CurrentHealth = spiritToClone.MaxHealth, MaxDefense = spiritToClone.MaxDefense, CurrentDefense = spiritToClone.MaxDefense, Damage = spiritToClone.Damage, CanMove = spiritToClone.CanMove, CanAttack = spiritToClone.CanAttack, CanDefend = spiritToClone.CanDefend, MovementType = spiritToClone.MovementType, AbilitiesJson = spiritToClone.AbilitiesJson, }; var tokenField = CreateTokenFieldCard(tokenProto, dest.Value); ctx.State.Players[ctx.ActorId].Field.Add(tokenField); board.PlaceUnit(dest.Value, tokenField.InstanceId, ctx.ActorId); EvaluateAurasOnEnter(ctx.State, tokenField.InstanceId); break; } case DestroyTokenEffect when target is FieldCard tokenFc && tokenFc.CardType == "SpiritToken": KillUnit(tokenFc, ctx, ctx.Source?.InstanceId); break; // ── §5.17 Player operations ──────────────────────────────────────── case SkipTurnEffect when target is PlayerState skipPs: skipPs.SkipTurnCount += 1; break; case ModifyCardsDrawnThisTurnEffect mcdtt when target is PlayerState mcdtPs: mcdtPs.CardsDrawnThisTurnBonus += ResolveValue(mcdtt.Amount, ctx); break; // ── §5.18 Zone operations ────────────────────────────────────────── case StackDeckEffect stkDe when target is PlayerState stackPs: { int n = Math.Min(stkDe.Count, stackPs.Deck.Count); if (n == 0) break; // Determine chooser account id. string chooserAccountId = stkDe.Chooser switch { "Opponent" => ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId, "Random" => "", _ => ctx.ActorId, // "Self" }; if (stkDe.Chooser == "Random" || string.IsNullOrEmpty(chooserAccountId)) { // Non-interactive: shuffle top N randomly. var topN = stackPs.Deck.TakeLast(n).ToList(); for (int si = topN.Count - 1; si > 0; si--) { int sj = Random.Shared.Next(si + 1); (topN[si], topN[sj]) = (topN[sj], topN[si]); } for (int si = 0; si < n; si++) stackPs.Deck[stackPs.Deck.Count - n + si] = topN[si]; break; } // Interactive: remove top N from deck and pause for chooser to order them. var revealed = stackPs.Deck.TakeLast(n).ToList(); stackPs.Deck.RemoveRange(stackPs.Deck.Count - n, n); ctx.State.PendingRevealChoicePick = new Models.PendingRevealChoicePick { ActorId = ctx.ActorId, ChooserActorId = chooserAccountId, SourceInstanceId = ctx.Source?.InstanceId ?? "", EffectType = "StackDeck", RevealedCardsJson = JsonSerializer.Serialize(revealed, _jsonOpts), Count = n, TargetPlayerAccountId = stackPs.AccountId, IntraActionContinuationJson = BuildIntraActionContinuationJson(stackPs, ctx), ContinuationActionsJson = JsonSerializer.Serialize(ctx.ContinuationActions, _jsonOpts), RangeJson = ctx.ActivationRange is not null ? JsonSerializer.Serialize(ctx.ActivationRange, _jsonOpts) : null, ForceDurationJson = duration is not null ? JsonSerializer.Serialize(duration, _jsonOpts) : null, }; break; } case SearchAndPlaceEffect sape when target is PlayerState sapPs: { var found = sapPs.Deck .Where(c => sape.Filters is null || FiltersMatch(sape.Filters, c, ctx)) .Take(sape.Count).ToList(); foreach (var card in found) { sapPs.Deck.Remove(card); switch (sape.Destination) { case "Hand": sapPs.Hand.Add(card); break; case "Discard": sapPs.Discard.Add(card); break; case "Battlefield": // Basic: put in discard if no tile available. sapPs.Discard.Add(card); break; default: sapPs.Hand.Add(card); break; } } if (sape.ShuffleAfter) { for (int si = sapPs.Deck.Count - 1; si > 0; si--) { int sj = Random.Shared.Next(si + 1); (sapPs.Deck[si], sapPs.Deck[sj]) = (sapPs.Deck[sj], sapPs.Deck[si]); } } break; } // ── §5.19 Unit manipulation ──────────────────────────────────────── case ChangeAttackTypeEffect cate when target is CardInstance ciCat: { var origAt = ciCat.AttackType; ciCat.AttackType = cate.AttackType; TrackEffect(new ChangeAttackTypeEffect { AttackType = origAt ?? default }, ciCat.InstanceId, duration, ctx); break; } case ObstructMovementTypeEffect omte when target is FieldCard fcOmte: { if (duration is null) break; // reversal call from ApplyReversal — no-op // Store the effect as an active marker. BuildBlockedSet queries ActiveEffects // for ObstructMovementTypeEffect entries to extend the blocked-set for pathfinding. // When expired, ApplyReversal calls ExecuteEffect(omte, ..., duration:null) which // hits the guard above and is a no-op; the entry has already been removed. var omteDuration = duration.Type is DurationType.Instant or DurationType.PermanentInMatch ? omte.Duration : duration; ctx.State.ActiveEffects.Add(new ActiveEffect { SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, TargetRef = fcOmte.InstanceId, EffectJson = JsonSerializer.Serialize((Effect)omte, _jsonOpts), DurationJson = JsonSerializer.Serialize(new TrackedDuration { Duration = omteDuration, OwnerAccountId = ctx.ActorId, }, _jsonOpts), TurnsRemaining = omteDuration.N ?? 0, Label = $"Obstruct:{omte.MovementType}", }); 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, // Store the ActionGroup as the canonical form; ActionsJson is a legacy fallback. ActionGroupJson = aoe.ActionGroup is not null ? JsonSerializer.Serialize(aoe.ActionGroup, _jsonOpts) : null, ActionsJson = "[]", }); 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) { switch (f) { case AffinityMatchesFilter amf: { var resolved = AffinitySystem.Resolve(tile.Base1, tile.Base2); if (!Enum.TryParse(amf.Affinity.ToString(), out var expected) || resolved != expected) return false; break; } case TileAffinityMatchesFilter tam: if (AffinitySystem.Resolve(tile.Base1, tile.Base2) != tam.Affinity) return false; break; case TileIsOccupiedFilter tio: if (tile.IsEmpty) return false; if (!string.IsNullOrEmpty(tio.UnitType) && tile.OccupantId is not null) { var utype = FindUnitType(ctx.State, tile.OccupantId); if (!string.Equals(utype, tio.UnitType, StringComparison.OrdinalIgnoreCase)) return false; } break; case TileIsUnoccupiedFilter: if (!tile.IsEmpty) return false; break; case TileWithinRangeFilter twr: if (ctx.Source is not FieldCard src || !src.Position.HasValue) return false; var d = src.Position.Value.ManhattanDistance(tile.Coord); if (d < twr.Min || d > twr.Max) return false; break; case TileIsAdjacentToUnitFilter tau: { if (ctx.State.Board is null) return false; var any = OrthogonalNeighbours(tile.Coord).Any(n => { var nt = ctx.State.Board.GetTile(n); if (nt is null || nt.IsEmpty || nt.OccupantId is null || nt.OccupantOwner is null) return false; if (!OwnershipMatchesForPlayer(tau.Ownership, nt.OccupantOwner, ctx.ActorId, ctx.State)) return false; if (tau.UnitFilter is null) return true; var nu = ctx.State.Players.Values.SelectMany(p => p.Field).FirstOrDefault(u => u.InstanceId == nt.OccupantId); return nu is not null && FilterMatches(tau.UnitFilter, nu, ctx); }); if (!any) return false; break; } default: break; } } return true; } // ── Damage helper ───────────────────────────────────────────────────────── private static void ApplyDamageToUnit( CardInstance unit, int rawAmount, bool bypassDefense, AbilityContext ctx) { // Pre-damage replacement/prevention window. FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.BeforeDamageApplied, ActorId = ctx.ActorId, Data = new TriggerEventData { SourceId = ctx.Source?.InstanceId, TargetId = unit.InstanceId, Amount = rawAmount }, UnitType = unit.CardType, }); var amount = rawAmount; if (_preventNextDamageByUnit.TryGetValue(unit.InstanceId, out var cap)) { var prevented = cap is null ? amount : Math.Min(amount, Math.Max(0, cap.Value)); amount -= prevented; if (cap is not null) { var remain = cap.Value - prevented; if (remain > 0) _preventNextDamageByUnit[unit.InstanceId] = remain; else _preventNextDamageByUnit.Remove(unit.InstanceId); } else { _preventNextDamageByUnit.Remove(unit.InstanceId); } if (prevented > 0) { FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.DamagePrevented, ActorId = ctx.ActorId, Data = new TriggerEventData { SourceId = ctx.Source?.InstanceId, TargetId = unit.InstanceId, Amount = prevented }, UnitType = unit.CardType, }); } } int net = bypassDefense ? amount : Math.Max(0, amount - (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) { // The unit may be an ArchSpirit, which lives in PlayerState.ArchSpirit (not in regular zones). var archOwner = ctx.State.Players.Values .FirstOrDefault(p => p.ArchSpirit?.InstanceId == unit.InstanceId); if (archOwner is null) return; GameEngine.EliminatePlayer(ctx.State, archOwner, out _); return; } // If the killed unit is a leader (ArchSpirit on the field), eliminate the player. if (unit is FieldCard { IsLeader: true }) { GameEngine.EliminatePlayer(ctx.State, owner, out _); return; } // Pre-death replacement/prevention window. FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.BeforeUnitDeath, ActorId = owner.AccountId, Data = new TriggerEventData { SourceId = killerInstanceId, TargetId = unit.InstanceId }, UnitType = unit.CardType, }); if (_preventDeathUnits.Remove(unit.InstanceId)) { unit.CurrentHealth = Math.Max(unit.CurrentHealth ?? 0, 1); 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; MoveUnitAndEmit(unit, ownerEntry.AccountId, unitPos, newPos, ctx); } private static Coord? ResolveCoordReference(string targetRef, AbilityContext ctx) { if (targetRef.StartsWith("Action", StringComparison.OrdinalIgnoreCase)) { var tail = targetRef[6..]; var dot = tail.IndexOf('.'); if (dot > 0 && int.TryParse(tail[..dot], out var actionNum)) { if (ctx.ResolvedTargets.TryGetValue(actionNum - 1, out var targets)) { var first = targets.FirstOrDefault(); if (first is Coord c) return c; if (first is FieldCard fc && fc.Position.HasValue) return fc.Position.Value; } } } return null; } private static void MoveUnitAndEmit(FieldCard unit, string ownerId, Coord from, Coord to, AbilityContext ctx) { if (ctx.State.Board is null) return; ctx.State.Board.RemoveUnit(unit.InstanceId); ctx.State.Board.PlaceUnit(to, unit.InstanceId, ownerId); unit.Position = to; EvaluateAuraTransitions(ctx.State, unit.InstanceId, from, to); FireTrigger(ctx.State, new TriggerOccurrence { Kind = TriggerEventKind.UnitMove, ActorId = ownerId, UnitType = unit.CardType, Data = new TriggerEventData { SourceId = unit.InstanceId, PreviousTile = from, DestinationTile = to, }, }); } // ── 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) { // Guard: ArchSpirit must be eliminated via EliminatePlayer, not removed directly. if (player.ArchSpirit?.InstanceId == card.InstanceId) throw new InvalidOperationException( $"RemoveFromAllZones must not be called on an ArchSpirit ({card.InstanceId}); use EliminatePlayer instead."); 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); // Clear board position so stale coords are never observed after a zone transition. if (card is FieldCard fc) fc.Position = null; } 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; } /// /// Returns the InstanceIds of all units currently carrying an /// active effect that obstructs . /// Used by to extend pathfinding blocked-sets. /// internal static HashSet GetUnitsObstructingMovementType(GameState state, MovementType movType) { var result = new HashSet(); foreach (var ae in state.ActiveEffects) { Effect? eff; try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); } catch { continue; } if (eff is ObstructMovementTypeEffect omte && omte.MovementType == movType) result.Add(ae.TargetRef); } return result; } /// Find the first card in the given zone ("Hand"|"Deck"|"Discard"|"Any") matching predicate. private static CardInstance? FindInZone(PlayerState player, string zone, Func predicate) => zone switch { "Hand" => player.Hand.FirstOrDefault(predicate), "Deck" => player.Deck.FirstOrDefault(predicate), "Discard" => player.Discard.FirstOrDefault(predicate), _ => // "Any": search all zones player.Hand.FirstOrDefault(predicate) ?? player.Deck.FirstOrDefault(predicate) ?? (CardInstance?)player.Discard.FirstOrDefault(predicate), }; /// Remove a card from the specified zone ("Hand"|"Deck"|"Discard"|"Any"). private static void RemoveFromZone(PlayerState player, string zone, CardInstance card) { switch (zone) { case "Hand": player.Hand.Remove(card); break; case "Deck": player.Deck.Remove(card); break; case "Discard": player.Discard.Remove(card); break; default: // "Any" if (!player.Hand.Remove(card)) if (!player.Deck.Remove(card)) player.Discard.Remove(card); break; } } private static IEnumerable OrthogonalNeighbours(Coord c) => [ new Coord(c.X - 1, c.Y), new Coord(c.X + 1, c.Y), new Coord(c.X, c.Y - 1), new Coord(c.X, c.Y + 1), ]; 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 NotCondition not: return !EvaluateCondition(not.Condition, ctx, subject); 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 DestinationTileAffinityIsCondition dta: { if (ctx.EventData?.DestinationTile is not Coord to || ctx.State.Board is null) return false; var tile = ctx.State.Board.GetTile(to); return tile is not null && AffinitySystem.Resolve(tile.Base1, tile.Base2) == dta.Affinity; } case PreviousTileAffinityIsCondition pta: { if (ctx.EventData?.PreviousTile is not Coord from || ctx.State.Board is null) return false; var tile = ctx.State.Board.GetTile(from); return tile is not null && AffinitySystem.Resolve(tile.Base1, tile.Base2) == pta.Affinity; } case MovedFromOrIntoAffinityCondition mfa: { if (ctx.State.Board is null) return false; var fromOk = false; var toOk = false; if (ctx.EventData?.PreviousTile is Coord from) { var t = ctx.State.Board.GetTile(from); fromOk = t is not null && AffinitySystem.Resolve(t.Base1, t.Base2) == mfa.Affinity; } if (ctx.EventData?.DestinationTile is Coord to) { var t = ctx.State.Board.GetTile(to); toOk = t is not null && AffinitySystem.Resolve(t.Base1, t.Base2) == mfa.Affinity; } return fromOk || toOk; } case IsAdjacentToTileWithAffinityCondition iat: { if (subject is not FieldCard afc || !afc.Position.HasValue || ctx.State.Board is null) return false; foreach (var n in OrthogonalNeighbours(afc.Position.Value)) { var tile = ctx.State.Board.GetTile(n); if (tile is not null && AffinitySystem.Resolve(tile.Base1, tile.Base2) == iat.Affinity) return true; } return false; } case IsOnOrAdjacentToTileWithAffinityCondition ioat: { if (subject is not FieldCard ofc || !ofc.Position.HasValue || ctx.State.Board is null) return false; var here = ctx.State.Board.GetTile(ofc.Position.Value); if (here is not null && AffinitySystem.Resolve(here.Base1, here.Base2) == ioat.Affinity) return true; foreach (var n in OrthogonalNeighbours(ofc.Position.Value)) { var tile = ctx.State.Board.GetTile(n); if (tile is not null && AffinitySystem.Resolve(tile.Base1, tile.Base2) == ioat.Affinity) return true; } return false; } case IsCurrentlyMovingCondition: { if (ctx.EventData?.PreviousTile is null || ctx.EventData?.DestinationTile is null) return false; if (subject is CardInstance sci) return ctx.EventData?.SourceId == sci.InstanceId; return true; } 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; } case ControlledTileCountWithAffinityCondition ctc: { if (ctx.State.Board is null) return false; var count = ctx.State.Board.Tiles.Values.Count(t => !string.IsNullOrEmpty(t.OccupantOwner) && AffinitySystem.Resolve(t.Base1, t.Base2) == ctc.Affinity && OwnershipMatchesForPlayer(ctc.Ownership, t.OccupantOwner!, ctx.ActorId, ctx.State)); return ctc.Comparator switch { Comparator.Equal => count == ctc.N, Comparator.NotEqual => count != ctc.N, Comparator.LessThan => count < ctc.N, Comparator.LessThanOrEqual => count <= ctc.N, Comparator.GreaterThan => count > ctc.N, Comparator.GreaterThanOrEqual => count >= ctc.N, _ => false, }; } // ── §6.6 Extended unit / player conditions ─────────────────────────── case UnitTypeIsCondition uti when subject is CardInstance utiCard: return utiCard.CardType == uti.UnitType; case OwnershipIsCondition oi: { var ownerPlayer = subject is CardInstance ownCard ? FindCardOwner(ctx.State, ownCard.InstanceId) : null; if (ownerPlayer is null) return false; return OwnershipMatchesForPlayer(oi.Ownership, ownerPlayer.AccountId, ctx.ActorId, ctx.State); } case IsThisCardCondition when subject is CardInstance thisCard: return ctx.Source is CardInstance srcCard && srcCard.InstanceId == thisCard.InstanceId; case UnitPropertyCompareCondition upc when subject is CardInstance upcCard: { int val = upc.PropertyName switch { "Damage" => upcCard.Damage ?? 0, "Defense" => upcCard.CurrentDefense ?? 0, "MaxDefense" => upcCard.MaxDefense ?? 0, "Health" => upcCard.CurrentHealth ?? 0, "MaxHealth" => upcCard.MaxHealth ?? 0, "MovementPoints" => upcCard is FieldCard fcMp ? fcMp.CurrentMp : 0, "MaxMovementPoints" => upcCard.MaxMp ?? 0, "MinAttackRange" => upcCard.MinAttackRange ?? 0, "MaxAttackRange" => upcCard.MaxAttackRange ?? 0, "MinChannelRange" => upcCard.MinChannelRange ?? 0, "MaxChannelRange" => upcCard.MaxChannelRange ?? 0, "Tier" => upcCard.Tier ?? 0, _ => 0, }; return CompareInt(upc.Comparator, val, upc.Value); } case PlayerPropertyCompareCondition ppc: { var targetPlayer = ppc.Subject.ToLowerInvariant() switch { "opponent" => ctx.State.Players.Values.FirstOrDefault(p => p.AccountId != ctx.ActorId), _ => player, // "self" | "owner" | "ally" → same player in a 2-player game }; if (targetPlayer is null) return false; int val = ppc.PropertyName switch { "SP" => targetPlayer.CurrentSp, "ST" => targetPlayer.CurrentSt, "SPAccumulation" => ctx.State.Rules.SpAccumulationPerTurn + targetPlayer.SpAccumulationBonus, "HandSize" => targetPlayer.Hand.Count, "DeckSize" => targetPlayer.Deck.Count, "DiscardSize" => targetPlayer.Discard.Count, _ => 0, }; return CompareInt(ppc.Comparator, val, ppc.Value); } case HandContainsCountCondition hcc: { var cnt = player.Hand.Count(c => (hcc.CardType is null || c.CardType == hcc.CardType) && (hcc.Affinity is null || c.Affinity == hcc.Affinity.ToString())); return CompareInt(hcc.Comparator, cnt, hcc.N); } case CardDefinitionCountInZoneCondition cdciz when subject is CardInstance defCard: { var defId = defCard.CardDefinitionId; var cnt = ctx.State.Players.Values .Where(p => cdciz.Ownership.ToLowerInvariant() == "any" || OwnershipMatchesForPlayer(cdciz.Ownership, p.AccountId, ctx.ActorId, ctx.State)) .SelectMany(p => cdciz.Zone.ToLowerInvariant() switch { "hand" => p.Hand.AsEnumerable(), "deck" => p.Deck.AsEnumerable(), "discard" => p.Discard.AsEnumerable(), "battlefield" => p.Field.AsEnumerable(), _ => Enumerable.Empty(), }) .Count(c => c.CardDefinitionId == defId); return CompareInt(cdciz.Comparator, cnt, cdciz.N); } case IsInRangeOfUnitCondition irru when subject is FieldCard fcIrru && fcIrru.Position.HasValue: { if (ctx.State.Board is null) return false; return ctx.State.Players.Values .SelectMany(p => p.Field.OfType()) .Where(u => u.InstanceId != fcIrru.InstanceId && u.Position.HasValue) .Where(u => irru.UnitType == "Unit" || u.CardType == irru.UnitType) .Where(u => { var op = FindCardOwner(ctx.State, u.InstanceId); return op is not null && OwnershipMatchesForPlayer(irru.Ownership, op.AccountId, ctx.ActorId, ctx.State); }) .Where(u => irru.UnitFilters is null || FiltersMatch(irru.UnitFilters, u, ctx)) .Any(u => { var d = fcIrru.Position!.Value.ManhattanDistance(u.Position!.Value); return d >= irru.Min && d <= irru.Max; }); } case TileOccupantCondition toc when subject is FieldCard fcToc && fcToc.Position.HasValue: { var tile = ctx.State.Board?.GetTile(fcToc.Position.Value); if (tile is null || tile.IsEmpty || tile.OccupantId is null || tile.OccupantOwner is null) return false; if (!OwnershipMatchesForPlayer(toc.Ownership, tile.OccupantOwner, ctx.ActorId, ctx.State)) return false; var occupant = ctx.State.Players.Values.SelectMany(p => p.Field) .FirstOrDefault(u => u.InstanceId == tile.OccupantId); if (occupant is null) return false; if (toc.UnitType != "Unit" && occupant.CardType != toc.UnitType) return false; return toc.UnitFilters is null || FiltersMatch(toc.UnitFilters, occupant, ctx); } case SurroundingTileCondition stc when subject is FieldCard fcStc && fcStc.Position.HasValue: { if (ctx.State.Board is null) return false; var cnt = ctx.State.Board.Tiles.Values .Where(t => { var d = fcStc.Position!.Value.ManhattanDistance(t.Coord); return d >= stc.Min && d <= stc.Max; }) .Count(t => stc.TileFilters is null || TileMatchesFilters(stc.TileFilters, t, ctx)); return CompareInt(stc.TileCountComparator, cnt, stc.TileCount); } case SPAccumulationCompareCondition spac: { var total = ctx.State.Rules.SpAccumulationPerTurn + player.SpAccumulationBonus; return CompareInt(spac.Comparator, total, spac.Value); } case CostOfCardsInHandCondition cochc: { var total = player.Hand .Where(c => (cochc.CardType is null || c.CardType == cochc.CardType) && (cochc.Affinity is null || c.Affinity == cochc.Affinity.ToString())) .Sum(c => cochc.CostType == "ST" ? c.StCost : c.SpCost); return CompareInt(cochc.Comparator, total, cochc.Value); } default: return true; } } private static bool CompareInt(Comparator c, int actual, int threshold) => c switch { Comparator.Equal => actual == threshold, Comparator.NotEqual => actual != threshold, Comparator.LessThan => actual < threshold, Comparator.LessThanOrEqual => actual <= threshold, Comparator.GreaterThan => actual > threshold, Comparator.GreaterThanOrEqual => actual >= threshold, _ => false, }; // ── 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, IsAdjacentToUnitMatchingFilter iau => card is FieldCard afc && afc.Position.HasValue && ctx.State.Board is not null && OrthogonalNeighbours(afc.Position.Value).Any(n => { var t = ctx.State.Board.GetTile(n); if (t is null || t.IsEmpty || t.OccupantId is null || t.OccupantOwner is null) return false; if (!OwnershipMatchesForPlayer(iau.Ownership, t.OccupantOwner, ctx.ActorId, ctx.State)) return false; var neighbour = ctx.State.Players.Values.SelectMany(p => p.Field).FirstOrDefault(u => u.InstanceId == t.OccupantId); if (neighbour is null) return false; return iau.UnitFilters is null || iau.UnitFilters.All(f => FilterMatches(f, neighbour, ctx)); }), IsAdjacentToTileMatchingFilter iat => card is FieldCard tfc && tfc.Position.HasValue && ctx.State.Board is not null && OrthogonalNeighbours(tfc.Position.Value).Any(n => { var t = ctx.State.Board.GetTile(n); return t is not null && (iat.TileFilters is null || TileMatchesFilters(iat.TileFilters, t, ctx)); }), _ => 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 t => occurrence.Kind == TriggerEventKind.DamageDealt && Own(t.SourceOwnership, occurrence, ownerId, state, uid) && UnitOwnerMatches(t.TargetOwnership, occurrence.Data?.TargetId, state, ownerId) && TriggerSourceMatchesFilter(t.SourceFilter, occurrence, state, ownerId), OnDamagePreventedTrigger t => occurrence.Kind == TriggerEventKind.DamagePrevented && UnitOwnerMatches(t.TargetOwnership, occurrence.Data?.TargetId, state, ownerId), BeforeDamageAppliedTrigger t => occurrence.Kind == TriggerEventKind.BeforeDamageApplied && Own(t.SourceOwnership, occurrence, ownerId, state, uid) && UnitOwnerMatches(t.TargetOwnership, occurrence.Data?.TargetId, state, ownerId), BeforeUnitDeathTrigger t => occurrence.Kind == TriggerEventKind.BeforeUnitDeath && UnitType(t.UnitType, occurrence.UnitType) && UnitOwnerMatches(t.Ownership, occurrence.Data?.TargetId, state, ownerId), 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 OwnershipMatchesForPlayer(scope, ownerId, referenceOwnerId, state); return true; } private static bool OwnershipMatchesForPlayer(string scope, string ownerId, string referenceOwnerId, GameState state) => scope.ToLowerInvariant() switch { "any" => true, "owner" or "self" or "ally" => state.AreAllies(ownerId, referenceOwnerId), "enemy" => !state.AreAllies(ownerId, referenceOwnerId), _ => true, }; private static bool TriggerSourceMatchesFilter(Filter? filter, TriggerOccurrence occ, GameState state, string ownerId) { if (filter is null) return true; if (occ.Data?.SourceId is not { Length: > 0 } sourceId) return false; var source = state.Players.Values.SelectMany(p => p.Field).FirstOrDefault(c => c.InstanceId == sourceId); if (source is null) return false; var tmpCtx = new AbilityContext { State = state, ActorId = ownerId, Source = source, EventData = occ.Data, }; return FilterMatches(filter, source, tmpCtx); } 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 ─────────────────────────────────────────── /// /// Applies a to a current stat value. /// Returns the new value (pre-clamping). The caller stores delta = newVal - oldVal /// so the reversal can be expressed as a simple Add(-delta). /// private static int ApplyStatOperator(int current, int amount, StatModOperator op) => op switch { StatModOperator.Subtract => current - amount, StatModOperator.Multiply => current * amount, StatModOperator.Divide => amount == 0 ? current : current / amount, StatModOperator.Percent => current + current * amount / 100, _ => current + amount, // Add (default) }; 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 }; // ── Intra-action continuation helpers ───────────────────────────────────── /// /// One step in an intra-action continuation: apply to the /// unit/player identified by (instanceId or accountId). /// private sealed class IntraActionStep { public string TargetRef { get; set; } = string.Empty; public string EffectsJson { get; set; } = "[]"; } /// /// Converts a resolved target object to a stable string reference used in /// and . /// private static string GetTargetRef(object target) => target switch { FieldCard fc => fc.InstanceId, CardInstance ci => ci.InstanceId, PlayerState ps => ps.AccountId, Coord c => $"tile:{c.X},{c.Y}", _ => string.Empty, }; /// /// Finds a target in by the string ref produced by /// . Returns a , , /// or boxed as object; null if not found. /// private static object? FindTargetByRef(GameState state, string targetRef) { if (string.IsNullOrEmpty(targetRef)) return null; if (state.Players.TryGetValue(targetRef, out var ps)) return ps; foreach (var p in state.Players.Values) { var c = (CardInstance?)( p.Field.FirstOrDefault(c => c.InstanceId == targetRef) ?? p.Hand.FirstOrDefault(c => c.InstanceId == targetRef) ?? p.Deck.FirstOrDefault(c => c.InstanceId == targetRef) ?? (CardInstance?)p.Discard.FirstOrDefault(c => c.InstanceId == targetRef)); if (c is not null) return c; if (p.ArchSpirit?.InstanceId == targetRef) return p.ArchSpirit; } if (targetRef.StartsWith("tile:")) { var parts = targetRef[5..].Split(','); if (parts.Length == 2 && int.TryParse(parts[0], out var tx) && int.TryParse(parts[1], out var ty)) return new Coord(tx, ty); } return null; } /// /// Builds the IntraActionContinuationJson stored in a pause model when an effect /// pauses mid-action. Captures: /// /// remaining effects on the current target (effects after the pausing one) /// all effects applied to each remaining target (targets after the current one) /// /// Returns null when there is nothing left within the current action. /// private static string? BuildIntraActionContinuationJson(object currentTarget, AbilityContext ctx) { var steps = new List(); // Remaining effects on the current target. if (ctx.CurrentActionAllEffects is { } allEffects && ctx.CurrentEffectIndex + 1 < allEffects.Length) { var remEffects = allEffects[(ctx.CurrentEffectIndex + 1)..]; steps.Add(new IntraActionStep { TargetRef = GetTargetRef(currentTarget), EffectsJson = JsonSerializer.Serialize(remEffects, _jsonOpts), }); } // All effects on every remaining target. if (ctx.CurrentActionTargets is { } allTargets && ctx.CurrentActionAllEffects is { } allEff2) { for (int rt = ctx.CurrentTargetIndex + 1; rt < allTargets.Length; rt++) { steps.Add(new IntraActionStep { TargetRef = GetTargetRef(allTargets[rt]), EffectsJson = JsonSerializer.Serialize(allEff2, _jsonOpts), }); } } return steps.Count > 0 ? JsonSerializer.Serialize(steps, _jsonOpts) : null; } /// /// Executes the intra-action continuation captured at pause time. /// Call this in resume methods after completing the effect-specific work and /// before executing the outer ContinuationActionsJson. /// /// /// Each can have a different effect list (e.g. the first step /// is only remaining effects on the originally-paused target, subsequent steps are the full /// effect list for each remaining target). If a nested pause occurs mid-replay we directly /// rebuild the next IntraActionContinuationJson from the remaining slice rather than /// relying on , which assumes a homogeneous /// per-target effect list and would produce wrong results here. /// private static void ApplyIntraActionContinuation( string? intraJson, DurationModel? actionDuration, AbilityContext ctx) { if (intraJson is null) return; IntraActionStep[]? steps; try { steps = JsonSerializer.Deserialize(intraJson, _jsonOpts); } catch { return; } if (steps is null) return; for (int si = 0; si < steps.Length; si++) { var step = steps[si]; var tgt = FindTargetByRef(ctx.State, step.TargetRef); if (tgt is null) continue; Effect[]? effects; try { effects = JsonSerializer.Deserialize(step.EffectsJson, _jsonOpts); } catch { continue; } if (effects is null) continue; for (int ei = 0; ei < effects.Length; ei++) { // Set position fields so ExecuteEffect has consistent context, but note that // we will override any IntraActionContinuationJson it writes (see below). ctx.CurrentEffectIndex = ei; ctx.CurrentActionAllEffects = effects; ctx.CurrentActionTargets = [tgt]; ctx.CurrentTargetIndex = 0; ctx.CurrentActionDuration = actionDuration; ExecuteEffect(effects[ei], tgt, actionDuration, ctx); if (ctx.State.HasPendingInteraction()) { // A nested pause was set. BuildIntraActionContinuationJson may have // already written an IntraActionContinuationJson based on the single-target // ctx snapshot above, which is incomplete. Override it with the precise // remaining slice: remaining effects on this step's target + remaining steps. var remEffects = effects[(ei + 1)..]; var newSteps = new List(); if (remEffects.Length > 0) newSteps.Add(new IntraActionStep { TargetRef = step.TargetRef, EffectsJson = JsonSerializer.Serialize(remEffects, _jsonOpts), }); for (int rs = si + 1; rs < steps.Length; rs++) newSteps.Add(steps[rs]); SetPendingIntraActionContinuation(ctx.State, newSteps.Count > 0 ? JsonSerializer.Serialize(newSteps, _jsonOpts) : null); return; } } if (ctx.State.HasPendingInteraction()) { // Pause between effects (edge case). Remaining = steps after si. var remSteps = new List(); for (int rs = si + 1; rs < steps.Length; rs++) remSteps.Add(steps[rs]); SetPendingIntraActionContinuation(ctx.State, remSteps.Count > 0 ? JsonSerializer.Serialize(remSteps, _jsonOpts) : null); return; } } } /// /// Overwrites the IntraActionContinuationJson on whichever pause model is currently /// set in . Used by to /// replace any stale value written by . /// private static void SetPendingIntraActionContinuation(GameState state, string? intraJson) { if (state.PendingTilePick is { } tp) { tp.IntraActionContinuationJson = intraJson; return; } if (state.PendingPlayerPick is { } pp) { pp.IntraActionContinuationJson = intraJson; return; } if (state.PendingRevealChoicePick is { } rcp) { rcp.IntraActionContinuationJson = intraJson; } } /// 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, Label = LabelFromReversal(reversal), }); } /// /// 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, Label = LabelFromTick(tickEffect), }); } /// /// Generates a human-readable label for the original applied effect, /// given the stored reversal effect. E.g., ModifyDamageEffect{-2} → "ATK +2". /// private static string LabelFromReversal(Effect reversal) => reversal switch { ModifyHealthEffect e => $"HP {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyDefenseEffect e => $"DEF {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyDamageEffect e => $"ATK {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyMPEffect e => $"MP {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyMinAttackRangeEffect e => $"Min Range {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyMaxAttackRangeEffect e => $"Max Range {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyCostEffect e => LabelCostReversal(e), ModifySPAccumulationEffect e => $"SP Acc {FormatDelta(-(e.Amount.Fixed ?? 0))}", ModifyCardsDrawnPerTurnEffect e => $"Draw {FormatDelta(-(e.Amount.Fixed ?? 0))}/T", SetMovementTypeEffect _ => "Move Type Changed", SetAttackRangeEffect _ => "ATK Range Changed", SetCanMoveEffect e => e.Value ? "Rooted" : "Move Granted", SetCanAttackEffect e => e.Value ? "Can't Attack" : "Atk Granted", SetCanDefendEffect e => e.Value ? "Can't Defend" : "Def Granted", SetCanBeAttackedEffect e => e.Value ? "Untargetable" : "Targetable", SetCanBeBlockedEffect e => e.Value ? "Unblockable" : "Blockable", SetCanBeObstructedEffect e => e.Value ? "Unobstructed" : "Obstructed", SetCanUseAbilityEffect e => e.Value ? "Ability Off" : "Ability On", SetCanBeSacrificedEffect e => e.Value ? "No Sacrifice" : "Sacrifice OK", SetCanDrawCardsEffect e => e.Value ? "No Draw" : "Draw Restored", SetAccumulatesSPEffect e => e.Value ? "No SP Gain" : "SP Gain", SetCanChannelSpiritEffect e => e.Value ? "No Channel" : "Channel OK", SetCanSacrificeSpiritEffect e => e.Value ? "No Sacrifice" : "Sacrifice OK", SetCanAscendArchSpiritEffect e => e.Value ? "No Ascend" : "Ascend OK", SetCanTransitionArchSpiritEffect e => e.Value ? "No Transition" : "Transition OK", SetCanChannelRepentanceEffect e => e.Value ? "No Repentance" : "Repentance OK", SetCanChannelInstinctEffect e => e.Value ? "No Instinct" : "Instinct OK", SetCanChannelRuinEffect e => e.Value ? "No Ruin" : "Ruin OK", SetCanChannelTerramorphaMonoEffect e => e.Value ? "No T-Mono" : "T-Mono OK", SetCanChannelTerramorphaDiEffect e => e.Value ? "No T-Di" : "T-Di OK", SetCanChannelTerramorphaTriEffect e => e.Value ? "No T-Tri" : "T-Tri OK", AddAbilityEffect e => $"Bonus: {e.AbilityDef.Name ?? "Ability"}", RemoveAbilityEffect e => $"Stripped: {e.AbilityRef}", EnableAbilityEffect e => $"Ability Off: {e.AbilityRef}", DisableAbilityEffect e => $"Ability On: {e.AbilityRef}", AddGenusEffect e => $"Genus: -{e.Tag}", RemoveGenusEffect e => $"Genus: +{e.Tag}", SetAffinityEffect _ => "Affinity Changed", SetBaseAffinity1Effect _ => "Affinity Overridden", SetBaseAffinity2Effect _ => "Affinity Overridden", ClearPreventDeathEffect _ => "Death Shield", ClearPreventNextDamageEffect _ => "Damage Block", SetFixedSacrificeReturnEffect _ => "Sacrifice Override", SetHealthMinimumEffect e => $"HP Min {e.Minimum}", _ => reversal.GetType().Name.Replace("Effect", ""), }; private static string LabelFromTick(Effect tick) => tick switch { DealDamageEffect e => $"Burn {e.Amount.Fixed ?? 0}/T", HealEffect e => $"Regen {e.Amount.Fixed ?? 0}/T", _ => tick.GetType().Name.Replace("Effect", ""), }; private static string FormatDelta(int n) => n >= 0 ? $"+{n}" : $"{n}"; private static string LabelCostReversal(ModifyCostEffect e) { var parts = new System.Collections.Generic.List(); if (e.Sp is { } sp && sp != 0) parts.Add($"SP {FormatDelta(-sp)}"); if (e.St is { } st && st != 0) parts.Add($"ST {FormatDelta(-st)}"); return parts.Count > 0 ? string.Join(", ", parts) : "Cost Changed"; } /// /// 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 = (CardInstance?)state.Players.Values .SelectMany(p => p.Field) .FirstOrDefault(c => c.InstanceId == ae.TargetRef) ?? state.Players.Values .Select(p => p.ArchSpirit) .FirstOrDefault(a => a?.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.UntilEndOfSequence: // handled by ExpireEndOfSequenceEffects after top-level action resolution 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 GameState ExpireEndOfSequenceEffects(GameState state) { var toRemove = new List(); foreach (var ae in state.ActiveEffects) { TrackedDuration? td; try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } catch { continue; } if (td?.Duration?.Type != DurationType.UntilEndOfSequence) continue; if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); toRemove.Add(ae); } 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, including ArchSpirit) 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) ?? (p.ArchSpirit?.InstanceId == ae.TargetRef ? p.ArchSpirit : null)); 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. /// // Returns all units currently on the board for a given player, including ArchSpirit. private static IEnumerable BoardUnits(PlayerState player) { if (player.ArchSpirit?.Position.HasValue == true) yield return player.ArchSpirit; foreach (var fc in player.Field.OfType().Where(f => f.Position.HasValue)) yield return fc; } // Finds the owner account-id of a unit, checking ArchSpirit and Field. private static string? FindUnitOwner(GameState state, string unitId) { foreach (var (oid, pl) in state.Players) { if (pl.ArchSpirit?.InstanceId == unitId) return oid; if (pl.Field.Any(c => c.InstanceId == unitId)) return oid; } return null; } 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 BoardUnits(player) .Where(f => 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 => BoardUnits(p)) .FirstOrDefault(f => f.InstanceId == movingUnitId); if (movingUnit is null) return state; var movingOwnerId = FindUnitOwner(state, movingUnitId); 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 BoardUnits(pl) .Where(f => 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 BoardUnits(player) .Where(f => 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. var newUnitOwnerId = FindUnitOwner(state, newUnitId); 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 BoardUnits(pl) .Where(f => 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; } /// /// Re-applies aura effects for units belonging to that are /// already inside an aura's range at the start of their turn. /// Called after the turn-start stat reset (CurrentMp/CurrentDefense restore) so that /// per-turn bonuses like ModifyMP(Current) are re-granted on top of the fresh base values. /// Stale tracked effects for each source→target pair are removed WITHOUT reversal because /// the underlying Current stats were already reset by the turn transition. /// public static GameState ReapplyAurasAtTurnStart(GameState state, string activePlayerId) { if (state.Board is null) return state; var activePlayerUnits = BoardUnits(state.Players[activePlayerId]).ToList(); if (activePlayerUnits.Count == 0) return state; foreach (var (auraOwnerId, auraPlayer) in state.Players) foreach (var auraUnit in BoardUnits(auraPlayer).ToList()) { foreach (var def in ParseAbilities(auraUnit.AbilitiesJson) .Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null)) { int min = def.AuraRange!.Min, max = def.AuraRange.Max; var auraPos = auraUnit.Position!.Value; foreach (var target in activePlayerUnits .Where(t => t.InstanceId != auraUnit.InstanceId)) { int dist = auraPos.ManhattanDistance(target.Position!.Value); if (dist < min || dist > max) continue; // Strip stale tracked effects for this source→target pair without reversal. // Current stats (CurrentMp, CurrentDefense) were already reset by the // turn transition, so applying the reversal would incorrectly subtract. state.ActiveEffects.RemoveAll(ae => ae.SourceInstanceId == auraUnit.InstanceId && ae.TargetRef == target.InstanceId); // Re-apply fresh — same path as when the unit entered the aura. ApplyAuraEffects(state, auraOwnerId, auraUnit, def, target.InstanceId); } } } 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 => BoardUnits(p)) .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 BoardUnits(player) .Where(f => 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. var leavingOwnerId = FindUnitOwner(state, leavingUnitId); 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 BoardUnits(pl) .Where(f => 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. /// Supports both ActionGroup (modern) and legacy flat Actions. /// private static void ApplyAuraEffects( GameState state, string auraOwnerId, FieldCard auraUnit, AbilityDefinition def, string targetUnitId) { // 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 }; var forceDuration = def.Duration ?? fallback; var actions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.AuraRange, forceDuration); if (actions is not { Length: > 0 }) return; ExecuteActions(actions, ctx, clientTargets: null, restrictTargets: new HashSet { targetUnitId }, forceDuration: forceDuration); } /// /// 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) { 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); // Execute one-shot OnEnterAuraActions (not duration-tracked, fired once on enter). if (def.OnEnterAuraActions is not null) { var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit }; var resolved = ResolveActionGroup(def.OnEnterAuraActions, ctx, abilityIndex: 0, range: def.AuraRange, forceDuration: null, continuationActions: []); if (resolved is not null) ExecuteActions(resolved, ctx, clientTargets: null, restrictTargets: new HashSet { 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); // Execute one-shot OnLeaveAuraActions (fired once on leave, regardless of ClearOnLeave). if (def.OnLeaveAuraActions is not null) { var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit }; var resolved = ResolveActionGroup(def.OnLeaveAuraActions, ctx, abilityIndex: 0, range: null, forceDuration: null, continuationActions: []); if (resolved is not null) ExecuteActions(resolved, ctx, clientTargets: null, restrictTargets: new HashSet { targetUnitId }); } } } }