namespace SOR.Game.Abilities;
using System.Text.Json;
using SOR.Database.Enums;
using SOR.Game.Abilities.Models;
using SOR.Game.Grid;
///
/// Evaluates and resolves ability activations and triggered ability firings.
///
/// Design:
/// • GameEngine delegates directly to the static methods here.
/// • All mutation is on GameState (pure — no DB access).
/// • Triggered abilities are fired inline during engine mutations via FireTrigger.
///
public static class AbilitySystem
{
// ── JSON options ───────────────────────────────────────────────────────────
private static readonly JsonSerializerOptions _jsonOpts = new()
{
PropertyNameCaseInsensitive = true,
Converters =
{
new System.Text.Json.Serialization.JsonStringEnumConverter(),
// Handle polymorphic deserialization when $type is not the first property.
// The default [JsonPolymorphic] behavior requires $type first for abstract
// base types; admin-tool JSON does not guarantee that ordering.
new EffectPolymorphicConverter(),
new ConditionPolymorphicConverter(),
new TriggerPolymorphicConverter(),
new FilterPolymorphicConverter(),
},
};
// ── Parsing ────────────────────────────────────────────────────────────────
public static AbilityDefinition[] ParseAbilities(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
return JsonSerializer.Deserialize(json, _jsonOpts) ?? [];
}
public static Models.Action[] ParseEffects(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
return JsonSerializer.Deserialize(json, _jsonOpts) ?? [];
}
// ── Active ability activation ──────────────────────────────────────────────
///
/// Entry point for a player manually activating an Active ability on one of
/// their units. Validates conditions, pays cost, resolves targets and effects.
///
public static GameState ActivateAbility(
GameState state,
string actorId,
string sourceInstanceId,
int abilityIndex,
IReadOnlyList? clientTargets)
{
var player = state.Players[actorId];
var source = player.Field.OfType()
.FirstOrDefault(f => f.InstanceId == sourceInstanceId)
?? 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 };
if (def.ActivationConditions is { Length: > 0 })
foreach (var cond in def.ActivationConditions)
if (!EvaluateCondition(cond, ctx, source))
throw new GameException("ABILITY_CONDITION_NOT_MET");
if (def.Cost is { Length: > 0 })
PayCost(def.Cost, ctx);
source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1;
ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range);
return state;
}
// ── Triggered ability firing ───────────────────────────────────────────────
///
/// Resolve the EffectsJson action list on a non-unit card (Repentance, Instinct, Ruin)
/// immediately when it is channeled. The card itself is the source in the context.
///
public static GameState FireCardEffects(GameState state, string actorId, CardInstance card,
IReadOnlyList? clientTargets = null)
{
var actions = ParseEffects(card.EffectsJson);
if (actions.Length == 0) return state;
var ctx = new AbilityContext { State = state, ActorId = actorId, Source = card };
ExecuteActions(actions, ctx, clientTargets, requireClientTargets: true);
return state;
}
///
/// Scans every battlefield unit for Triggered abilities matching the occurrence
/// and fires each matching one. Called inline from GameEngine mutation methods.
///
public static GameState FireTrigger(GameState state, TriggerOccurrence occurrence)
{
foreach (var (ownerId, player) in state.Players)
{
var units = player.Field.OfType().ToList(); // snapshot
foreach (var unit in units)
{
var abilities = ParseAbilities(unit.AbilitiesJson);
for (int i = 0; i < abilities.Length; i++)
{
var def = abilities[i];
if (def.Type != AbilityType.Triggered) continue;
if (def.TriggerEvent is null) continue;
if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId, unit)) continue;
var ctx = new AbilityContext
{
State = state,
ActorId = ownerId,
Source = unit,
EventData = occurrence.Data,
};
if (def.ActivationConditions is { Length: > 0 })
if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, unit)))
continue;
ExecuteActions(def.Actions, ctx, clientTargets: null);
}
}
}
// ── Check pending deferred effects ────────────────────────────────────
var toFire = state.PendingDeferredEffects
.Where(p =>
{
TriggerEvent? t;
try { t = JsonSerializer.Deserialize(p.TriggerJson, _jsonOpts); }
catch { return false; }
return t is not null && TriggerMatches(t, occurrence, state, p.OwnerAccountId);
})
.ToList();
foreach (var pending in toFire)
{
state.PendingDeferredEffects.Remove(pending);
Effect[]? deferredEffects;
try { deferredEffects = JsonSerializer.Deserialize(pending.EffectsJson, _jsonOpts); }
catch { continue; }
if (deferredEffects is null) continue;
var tgt = FindDeferredTarget(state, pending.TargetRef);
if (tgt is null) continue;
var dSrc = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
var dCtx = new AbilityContext { State = state, ActorId = pending.OwnerAccountId, Source = dSrc };
foreach (var eff in deferredEffects)
ExecuteEffect(eff, tgt, DurationModel.Instant, dCtx);
}
return state;
}
private static object? FindDeferredTarget(GameState state, string targetRef)
{
foreach (var player in state.Players.Values)
{
var ci = (CardInstance?)(
player.Field.FirstOrDefault(c => c.InstanceId == targetRef)
?? player.Hand.FirstOrDefault(c => c.InstanceId == targetRef)
?? player.Deck.FirstOrDefault(c => c.InstanceId == targetRef)
?? player.Discard.FirstOrDefault(c => c.InstanceId == targetRef));
if (ci is not null) return ci;
if (player.AccountId == targetRef) return player;
}
return null;
}
///
/// At the start of each turn: for every Ruin on the battlefield whose tile is occupied
/// by a Spirit or ArchSpirit, pick ONE of the Ruin's OnRuinActivationTrigger abilities
/// at random and execute it. Then fire RuinActivation for any observer cards.
///
public static GameState FireRuinAbilities(GameState state)
{
foreach (var (ownerId, player) in state.Players)
{
var ruins = player.Field
.OfType()
.Where(c => c.CardType == "Ruin" && c.Position.HasValue)
.ToList();
foreach (var ruin in ruins)
{
var tile = state.Board?.GetTile(ruin.Position!.Value);
if (tile?.OccupantId is null) continue;
// Only fires if a Spirit or ArchSpirit is on the tile.
var occupantType = FindUnitType(state, tile.OccupantId);
if (occupantType is not ("Spirit" or "ArchSpirit" or "SpiritToken")) continue;
var abilities = ParseAbilities(ruin.AbilitiesJson);
var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = ruin };
var eligible = abilities
.Where(a => a.Type == AbilityType.Triggered
&& a.TriggerEvent is OnRuinActivationTrigger)
.Where(a => a.ActivationConditions is not { Length: > 0 }
|| a.ActivationConditions.All(c => EvaluateCondition(c, ctx, ruin)))
.ToList();
if (eligible.Count == 0) continue;
// Select exactly one ability at random.
var chosen = eligible[Random.Shared.Next(eligible.Count)];
ExecuteActions(chosen.Actions, ctx, clientTargets: null);
// Notify observer cards that the ruin activated.
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.RuinActivation,
ActorId = ownerId,
Data = new TriggerEventData
{
SourceId = ruin.InstanceId,
TargetId = tile.OccupantId,
},
});
}
}
return state;
}
private static string? FindUnitType(GameState state, string instanceId)
{
foreach (var player in state.Players.Values)
{
var c = player.Field.FirstOrDefault(x => x.InstanceId == instanceId)
?? player.ArchSpirit as CardInstance;
if (c?.InstanceId == instanceId) return c.CardType;
}
return null;
}
// ── Cost payment ──────────────────────────────────────────────────────────
private static void PayCost(CostEntry[] costs, AbilityContext ctx)
{
var player = ctx.State.Players[ctx.ActorId];
foreach (var cost in costs)
{
switch (cost.Type)
{
case CostType.SpiritPoints:
if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP");
player.CurrentSp -= cost.Amount;
break;
case CostType.SacrificeTokens:
if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST");
player.CurrentSt -= cost.Amount;
break;
case CostType.DiscardFromHand:
{
var candidates = player.Hand
.Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx))
.Take(cost.Amount).ToList();
if (candidates.Count < cost.Amount)
throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD");
foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); }
break;
}
case CostType.MillTopOfDeck:
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
{
var top = player.Deck[^1];
player.Deck.RemoveAt(player.Deck.Count - 1);
player.Discard.Add(top);
}
break;
case CostType.MillBottomOfDeck:
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
{
var bottom = player.Deck[0];
player.Deck.RemoveAt(0);
player.Discard.Add(bottom);
}
break;
case CostType.DealDamageToOwnArchSpirit:
if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT");
ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx);
break;
case CostType.DealDamageToOwnSpirit:
{
var spirit = player.Field.OfType()
.FirstOrDefault(f => !f.IsLeader
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx);
break;
}
case CostType.SendSpiritFromBattlefieldToDiscard:
{
var spirit = player.Field.OfType()
.FirstOrDefault(f => !f.IsLeader
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
ctx.State.Board?.RemoveUnit(spirit.InstanceId);
player.Field.Remove(spirit);
player.Discard.Add(spirit);
break;
}
}
}
}
// ── Action execution ──────────────────────────────────────────────────────
private static void ExecuteActions(
Models.Action[] actions,
AbilityContext ctx,
IReadOnlyList? clientTargets,
bool requireClientTargets = false,
AbilityRange? activationRange = null,
HashSet? restrictTargets = null,
DurationModel? forceDuration = null)
{
for (int i = 0; i < actions.Length; i++)
ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i,
requireClientTargets, activationRange, restrictTargets, forceDuration);
}
private static void ExecuteSingleAction(
Models.Action action,
AbilityContext ctx,
IReadOnlyList? clientTargets,
int actionIndex,
bool requireClientTargets = false,
AbilityRange? activationRange = null,
HashSet? restrictTargets = null,
DurationModel? forceDuration = null)
{
// Source-level conditions (Subject != "Target"): gate the whole action.
if (action.Conditions is { Length: > 0 })
foreach (var cond in action.Conditions)
if (cond.Subject != "Target" && !EvaluateCondition(cond, ctx, ctx.Source!))
return;
var resolved = ResolveTargets(
action.Target, ctx, clientTargets, actionIndex, requireClientTargets, activationRange, restrictTargets);
ctx.ResolvedTargets[actionIndex] = resolved;
// Target-level conditions (Subject == "Target"): filter per target.
var targetConds = action.Conditions?.Where(c => c.Subject == "Target").ToArray();
var duration = forceDuration ?? action.Duration;
foreach (var target in resolved)
{
if (targetConds is { Length: > 0 })
{
// Temporarily expose current target so EvaluateCondition resolves "Target" correctly.
ctx.ResolvedTargets[actionIndex] = [target];
bool passes = targetConds.All(c => EvaluateCondition(c, ctx, target));
ctx.ResolvedTargets[actionIndex] = resolved;
if (!passes) continue;
}
foreach (var effect in action.Effects)
ExecuteEffect(effect, target, duration, ctx);
}
}
// ── Target resolution ─────────────────────────────────────────────────────
private static List ResolveTargets(
TargetSelector selector,
AbilityContext ctx,
IReadOnlyList? clientTargets,
int actionIndex,
bool requireClientTargets = false,
AbilityRange? activationRange = null,
HashSet? restrictTargets = null)
{
var state = ctx.State;
if (selector.Type == TargetType.Player)
{
return selector.Ownership switch
{
TargetOwnership.Owner or TargetOwnership.Self =>
[state.Players[ctx.ActorId]],
TargetOwnership.Enemy =>
state.Players.Values.Where(p => p.AccountId != ctx.ActorId).Cast().ToList(),
_ => state.Players.Values.Cast().ToList(),
};
}
if (selector.Type == TargetType.Tile)
{
if (clientTargets is null) return [];
var tiles = clientTargets
.Where(t => t.ActionIndex == actionIndex && t.Coord is not null)
.Select(t => (object)new Coord(t.Coord!.X, t.Coord!.Y))
.ToList();
if (activationRange is not null)
tiles = FilterTargetsByAbilityRange(tiles, ctx, activationRange);
return tiles;
}
var candidates = BuildCandidates(selector, state, ctx.ActorId);
// ExactSelf: narrow to the exact unit instance that owns this ability.
if (selector.Ownership == TargetOwnership.ExactSelf && ctx.Source is not null)
candidates = candidates.Where(c => c.InstanceId == ctx.Source.InstanceId).ToList();
// Passive apply-to-new-unit: restrict to a specific subset of candidates.
if (restrictTargets is not null)
candidates = candidates.Where(c => restrictTargets.Contains(c.InstanceId)).ToList();
if (selector.Filters is { Length: > 0 })
candidates = candidates.Where(c => FiltersMatch(selector.Filters, c, ctx)).ToList();
HashSet clientIds = [];
if (clientTargets is not null)
{
clientIds = clientTargets
.Where(t => t.ActionIndex == actionIndex && t.InstanceId is not null)
.Select(t => t.InstanceId!).ToHashSet();
if (clientIds.Count > 0)
candidates = candidates.Where(c => clientIds.Contains(c.InstanceId)).ToList();
}
else if (requireClientTargets && !selector.Count.All && !selector.Count.UpTo && selector.Count.N > 0)
{
// Mandatory explicit-target action with no client selection provided — fail fast.
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)
throw new GameException("INSUFFICIENT_TARGETS");
candidates = candidates.Take(needed).ToList();
}
return candidates.Cast().ToList();
}
private static List FilterTargetsByAbilityRange(
List targets, AbilityContext ctx, AbilityRange range)
{
if (ctx.Source is not FieldCard source || !source.Position.HasValue)
return [];
return targets.Where(t => t switch
{
FieldCard fc when fc.Position.HasValue =>
IsTargetInAbilityRange(ctx.State, source.Position.Value, fc.Position.Value, range),
Coord coord =>
IsTargetInAbilityRange(ctx.State, source.Position.Value, coord, range),
_ => false,
}).ToList();
}
private static bool IsTargetInAbilityRange(
GameState state, Coord sourcePos, Coord targetPos, AbilityRange range)
{
int dist = sourcePos.ManhattanDistance(targetPos);
if (dist < range.Min || dist > range.Max)
return false;
if (range.LinearOnly)
{
int dx = Math.Abs(targetPos.X - sourcePos.X);
int dy = Math.Abs(targetPos.Y - sourcePos.Y);
if (!(dx == 0 || dy == 0 || dx == dy))
return false;
}
if (range.RequiresLos)
{
var board = state.Board;
if (board is null) return false;
var occupancy = board.BuildOccupancyMap();
occupancy.Remove(sourcePos);
if (!LineOfSight.HasLos(board, sourcePos, targetPos, occupancy))
return false;
}
return true;
}
private static List BuildCandidates(
TargetSelector selector, GameState state, string actorId)
{
var all = new List();
IEnumerable ownerIds = selector.Ownership switch
{
TargetOwnership.Owner or TargetOwnership.Self or TargetOwnership.ExactSelf => [actorId],
TargetOwnership.Enemy => state.Players.Keys.Where(k => k != actorId),
TargetOwnership.Ally => state.Players.Keys.Where(k => k != actorId),
_ => state.Players.Keys,
};
foreach (var ownerId in ownerIds)
{
var p = state.Players[ownerId];
switch (selector.Scope)
{
case TargetScope.Battlefield:
all.AddRange(p.Field);
if (p.ArchSpirit is not null) all.Add(p.ArchSpirit);
break;
case TargetScope.Hand: all.AddRange(p.Hand); break;
case TargetScope.Deck: all.AddRange(p.Deck); break;
case TargetScope.Discard: all.AddRange(p.Discard); break;
case TargetScope.AnyZone:
all.AddRange(p.Hand); all.AddRange(p.Deck);
all.AddRange(p.Field); all.AddRange(p.Discard);
if (p.ArchSpirit is not null) all.Add(p.ArchSpirit);
break;
}
}
return selector.Type switch
{
TargetType.ArchSpirit => all.Where(c => c.CardType == "ArchSpirit").ToList(),
TargetType.Spirit => all.Where(c => c.CardType == "Spirit").ToList(),
TargetType.SpiritToken => all.Where(c => c.CardType == "SpiritToken").ToList(),
TargetType.Ruin => all.Where(c => c.CardType == "Ruin").ToList(),
TargetType.Unit => all.Where(c =>
c.CardType is "ArchSpirit" or "Spirit" or "SpiritToken").ToList(),
_ => all,
};
}
// ── Effect execution ──────────────────────────────────────────────────────
private static void ExecuteEffect(
Effect effect, object target, DurationModel? duration, AbilityContext ctx)
{
switch (effect)
{
// ── §5.1 Stat modification ─────────────────────────────────────────
case ModifyHealthEffect mh when target is CardInstance ci:
{
int amt = ResolveValue(mh.Amount, ctx);
if (mh.StatTarget == StatTarget.Current)
{
ci.CurrentHealth = (ci.CurrentHealth ?? 0) + amt;
if (ci.MaxHealth.HasValue)
ci.CurrentHealth = Math.Min(ci.CurrentHealth.Value, ci.MaxHealth.Value);
if (ci.CurrentHealth <= 0) KillUnit(ci, ctx);
}
else
{
ci.MaxHealth = (ci.MaxHealth ?? 0) + amt;
if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth;
}
TrackEffect(new ModifyHealthEffect { Amount = V(-amt), StatTarget = mh.StatTarget },
ci.InstanceId, duration, ctx);
break;
}
case ModifyDefenseEffect md when target is CardInstance ci:
{
int amt = ResolveValue(md.Amount, ctx);
if (md.StatTarget == StatTarget.Current)
ci.CurrentDefense = Math.Max(0, (ci.CurrentDefense ?? 0) + amt);
else
ci.MaxDefense = (ci.MaxDefense ?? 0) + amt;
TrackEffect(new ModifyDefenseEffect { Amount = V(-amt), StatTarget = md.StatTarget },
ci.InstanceId, duration, ctx);
break;
}
case ModifyDamageEffect mdam when target is CardInstance ci:
{
int amt = ResolveValue(mdam.Amount, ctx);
ci.Damage = Math.Max(0, (ci.Damage ?? 0) + amt);
TrackEffect(new ModifyDamageEffect { Amount = V(-amt) }, ci.InstanceId, duration, ctx);
break;
}
case ModifyMPEffect mmp when target is CardInstance ci:
{
int amt = ResolveValue(mmp.Amount, ctx);
if (mmp.StatTarget == StatTarget.Current && ci is FieldCard fc)
fc.CurrentMp = Math.Max(0, fc.CurrentMp + amt);
else
ci.MaxMp = Math.Max(0, (ci.MaxMp ?? 0) + amt);
TrackEffect(new ModifyMPEffect { Amount = V(-amt), StatTarget = mmp.StatTarget },
ci.InstanceId, duration, ctx);
break;
}
case SetMovementTypeEffect smt when target is CardInstance ci:
{
var orig = ci.MovementType;
ci.MovementType = smt.MovementType;
if (orig.HasValue)
TrackEffect(new SetMovementTypeEffect { MovementType = orig.Value },
ci.InstanceId, duration, ctx);
break;
}
case SetAttackRangeEffect sar when target is CardInstance ci:
{
int? origMin = ci.MinAttackRange, origMax = ci.MaxAttackRange;
ci.MinAttackRange = sar.Min; ci.MaxAttackRange = sar.Max;
if (origMin.HasValue && origMax.HasValue)
TrackEffect(new SetAttackRangeEffect { Min = origMin.Value, Max = origMax.Value },
ci.InstanceId, duration, ctx);
break;
}
case 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;
}
// ── §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) { 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);
}
break;
}
case SearchDeckEffect sde:
{
var ps = ResolvePlayerForEffect("Owner", ctx);
var found = ps.Deck
.Where(c => sde.Filters is null || FiltersMatch(sde.Filters, c, ctx))
.Take(sde.Count).ToList();
foreach (var card in found)
{
ps.Deck.Remove(card);
if (sde.ThenAction is not null)
{
var innerCtx = new AbilityContext
{ State = ctx.State, ActorId = ctx.ActorId, Source = ctx.Source };
foreach (var eff in sde.ThenAction.Effects)
ExecuteEffect(eff, card, sde.ThenAction.Duration, innerCtx);
}
else
{
ps.Hand.Add(card);
}
}
break;
}
case ShuffleDeckEffect sde:
{
var ps = ResolvePlayerForEffect(sde.Player, ctx);
var rng = new Random();
for (int i = ps.Deck.Count - 1; i > 0; i--)
{
int j = rng.Next(i + 1);
(ps.Deck[i], ps.Deck[j]) = (ps.Deck[j], ps.Deck[i]);
}
break;
}
case RevealCardsEffect when target is CardInstance ci:
ci.IsRevealed = true;
break;
case PlaceOnDeckEffect pod when target is CardInstance ci:
{
var owner = FindCardOwner(ctx.State, ci.InstanceId);
if (owner is not null)
{
RemoveFromAllZones(owner, ci, ctx.State.Board);
PlaceInDeck(owner, ci, pod.Position);
}
break;
}
// ── §5.8 Combat / damage ──────────────────────────────────────────
case DealDamageEffect dd when target is CardInstance ci:
ApplyDamageToUnit(ci, ResolveValue(dd.Amount, ctx), dd.BypassDefense, ctx);
break;
case HealEffect he when target is CardInstance ci:
ci.CurrentHealth = Math.Min(ci.MaxHealth ?? int.MaxValue,
(ci.CurrentHealth ?? 0) + ResolveValue(he.Amount, ctx));
break;
case DealDamageToSelfEffect ddself:
if (ctx.Source is not null)
ApplyDamageToUnit(ctx.Source, ResolveValue(ddself.Amount, ctx),
ddself.BypassDefense, ctx);
break;
case DOTEffect dot when target is CardInstance ci:
TrackTick(new DealDamageEffect { Amount = V(ResolveValue(dot.Amount, ctx)), BypassDefense = dot.BypassDefense },
ci.InstanceId, dot.Duration, ctx);
break;
case HOTEffect hot when target is CardInstance ci:
TrackTick(new HealEffect { Amount = V(ResolveValue(hot.Amount, ctx)) },
ci.InstanceId, hot.Duration, ctx);
break;
// ── §5.9 Displacement ─────────────────────────────────────────────
case PushUnitEffect pu when target is FieldCard fc2:
DisplaceUnit(fc2, pu.Tiles, fromSource: true, ctx); break;
case PullUnitEffect pull when target is FieldCard fc3:
DisplaceUnit(fc3, pull.Tiles, fromSource: false, ctx); break;
case DisplaceUnitEffect du when target is FieldCard fc5:
{
if (!fc5.Position.HasValue || ctx.State.Board is null) break;
var (dx, dy) = ParseDirection(du.Direction);
if (dx == 0 && dy == 0) break;
var oldPos5 = fc5.Position.Value;
var newPos5 = new Coord(oldPos5.X + dx * du.Tiles, oldPos5.Y + dy * du.Tiles);
if (!ctx.State.Board.IsInBounds(newPos5) || !ctx.State.Board.GetTile(newPos5)!.IsEmpty) break;
var duOwner = ctx.State.Players.Values
.FirstOrDefault(p => p.Field.Any(f => f.InstanceId == fc5.InstanceId));
if (duOwner is null) break;
ctx.State.Board.RemoveUnit(fc5.InstanceId);
ctx.State.Board.PlaceUnit(newPos5, fc5.InstanceId, duOwner.AccountId);
fc5.Position = newPos5;
EvaluateAuraTransitions(ctx.State, fc5.InstanceId, oldPos5, newPos5);
break;
}
// ── §5.10 Control ─────────────────────────────────────────────────
case TakeControlEffect when target is FieldCard fc4:
{
var originalOwner = FindCardOwner(ctx.State, fc4.InstanceId);
if (originalOwner is not null) originalOwner.Field.Remove(fc4);
ctx.State.Players[ctx.ActorId].Field.Add(fc4);
break;
}
case GrantMovementControlEffect gmc when target is FieldCard fc6:
{
fc6.CurrentMp += gmc.N;
TrackEffect(new ModifyMPEffect { Amount = V(-gmc.N), StatTarget = StatTarget.Current },
fc6.InstanceId, duration, ctx);
break;
}
case SetFixedSacrificeReturnEffect sfsr when target is CardInstance ci:
{
int? orig = ci.FixedSacrificeReturn;
// Negative StAmount is a sentinel meaning "clear override" (used in reversals).
ci.FixedSacrificeReturn = sfsr.StAmount >= 0 ? sfsr.StAmount : (int?)null;
TrackEffect(new SetFixedSacrificeReturnEffect { StAmount = orig ?? -1 },
ci.InstanceId, duration, ctx);
break;
}
// ── §5.11 Token summoning ─────────────────────────────────────────
case SummonTokenEffect ste when target is Coord coord:
{
var board = ctx.State.Board;
if (board is null) break;
var tile = board.GetTile(coord);
if (tile is null || !tile.IsEmpty) break;
// TokenDefJson is deserialized directly as CardInstance field values.
var proto = JsonSerializer.Deserialize(ste.TokenDefJson, _jsonOpts);
if (proto is null) break;
proto.InstanceId = Guid.NewGuid().ToString("N")[..8];
proto.CardType = "SpiritToken";
var tokenField = CreateTokenFieldCard(proto, coord);
ctx.State.Players[ctx.ActorId].Field.Add(tokenField);
board.PlaceUnit(coord, tokenField.InstanceId, ctx.ActorId);
FireTrigger(ctx.State, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitEnterBattlefield,
ActorId = ctx.ActorId,
UnitType = "SpiritToken",
Data = new TriggerEventData { SourceId = tokenField.InstanceId },
});
EvaluateAurasOnEnter(ctx.State, tokenField.InstanceId);
ApplyPassivesForSource(ctx.State, tokenField.InstanceId, ctx.ActorId);
ApplyPassivesToNewTarget(ctx.State, tokenField.InstanceId);
break;
}
// ── §5.12 Deferred ────────────────────────────────────────────────
case ApplyOnEventEffect aoe:
{
string targetRef = target is CardInstance ci3 ? ci3.InstanceId
: target is PlayerState ps3 ? ps3.AccountId
: string.Empty;
if (string.IsNullOrEmpty(targetRef)) break;
ctx.State.PendingDeferredEffects.Add(new PendingDeferredEffect
{
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
OwnerAccountId = ctx.ActorId,
TriggerJson = JsonSerializer.Serialize(aoe.Trigger, _jsonOpts),
TargetRef = targetRef,
EffectsJson = JsonSerializer.Serialize(aoe.Effects, _jsonOpts),
});
break;
}
default:
break;
}
}
private static FieldCard CreateTokenFieldCard(CardInstance proto, Coord position)
=> new()
{
InstanceId = proto.InstanceId,
Name = proto.Name,
CardType = "SpiritToken",
Affinity = proto.Affinity,
MaxHealth = proto.MaxHealth,
CurrentHealth = proto.MaxHealth,
MaxDefense = proto.MaxDefense,
CurrentDefense = proto.MaxDefense,
Damage = proto.Damage,
CanAttack = proto.CanAttack,
CanDefend = proto.CanDefend,
CanMove = proto.CanMove,
CanBeAttacked = proto.CanBeAttacked,
CanBeBlocked = proto.CanBeBlocked,
CanBeObstructed = proto.CanBeObstructed,
CanUseAbility = proto.CanUseAbility,
CanBeSacrificed = proto.CanBeSacrificed,
DisabledAbilities = proto.DisabledAbilities is null
? null : [.. proto.DisabledAbilities],
MovementType = proto.MovementType,
MaxMp = proto.MaxMp,
CurrentMp = proto.MaxMp ?? 0,
MinAttackRange = proto.MinAttackRange,
MaxAttackRange = proto.MaxAttackRange,
RequiresLos = proto.RequiresLos,
AbilitiesJson = proto.AbilitiesJson,
IsExhausted = false,
Position = position,
};
// ── Displacement helpers ──────────────────────────────────────────────────
private static (int dx, int dy) ParseDirection(string dir) => dir.ToUpperInvariant() switch
{
"NORTH" or "N" => (0, 1),
"SOUTH" or "S" => (0, -1),
"EAST" or "E" => ( 1, 0),
"WEST" or "W" => (-1, 0),
"NORTHEAST" or "NE" => ( 1, 1),
"NORTHWEST" or "NW" => (-1, 1),
"SOUTHEAST" or "SE" => ( 1, -1),
"SOUTHWEST" or "SW" => (-1, -1),
_ => (0, 0),
};
///
/// Applies affinity-based filter matching to a board tile.
/// Non-affinity filters are silently accepted (they apply to cards, not tiles).
///
private static bool TileMatchesFilters(Filter[] filters, Tile tile, AbilityContext ctx)
{
foreach (var f in filters)
{
if (f is AffinityMatchesFilter amf)
{
var resolved = AffinitySystem.Resolve(tile.Base1, tile.Base2);
if (!Enum.TryParse(amf.Affinity.ToString(), out var expected)
|| resolved != expected) return false;
}
}
return true;
}
// ── Damage helper ─────────────────────────────────────────────────────────
private static void ApplyDamageToUnit(
CardInstance unit, int rawAmount, bool bypassDefense, AbilityContext ctx)
{
int net = bypassDefense
? rawAmount
: Math.Max(0, rawAmount - (unit.CurrentDefense ?? 0));
unit.CurrentHealth = (unit.CurrentHealth ?? 0) - net;
if (unit.CurrentHealth <= 0) KillUnit(unit, ctx);
}
private static void KillUnit(CardInstance unit, AbilityContext ctx)
{
var owner = FindCardOwner(ctx.State, unit.InstanceId);
if (owner is null) return;
// Cancel deferred effects whose source is this unit.
ctx.State.PendingDeferredEffects.RemoveAll(p => p.SourceInstanceId == unit.InstanceId);
// Fire leave-aura triggers before removing from board.
EvaluateAurasOnLeave(ctx.State, unit.InstanceId);
RevokePassivesForSource(ctx.State, unit.InstanceId);
if (unit.CardType == "Ruin")
ctx.State.Board?.RemoveRuin(unit.InstanceId);
else
ctx.State.Board?.RemoveUnit(unit.InstanceId);
RemoveFromAllZones(owner, unit, board: null); // board already handled above
unit.CurrentHealth = 0;
owner.Discard.Add(unit);
FireTrigger(ctx.State, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitDeath,
ActorId = ctx.ActorId,
Data = new TriggerEventData { TargetId = unit.InstanceId },
UnitType = unit.CardType,
});
}
// ── Displacement helper ───────────────────────────────────────────────────
private static void DisplaceUnit(
FieldCard unit, int tiles, bool fromSource, AbilityContext ctx)
{
if (!unit.Position.HasValue || ctx.Source is not FieldCard srcFc
|| !srcFc.Position.HasValue || ctx.State.Board is null)
return;
var srcPos = srcFc.Position.Value;
var unitPos = unit.Position.Value;
int dx = unitPos.X - srcPos.X;
int dy = unitPos.Y - srcPos.Y;
if (dx == 0 && dy == 0) return;
int stepX = Math.Sign(dx);
int stepY = Math.Sign(dy);
if (!fromSource) { stepX = -stepX; stepY = -stepY; }
var newPos = new Coord(unitPos.X + stepX * tiles, unitPos.Y + stepY * tiles);
var board = ctx.State.Board;
if (!board.IsInBounds(newPos) || !board.GetTile(newPos)!.IsEmpty) return;
var ownerEntry = ctx.State.Players.Values
.FirstOrDefault(p => p.Field.Any(f => f.InstanceId == unit.InstanceId));
if (ownerEntry is null) return;
board.RemoveUnit(unit.InstanceId);
board.PlaceUnit(newPos, unit.InstanceId, ownerEntry.AccountId);
unit.Position = newPos;
}
// ── Zone helpers ──────────────────────────────────────────────────────────
private static void DrawCards(PlayerState player, int n)
{
for (int i = 0; i < n && player.Deck.Count > 0; i++)
{
var top = player.Deck[^1];
player.Deck.RemoveAt(player.Deck.Count - 1);
player.Hand.Add(top);
}
}
private static void DiscardFromHand(
PlayerState player, int n, Filter[]? filters, AbilityContext ctx)
{
var toDiscard = player.Hand
.Where(c => filters is null || FiltersMatch(filters, c, ctx))
.Take(n).ToList();
foreach (var c in toDiscard) { player.Hand.Remove(c); player.Discard.Add(c); }
}
private static void PlaceInDeck(PlayerState player, CardInstance card, string position)
{
switch (position.ToLowerInvariant())
{
case "bottom": player.Deck.Insert(0, card); break;
case "random":
int idx = new Random().Next(player.Deck.Count + 1);
player.Deck.Insert(idx, card); break;
default: player.Deck.Add(card); break;
}
}
private static void RemoveFromAllZones(PlayerState player, CardInstance card, Board? board)
{
if (board is not null)
{
board.RemoveUnit(card.InstanceId);
if (card.CardType == "Ruin") board.RemoveRuin(card.InstanceId);
}
player.Hand.Remove(card);
player.Deck.Remove(card);
player.Field.Remove(card);
player.Discard.Remove(card);
}
private static PlayerState? FindCardOwner(GameState state, string instanceId)
{
foreach (var player in state.Players.Values)
{
if (player.Hand.Any(c => c.InstanceId == instanceId)) return player;
if (player.Deck.Any(c => c.InstanceId == instanceId)) return player;
if (player.Field.Any(c => c.InstanceId == instanceId)) return player;
if (player.Discard.Any(c => c.InstanceId == instanceId)) return player;
}
return null;
}
private static PlayerState ResolvePlayerForEffect(string playerRef, AbilityContext ctx)
=> playerRef.ToLowerInvariant() switch
{
"enemy" or "opponent" =>
ctx.State.Players.Values.First(p => p.AccountId != ctx.ActorId),
_ => ctx.State.Players[ctx.ActorId],
};
// ── Condition evaluation ──────────────────────────────────────────────────
public static bool EvaluateCondition(
Condition condition, AbilityContext ctx, object subject)
{
if (condition.Subject == "Target" && ctx.ResolvedTargets.Count > 0)
subject = ctx.ResolvedTargets.Values.Last().FirstOrDefault() ?? subject;
var player = ctx.State.Players[ctx.ActorId];
switch (condition)
{
case AndCondition and:
return and.Conditions.All(c => EvaluateCondition(c, ctx, subject));
case OrCondition or:
return or.Conditions.Any(c => EvaluateCondition(c, ctx, subject));
case XorCondition xor:
return xor.Conditions.Count(c => EvaluateCondition(c, ctx, subject)) == 1;
case HealthBelowCondition hb when subject is CardInstance ci:
return (ci.CurrentHealth ?? 0) < hb.N;
case HealthAboveCondition ha when subject is CardInstance ci:
return (ci.CurrentHealth ?? 0) > ha.N;
case DefenseIsCondition di when subject is CardInstance ci:
return (ci.CurrentDefense ?? 0) == di.N;
case HasGenusCondition hg when subject is CardInstance ci:
return ci.Genus?.Contains(hg.Tag) == true;
case HasAbilityCondition hab when subject is CardInstance ci:
return ParseAbilities(ci.AbilitiesJson).Any(a => a.Name == hab.AbilityRef);
case IsOnTileWithAffinityCondition iotwa when subject is FieldCard fc
&& fc.Position.HasValue && ctx.State.Board is not null:
{
var tile = ctx.State.Board.GetTile(fc.Position.Value);
return tile is not null
&& AffinitySystem.Resolve(tile.Base1, tile.Base2) == iotwa.Affinity;
}
case MovementTypeIsCondition mti when subject is CardInstance ci:
return ci.MovementType == mti.MovementType;
case SPAtLeastCondition spal: return player.CurrentSp >= spal.N;
case SPAtMostCondition spam: return player.CurrentSp <= spam.N;
case STAtLeastCondition stal: return player.CurrentSt >= stal.N;
case STAtMostCondition stam: return player.CurrentSt <= stam.N;
case HandSizeAtLeastCondition hsal: return player.Hand.Count >= hsal.N;
case HandSizeAtMostCondition hsam: return player.Hand.Count <= hsam.N;
case DeckSizeAtLeastCondition dsal: return player.Deck.Count >= dsal.N;
case DiscardSizeAtLeastCondition dis: return player.Discard.Count >= dis.N;
case IsOwnTurnCondition:
return ctx.State.ActivePlayerAccountId == ctx.ActorId;
case IsOpponentTurnCondition:
return ctx.State.ActivePlayerAccountId != ctx.ActorId;
case IsAllyTurnCondition:
return ctx.State.ActivePlayerAccountId == ctx.ActorId;
case IsActivePlayerTurnCondition iaptc:
return iaptc.Ownership.ToLowerInvariant() == "owner"
? ctx.State.ActivePlayerAccountId == ctx.ActorId
: ctx.State.ActivePlayerAccountId != ctx.ActorId;
case UnitCountOnBattlefieldCondition ucob:
{
IEnumerable pool =
ucob.Ownership.ToLowerInvariant() == "enemy"
? ctx.State.Players.Values.Where(p => p.AccountId != ctx.ActorId)
.SelectMany(p => p.Field)
: player.Field;
if (ucob.UnitType != "Unit")
pool = pool.Where(c => c.CardType == ucob.UnitType);
int count = pool.Count();
return ucob.Comparator switch
{
Comparator.Equal => count == ucob.N,
Comparator.NotEqual => count != ucob.N,
Comparator.LessThan => count < ucob.N,
Comparator.LessThanOrEqual => count <= ucob.N,
Comparator.GreaterThan => count > ucob.N,
Comparator.GreaterThanOrEqual => count >= ucob.N,
_ => false,
};
}
default:
return true;
}
}
// ── Filter evaluation ─────────────────────────────────────────────────────
private static bool FiltersMatch(Filter[] filters, CardInstance card, AbilityContext ctx)
=> filters.All(f => FilterMatches(f, card, ctx));
private static bool FilterMatches(Filter filter, CardInstance card, AbilityContext ctx)
=> filter switch
{
CardTypeIsFilter ctif => card.CardType == ctif.CardType.ToString(),
AffinityMatchesFilter amf => card.Affinity == amf.Affinity.ToString(),
HasFlagFilter hff => hff.Flag switch
{
"IsLeader" => card.IsLeader,
"IsExhausted" => card.IsExhausted,
"CanMove" => card.CanMove,
"CanAttack" => card.CanAttack,
_ => false,
},
TierIsFilter tif => card.Tier == tif.Tier,
// IsSelf: definition-level match (any instance of the same card definition).
IsSelfFilter => ctx.Source is not null && card.CardDefinitionId == ctx.Source.CardDefinitionId,
// IsExactSelf: instance-level match (only this specific unit on the battlefield).
IsExactSelfFilter => ctx.Source is not null && card.InstanceId == ctx.Source.InstanceId,
HealthBelowFilter hbf => (card.CurrentHealth ?? 0) < hbf.N,
HealthAboveFilter haf => (card.CurrentHealth ?? 0) > haf.N,
IsAdjacentToSourceFilter =>
ctx.Source is FieldCard srcAdj && srcAdj.Position.HasValue &&
card is FieldCard adjTgt && adjTgt.Position.HasValue &&
srcAdj.Position.Value.IsOrthogonallyAdjacentTo(adjTgt.Position.Value),
WithinRangeFilter wrf =>
ctx.Source is FieldCard srcWr && srcWr.Position.HasValue &&
card is FieldCard wrTgt && wrTgt.Position.HasValue &&
srcWr.Position.Value.ManhattanDistance(wrTgt.Position.Value) >= wrf.Min &&
srcWr.Position.Value.ManhattanDistance(wrTgt.Position.Value) <= wrf.Max,
_ => true,
};
// ── Trigger matching ──────────────────────────────────────────────────────
///
/// The specific battlefield unit whose trigger is being evaluated.
/// Required for the "ExactSelf" ownership scope — fire only when this unit
/// is the source of the event (occ.Data.SourceId == evaluatingUnit.InstanceId).
///
private static bool TriggerMatches(
TriggerEvent trigger, TriggerOccurrence occurrence, GameState state, string ownerId,
FieldCard? evaluatingUnit = null)
{
var uid = evaluatingUnit?.InstanceId;
return trigger switch
{
OnTurnStartTrigger t =>
occurrence.Kind == TriggerEventKind.TurnStart
&& Own(t.Player, occurrence, ownerId, state, uid),
OnTurnEndTrigger t =>
occurrence.Kind == TriggerEventKind.TurnEnd
&& Own(t.Player, occurrence, ownerId, state, uid),
OnUnitDeathTrigger t =>
occurrence.Kind == TriggerEventKind.UnitDeath
&& UnitType(t.UnitType, occurrence.UnitType)
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnDamageDealtTrigger =>
occurrence.Kind == TriggerEventKind.DamageDealt,
OnUnitEnterBattlefieldTrigger t =>
occurrence.Kind == TriggerEventKind.UnitEnterBattlefield
&& UnitType(t.UnitType, occurrence.UnitType)
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnUnitLeaveBattlefieldTrigger t =>
occurrence.Kind == TriggerEventKind.UnitLeaveBattlefield
&& UnitType(t.UnitType, occurrence.UnitType)
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnSPGainedTrigger t =>
occurrence.Kind == TriggerEventKind.SPGained
&& Own(t.Player, occurrence, ownerId, state, uid),
OnSPSpentTrigger t =>
occurrence.Kind == TriggerEventKind.SPSpent
&& Own(t.Player, occurrence, ownerId, state, uid),
OnSTGainedTrigger t =>
occurrence.Kind == TriggerEventKind.STGained
&& Own(t.Player, occurrence, ownerId, state, uid),
OnSTSpentTrigger t =>
occurrence.Kind == TriggerEventKind.STSpent
&& Own(t.Player, occurrence, ownerId, state, uid),
OnCardDrawnTrigger t =>
occurrence.Kind == TriggerEventKind.CardDrawn
&& Own(t.Player, occurrence, ownerId, state, uid),
OnUnitMoveTrigger t =>
occurrence.Kind == TriggerEventKind.UnitMove
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnUnitAttackTrigger t =>
occurrence.Kind == TriggerEventKind.UnitAttack
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnSpiritSacrificedTrigger t =>
occurrence.Kind == TriggerEventKind.SpiritSacrificed
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnAscendTrigger t =>
occurrence.Kind == TriggerEventKind.Ascend
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnTransitionTrigger t =>
occurrence.Kind == TriggerEventKind.Transition
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnChanneledTrigger t =>
occurrence.Kind == TriggerEventKind.Channeled
&& CardType(t.CardType, occurrence.CardType)
&& Own(t.Ownership, occurrence, ownerId, state, uid),
OnEnterAuraRangeTrigger eat =>
occurrence.Kind == TriggerEventKind.EnterAuraRange
&& Own(eat.AuraOwnership, occurrence, ownerId, state, uid)
&& UnitOwnerMatches(eat.UnitOwnership, occurrence.Data?.TargetId, state, ownerId),
OnLeaveAuraRangeTrigger lat =>
occurrence.Kind == TriggerEventKind.LeaveAuraRange
&& Own(lat.AuraOwnership, occurrence, ownerId, state, uid)
&& UnitOwnerMatches(lat.UnitOwnership, occurrence.Data?.TargetId, state, ownerId),
OnRuinActivationTrigger rat =>
occurrence.Kind == TriggerEventKind.RuinActivation
&& Own(rat.RuinOwnership, occurrence, ownerId, state, uid)
&& (rat.OccupantOwnership is null
|| UnitOwnerMatches(rat.OccupantOwnership, occurrence.Data?.TargetId, state, ownerId)),
OnUnitOccupyRuinTrigger uor =>
occurrence.Kind == TriggerEventKind.UnitOccupyRuin
&& Own(uor.UnitOwnership, occurrence, ownerId, state, uid),
_ => false,
};
}
///
/// Instance ID of the unit whose trigger is being evaluated.
/// Only used for the "ExactSelf" scope: the trigger fires only when this unit
/// is the specific unit that caused the event (occ.Data.SourceId == evalUnitId).
///
private static bool Own(string? scope, TriggerOccurrence occ, string unitOwnerId, GameState _,
string? evalUnitId = null)
=> (scope?.ToLowerInvariant()) switch
{
null or "any" => true,
"own" or "self" or "owner" => occ.ActorId == unitOwnerId,
"enemy" => occ.ActorId != unitOwnerId,
"ally" => occ.ActorId == unitOwnerId,
// ExactSelf: fires only for the specific unit that performed the action.
// Requires occ.Data.SourceId to carry the acting unit's instance ID.
"exactself" => evalUnitId is not null && occ.Data?.SourceId == evalUnitId,
_ => true,
};
private static bool UnitOwnerMatches(
string scope, string? unitInstanceId, GameState state, string referenceOwnerId)
{
if (scope.ToLowerInvariant() == "any" || unitInstanceId is null) return true;
foreach (var (ownerId, player) in state.Players)
if (player.Field.Any(c => c.InstanceId == unitInstanceId))
return scope.ToLowerInvariant() switch
{
"ally" or "owner" => ownerId == referenceOwnerId,
"enemy" => ownerId != referenceOwnerId,
_ => true,
};
return true;
}
private static bool UnitType(string? required, string? actual)
=> required is null or "Unit" or "Any" || required == actual;
private static bool CardType(string? required, string? actual)
=> required is null or "Any" || required == actual;
// ── Value / affinity resolution ───────────────────────────────────────────
private static int ResolveValue(ValueExpr expr, AbilityContext ctx)
{
if (expr.Fixed.HasValue) return expr.Fixed.Value;
if (expr.Ref is null) return 0;
var parts = expr.Ref.Split('.');
return (parts[0], parts.Length > 1 ? parts[1] : "") switch
{
("EventData", "Amount") => ctx.EventData?.Amount ?? 0,
("Self", "Damage") => ctx.Source?.Damage ?? 0,
("Self", "Health") => ctx.Source?.CurrentHealth ?? 0,
("Self", "Defense") => ctx.Source?.CurrentDefense ?? 0,
("Self", "MP") => (ctx.Source as FieldCard)?.CurrentMp ?? 0,
_ => 0,
};
}
private static Affinity ResolveAffinity(AffinityExpr expr, AbilityContext ctx)
{
if (expr.Fixed.HasValue) return expr.Fixed.Value;
if (expr.Ref is null) return Affinity.Void;
var parts = expr.Ref.Split('.');
return (parts[0], parts.Length > 1 ? parts[1] : "") switch
{
("Self", "Affinity") when ctx.Source is not null =>
Enum.TryParse(ctx.Source.Affinity, out var a) ? a : Affinity.Void,
_ => Affinity.Void,
};
}
// ── Duration tracking ──────────────────────────────────────────────────────
private static ValueExpr V(int n) => new() { Fixed = n };
/// Internal metadata envelope stored in ActiveEffect.DurationJson.
private sealed class TrackedDuration
{
public DurationModel Duration { get; set; } = new();
public string OwnerAccountId { get; set; } = string.Empty;
/// True for DOT/HOT tick effects (apply each turn); false for reversal effects.
public bool IsTick { get; set; }
}
///
/// Stores a reversal effect to be applied when the duration expires.
/// No-op for Instant or PermanentInMatch durations.
///
private static void TrackEffect(
Effect reversal,
string targetRef,
DurationModel? duration,
AbilityContext ctx)
{
if (duration is null
|| duration.Type is DurationType.Instant or DurationType.PermanentInMatch)
return;
ctx.State.ActiveEffects.Add(new ActiveEffect
{
SourceInstanceId = ctx.Source?.InstanceId ?? "",
TargetRef = targetRef,
EffectJson = JsonSerializer.Serialize(reversal, _jsonOpts),
DurationJson = JsonSerializer.Serialize(new TrackedDuration
{
Duration = duration,
OwnerAccountId = ctx.ActorId,
}, _jsonOpts),
TurnsRemaining = duration.N ?? 0,
});
}
///
/// Stores a tick effect (DOT/HOT) to be applied each turn for the duration.
///
private static void TrackTick(
Effect tickEffect,
string targetRef,
DurationModel duration,
AbilityContext ctx)
{
if (duration.Type is DurationType.Instant or DurationType.PermanentInMatch)
return;
ctx.State.ActiveEffects.Add(new ActiveEffect
{
SourceInstanceId = ctx.Source?.InstanceId ?? "",
TargetRef = targetRef,
EffectJson = JsonSerializer.Serialize(tickEffect, _jsonOpts),
DurationJson = JsonSerializer.Serialize(new TrackedDuration
{
Duration = duration,
OwnerAccountId = ctx.ActorId,
IsTick = true,
}, _jsonOpts),
TurnsRemaining = duration.N ?? 0,
});
}
///
/// Fires DOT/HOT tick effects for the given player's turn.
/// Call at TurnEnd before expiry processing.
///
public static GameState TickActiveEffects(GameState state, string activePlayerId)
{
foreach (var ae in state.ActiveEffects.ToList())
{
TrackedDuration? td;
try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); }
catch { continue; }
if (td?.IsTick != true) continue;
Effect? eff;
try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); }
catch { continue; }
if (eff is null) continue;
var tgt = state.Players.Values
.SelectMany(p => p.Field)
.FirstOrDefault(c => c.InstanceId == ae.TargetRef);
if (tgt is null) continue;
var src = state.Players.Values
.SelectMany(p => p.Field).OfType()
.FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId);
ExecuteEffect(eff, tgt, DurationModel.Instant, new AbilityContext
{
State = state,
ActorId = td.OwnerAccountId,
Source = src,
});
}
return state;
}
///
/// Expires duration-tracked effects at a turn boundary.
/// Call with =true at end of 's
/// turn, and false at start of 's turn (after player switch).
///
public static GameState ExpireActiveEffects(
GameState state,
string currentPlayerId,
bool isEndOfTurn)
{
var toRemove = new List();
foreach (var ae in state.ActiveEffects)
{
TrackedDuration? td;
try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); }
catch { continue; }
if (td is null) continue;
var dur = td.Duration;
switch (dur.Type)
{
case DurationType.UntilEndOfTurn:
if (isEndOfTurn
&& (dur.PlayerScope is null
|| MatchPlayerScope(dur.PlayerScope, currentPlayerId, td.OwnerAccountId)))
{
if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId);
toRemove.Add(ae);
}
break;
case DurationType.UntilStartOfOwnerTurn:
case DurationType.UntilStartOfSourceOwnerTurn:
if (!isEndOfTurn && currentPlayerId == td.OwnerAccountId)
{
if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId);
toRemove.Add(ae);
}
break;
case DurationType.ForNTurns:
if (isEndOfTurn)
{
ae.TurnsRemaining--;
if (ae.TurnsRemaining <= 0)
{
if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId);
toRemove.Add(ae);
}
}
break;
case DurationType.WhileCondition:
if (dur.Condition is not null)
{
var src = state.Players.Values
.SelectMany(p => p.Field)
.FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId);
var condCtx = new AbilityContext
{
State = state,
ActorId = td.OwnerAccountId,
Source = src,
};
if (!EvaluateCondition(dur.Condition, condCtx, src ?? (object)state))
{
if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId);
toRemove.Add(ae);
}
}
break;
}
}
foreach (var ae in toRemove) state.ActiveEffects.Remove(ae);
return state;
}
private static bool MatchPlayerScope(
string scope, string currentPlayerId, string ownerAccountId)
=> scope.ToLowerInvariant() switch
{
"owner" or "self" => currentPlayerId == ownerAccountId,
"enemy" => currentPlayerId != ownerAccountId,
_ => true,
};
private static void ApplyReversal(GameState state, ActiveEffect ae, string ownerAccountId)
{
Effect? eff;
try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); }
catch { return; }
if (eff is null) return;
// Find target by instanceId (any zone) or by accountId (player).
object? tgt = null;
foreach (var p in state.Players.Values)
{
tgt = (CardInstance?)(
p.Field.FirstOrDefault(c => c.InstanceId == ae.TargetRef)
?? p.Hand.FirstOrDefault(c => c.InstanceId == ae.TargetRef)
?? p.Deck.FirstOrDefault(c => c.InstanceId == ae.TargetRef)
?? p.Discard.FirstOrDefault(c => c.InstanceId == ae.TargetRef));
if (tgt is not null) break;
if (p.AccountId == ae.TargetRef) { tgt = p; break; }
}
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 duration = new DurationModel { Type = DurationType.WhileSourceOnBattlefield };
foreach (var def in ParseAbilities(source.AbilitiesJson).Where(d => d.Type == AbilityType.Passive))
ExecuteActions(def.Actions, ctx, clientTargets: null, forceDuration: duration);
}
///
/// 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 duration = 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))
ExecuteActions(def.Actions, ctx, clientTargets: null,
restrictTargets: restrict, forceDuration: duration);
}
}
///
/// 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);
}
}
// ── Aura range evaluation ─────────────────────────────────────────────────
///
/// Fires OnEnterAuraRange / OnLeaveAuraRange triggers when a unit moves from
/// to .
/// Handles both the moving unit crossing into/out of stationary auras, and the
/// moving unit's own auras sweeping over stationary units.
/// Call after updating the unit's position on the board.
///
public static GameState EvaluateAuraTransitions(
GameState state,
string movingUnitId,
Coord from,
Coord to)
{
// Part 1: stationary aura-bearing units vs. moving unit's position change.
foreach (var (auraOwnerId, player) in state.Players)
foreach (var auraUnit in player.Field.OfType()
.Where(f => f.Position.HasValue && f.InstanceId != movingUnitId).ToList())
{
foreach (var def in ParseAbilities(auraUnit.AbilitiesJson)
.Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null))
{
var auraPos = auraUnit.Position!.Value;
int min = def.AuraRange!.Min, max = def.AuraRange.Max;
FireAuraTransition(state, auraOwnerId, auraUnit.InstanceId, movingUnitId,
wasIn: from.ManhattanDistance(auraPos) >= min && from.ManhattanDistance(auraPos) <= max,
isIn: to.ManhattanDistance(auraPos) >= min && to.ManhattanDistance(auraPos) <= max);
}
}
// Part 2: moving unit's own auras vs. stationary units.
var movingUnit = state.Players.Values
.SelectMany(p => p.Field.OfType())
.FirstOrDefault(f => f.InstanceId == movingUnitId);
if (movingUnit is null) return state;
string? movingOwnerId = null;
foreach (var (oid, pl) in state.Players)
if (pl.Field.Any(c => c.InstanceId == movingUnitId)) { movingOwnerId = oid; break; }
if (movingOwnerId is null) return state;
foreach (var def in ParseAbilities(movingUnit.AbilitiesJson)
.Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null))
{
int min = def.AuraRange!.Min, max = def.AuraRange.Max;
foreach (var (_, pl) in state.Players)
foreach (var other in pl.Field.OfType()
.Where(f => f.Position.HasValue && f.InstanceId != movingUnitId).ToList())
{
var otherPos = other.Position!.Value;
FireAuraTransition(state, movingOwnerId, movingUnitId, other.InstanceId,
wasIn: from.ManhattanDistance(otherPos) >= min && from.ManhattanDistance(otherPos) <= max,
isIn: to.ManhattanDistance(otherPos) >= min && to.ManhattanDistance(otherPos) <= max);
}
}
return state;
}
///
/// Fires OnEnterAuraRange triggers for a unit newly placed on the battlefield.
/// Handles both existing auras covering the new unit and the new unit's own auras
/// covering existing units.
/// Call after placing the unit at its initial position.
///
public static GameState EvaluateAurasOnEnter(GameState state, string newUnitId)
{
var newUnit = state.Players.Values
.SelectMany(p => p.Field.OfType())
.FirstOrDefault(f => f.InstanceId == newUnitId);
if (newUnit?.Position is null) return state;
var newPos = newUnit.Position.Value;
// Part 1: existing aura units — check if new unit entered their range.
foreach (var (auraOwnerId, player) in state.Players)
foreach (var auraUnit in player.Field.OfType()
.Where(f => f.Position.HasValue && f.InstanceId != newUnitId).ToList())
{
foreach (var def in ParseAbilities(auraUnit.AbilitiesJson)
.Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null))
{
int dist = newPos.ManhattanDistance(auraUnit.Position!.Value);
if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max)
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.EnterAuraRange,
ActorId = auraOwnerId,
Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = newUnitId },
});
}
}
// Part 2: new unit's own auras — check all existing units.
string? newUnitOwnerId = null;
foreach (var (oid, pl) in state.Players)
if (pl.Field.Any(c => c.InstanceId == newUnitId)) { newUnitOwnerId = oid; break; }
if (newUnitOwnerId is null) return state;
foreach (var def in ParseAbilities(newUnit.AbilitiesJson)
.Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null))
{
foreach (var (_, pl) in state.Players)
foreach (var other in pl.Field.OfType()
.Where(f => f.Position.HasValue && f.InstanceId != newUnitId).ToList())
{
int dist = newPos.ManhattanDistance(other.Position!.Value);
if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max)
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.EnterAuraRange,
ActorId = newUnitOwnerId,
Data = new TriggerEventData { SourceId = newUnitId, TargetId = other.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 => p.Field.OfType())
.FirstOrDefault(f => f.InstanceId == leavingUnitId);
if (leavingUnit?.Position is null) return state;
var leavingPos = leavingUnit.Position.Value;
// Part 1: existing aura units — check if leaving unit was in their range.
foreach (var (auraOwnerId, player) in state.Players)
foreach (var auraUnit in player.Field.OfType()
.Where(f => f.Position.HasValue && f.InstanceId != leavingUnitId).ToList())
{
foreach (var def in ParseAbilities(auraUnit.AbilitiesJson)
.Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null))
{
int dist = leavingPos.ManhattanDistance(auraUnit.Position!.Value);
if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max)
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.LeaveAuraRange,
ActorId = auraOwnerId,
Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = leavingUnitId },
});
}
}
// Part 2: leaving unit's own auras — fire LeaveAuraRange for each in-range unit.
string? leavingOwnerId = null;
foreach (var (oid, pl) in state.Players)
if (pl.Field.Any(c => c.InstanceId == leavingUnitId)) { leavingOwnerId = oid; break; }
if (leavingOwnerId is null) return state;
foreach (var def in ParseAbilities(leavingUnit.AbilitiesJson)
.Where(d => d.Type == AbilityType.Aura && d.AuraRange is not null))
{
foreach (var (_, pl) in state.Players)
foreach (var other in pl.Field.OfType()
.Where(f => f.Position.HasValue && f.InstanceId != leavingUnitId).ToList())
{
int dist = leavingPos.ManhattanDistance(other.Position!.Value);
if (dist >= def.AuraRange!.Min && dist <= def.AuraRange.Max)
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.LeaveAuraRange,
ActorId = leavingOwnerId,
Data = new TriggerEventData { SourceId = leavingUnitId, TargetId = other.InstanceId },
});
}
}
return state;
}
private static void FireAuraTransition(
GameState state,
string auraOwnerId,
string auraUnitId,
string targetUnitId,
bool wasIn,
bool isIn)
{
if (!wasIn && isIn)
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.EnterAuraRange,
ActorId = auraOwnerId,
Data = new TriggerEventData { SourceId = auraUnitId, TargetId = targetUnitId },
});
else if (wasIn && !isIn)
FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.LeaveAuraRange,
ActorId = auraOwnerId,
Data = new TriggerEventData { SourceId = auraUnitId, TargetId = targetUnitId },
});
}
}