From be8c0844c60d07d873ee60d810d522abb7d10301 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 26 Feb 2026 16:16:46 -0500 Subject: [PATCH] =?UTF-8?q?Add=20AbilitySystem=20=E2=80=94=20core=20effect?= =?UTF-8?q?=20execution,=20trigger=20hooks,=20activate=5Fability=20handler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - AbilitySystem.cs: full rewrite — ActivateAbility, FireTrigger, FireCardEffects, ExecuteActions, ResolveTargets, ExecuteEffect (§5.1–5.10), condition evaluation, filter evaluation, trigger matching, value/affinity resolution - GameState.cs: CardInstance gains AbilitiesJson, EffectsJson, AbilityUsesThisTurn, Genus; PlayerState gains SpAccumulationBonus, DrawPerTurnBonus and 12 action- restriction flags; GameState gains ActiveEffects list; new ActiveEffect class - GameMessages.cs: GameActivateAbilityRequest/Response + AbilityTarget DTO - GameEngine.cs: ActivateAbility public method; trigger hooks in ChannelCard, MoveUnit, Attack (UnitAttack + UnitDeath), Sacrifice, EndTurn (TurnEnd/TurnStart), Ascend, Transition; AbilitiesJson/EffectsJson copied in DefinitionToInstance, BuildPlayerState, ToFieldCard; Repentance/Instinct/Ruin now fire EffectsJson inline - GameActivateAbilityHandler: game.activate_ability message handler - ServiceRegistration: register GameActivateAbilityHandler Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../src/SOR.Game/Abilities/AbilitySystem.cs | 650 ++++++------------ Server/src/SOR.Game/GameEngine.cs | 153 ++++- Server/src/SOR.Game/GameMessages.cs | 25 + Server/src/SOR.Game/GameState.cs | 86 +++ .../Handlers/GameActivateAbilityHandler.cs | 55 ++ Server/src/SOR.Game/ServiceRegistration.cs | 1 + 6 files changed, 543 insertions(+), 427 deletions(-) create mode 100644 Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index bc5dcc4..79b4c42 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -15,7 +15,7 @@ using SOR.Game.Grid; /// public static class AbilitySystem { - // ── JSON options shared across all parse calls ───────────────────────────── + // ── JSON options ─────────────────────────────────────────────────────────── private static readonly JsonSerializerOptions _jsonOpts = new() { @@ -41,7 +41,6 @@ public static class AbilitySystem /// /// Entry point for a player manually activating an Active ability on one of /// their units. Validates conditions, pays cost, resolves targets and effects. - /// Returns the mutated game state. /// public static GameState ActivateAbility( GameState state, @@ -50,7 +49,6 @@ public static class AbilitySystem int abilityIndex, IReadOnlyList? clientTargets) { - // Find the source unit on the battlefield. var player = state.Players[actorId]; var source = player.Field.OfType() .FirstOrDefault(f => f.InstanceId == sourceInstanceId) @@ -59,7 +57,6 @@ public static class AbilitySystem if (source.IsExhausted) throw new GameException("UNIT_EXHAUSTED"); - // Parse abilities from the copied JSON blob on the card instance. var abilities = ParseAbilities(source.AbilitiesJson); if (abilityIndex < 0 || abilityIndex >= abilities.Length) throw new GameException("ABILITY_INDEX_OUT_OF_RANGE"); @@ -69,33 +66,23 @@ public static class AbilitySystem if (def.Type != AbilityType.Active) throw new GameException("ABILITY_NOT_ACTIVE"); - // Enforce UsesPerTurn limit. 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, - }; + var ctx = new AbilityContext { State = state, ActorId = actorId, Source = source }; - // Check activation conditions. if (def.ActivationConditions is { Length: > 0 }) foreach (var cond in def.ActivationConditions) if (!EvaluateCondition(cond, ctx, source)) throw new GameException("ABILITY_CONDITION_NOT_MET"); - // Pay cost. if (def.Cost is { Length: > 0 }) PayCost(def.Cost, ctx); - // Track use. source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; - // Execute actions. ExecuteActions(def.Actions, ctx, clientTargets); return state; @@ -104,15 +91,27 @@ public static class AbilitySystem // ── Triggered ability firing ─────────────────────────────────────────────── /// - /// Called from GameEngine mutation methods to fire any Triggered abilities - /// that match the given occurrence. Scans every unit on the battlefield. + /// 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) + { + 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: null); + 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) { - // Snapshot the current field — effects may mutate it. - var units = player.Field.OfType().ToList(); + var units = player.Field.OfType().ToList(); // snapshot foreach (var unit in units) { var abilities = ParseAbilities(unit.AbilitiesJson); @@ -138,36 +137,10 @@ public static class AbilitySystem ExecuteActions(def.Actions, ctx, clientTargets: null); } } - - // Also fire effects from non-unit cards (EffectsJson on Field cards). - foreach (var unit in player.Field.ToList()) - { - var actions = ParseEffects(unit.EffectsJson); - // EffectsJson is a raw Actions array — fire unconditionally. - if (actions.Length == 0) continue; - var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = unit }; - foreach (var action in actions) - ExecuteSingleAction(action, ctx, clientTargets: null, actionIndex: 0); - } } return state; } - // ── Passive / Aura evaluation (applied per-turn refresh) ────────────────── - - /// - /// Resets and re-applies all Passive and Aura abilities for all units. - /// Called at the start of each player's turn to keep derived stats current. - /// - public static GameState RefreshPassives(GameState state) - { - // Passive effects are handled as permanent stat modifiers baked into - // the unit's stat block at FieldCard construction time. A full - // re-evaluation pass would require baseline snapshots; that complexity - // is deferred until the stat-mod layer is fleshed out. - return state; - } - // ── Cost payment ────────────────────────────────────────────────────────── private static void PayCost(CostEntry[] costs, AbilityContext ctx) @@ -179,14 +152,12 @@ public static class AbilitySystem switch (cost.Type) { case CostType.SpiritPoints: - if (player.CurrentSp < cost.Amount) - throw new GameException("INSUFFICIENT_SP"); + 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"); + if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST"); player.CurrentSt -= cost.Amount; break; @@ -194,15 +165,10 @@ public static class AbilitySystem { var candidates = player.Hand .Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx)) - .Take(cost.Amount) - .ToList(); + .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); - } + foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); } break; } @@ -225,34 +191,28 @@ public static class AbilitySystem break; case CostType.DealDamageToOwnArchSpirit: - if (player.ArchSpirit is null) - throw new GameException("NO_ARCHSPIRIT"); + 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() + 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"); + 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() + 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"); + if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); + ctx.State.Board?.RemoveUnit(spirit.InstanceId); player.Field.Remove(spirit); - if (spirit.Position.HasValue && ctx.State.Board is not null) - ctx.State.Board.ClearUnit(spirit.Position.Value); player.Discard.Add(spirit); break; } @@ -277,22 +237,17 @@ public static class AbilitySystem IReadOnlyList? clientTargets, int actionIndex) { - // Check per-action conditions. if (action.Conditions is { Length: > 0 }) foreach (var cond in action.Conditions) if (!EvaluateCondition(cond, ctx, ctx.Source!)) - return; // skip this action if condition not met + return; - // Resolve targets. var resolved = ResolveTargets(action.Target, ctx, clientTargets, actionIndex); ctx.ResolvedTargets[actionIndex] = resolved; - // Execute effects on each resolved target. foreach (var target in resolved) - { foreach (var effect in action.Effects) ExecuteEffect(effect, target, action.Duration, ctx); - } } // ── Target resolution ───────────────────────────────────────────────────── @@ -303,26 +258,20 @@ public static class AbilitySystem IReadOnlyList? clientTargets, int actionIndex) { - var state = ctx.State; - var player = state.Players[ctx.ActorId]; + var state = ctx.State; - // For player targets — return the player state objects. if (selector.Type == TargetType.Player) { return selector.Ownership switch { TargetOwnership.Owner or TargetOwnership.Self => - [player], + [state.Players[ctx.ActorId]], TargetOwnership.Enemy => - state.Players.Values - .Where(p => p.AccountId != ctx.ActorId) - .Cast() - .ToList(), + state.Players.Values.Where(p => p.AccountId != ctx.ActorId).Cast().ToList(), _ => state.Players.Values.Cast().ToList(), }; } - // For tile targets — use client-provided coords. if (selector.Type == TargetType.Tile) { if (clientTargets is null) return []; @@ -332,29 +281,20 @@ public static class AbilitySystem .ToList(); } - // For unit/card targets — build the candidate pool. var candidates = BuildCandidates(selector, state, ctx.ActorId); - // Apply filters. if (selector.Filters is { Length: > 0 }) - candidates = candidates - .Where(c => FiltersMatch(selector.Filters, c, ctx)) - .ToList(); + candidates = candidates.Where(c => FiltersMatch(selector.Filters, c, ctx)).ToList(); - // If client-targeted, filter down to what the client specified. if (clientTargets is not null) { var clientIds = clientTargets .Where(t => t.ActionIndex == actionIndex && t.InstanceId is not null) - .Select(t => t.InstanceId!) - .ToHashSet(); + .Select(t => t.InstanceId!).ToHashSet(); if (clientIds.Count > 0) - candidates = candidates - .Where(c => c is CardInstance ci && clientIds.Contains(ci.InstanceId)) - .ToList(); + candidates = candidates.Where(c => clientIds.Contains(c.InstanceId)).ToList(); } - // Enforce count. if (!selector.Count.All) { int needed = selector.Count.N; @@ -367,20 +307,15 @@ public static class AbilitySystem } private static List BuildCandidates( - TargetSelector selector, - GameState state, - string actorId) + TargetSelector selector, GameState state, string actorId) { var all = new List(); IEnumerable ownerIds = selector.Ownership switch { - TargetOwnership.Owner or TargetOwnership.Self => - [actorId], - TargetOwnership.Enemy => - state.Players.Keys.Where(k => k != actorId), - TargetOwnership.Ally => - state.Players.Keys.Where(k => k != actorId), // 1v1 same as enemy; expand for multiplayer + TargetOwnership.Owner or TargetOwnership.Self => [actorId], + TargetOwnership.Enemy => state.Players.Keys.Where(k => k != actorId), + TargetOwnership.Ally => state.Players.Keys.Where(k => k != actorId), _ => state.Players.Keys, }; @@ -389,35 +324,25 @@ public static class AbilitySystem var p = state.Players[ownerId]; switch (selector.Scope) { - case TargetScope.Battlefield: - all.AddRange(p.Field); - 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.Battlefield: all.AddRange(p.Field); 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); + all.AddRange(p.Hand); all.AddRange(p.Deck); + all.AddRange(p.Field); all.AddRange(p.Discard); break; } } - // Type filter. 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(), + 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, }; } @@ -425,16 +350,8 @@ public static class AbilitySystem // ── Effect execution ────────────────────────────────────────────────────── private static void ExecuteEffect( - Effect effect, - object target, - DurationModel? duration, - AbilityContext ctx) + Effect effect, object target, DurationModel? duration, AbilityContext ctx) { - // Instant effects (or no duration specified) are applied directly. - // Duration-tracked effects (UntilEndOfTurn, ForNTurns, etc.) are added - // to ActiveEffects for the cleanup pass. For this first pass we apply - // all effects immediately; the duration model is recorded for future - // cleanup support. switch (effect) { // ── §5.1 Stat modification ───────────────────────────────────────── @@ -444,17 +361,14 @@ public static class AbilitySystem if (mh.StatTarget == StatTarget.Current) { ci.CurrentHealth = (ci.CurrentHealth ?? 0) + amt; - // clamp if (ci.MaxHealth.HasValue) ci.CurrentHealth = Math.Min(ci.CurrentHealth.Value, ci.MaxHealth.Value); - if (ci.CurrentHealth <= 0) - KillUnit(ci, ctx); + if (ci.CurrentHealth <= 0) KillUnit(ci, ctx); } else { ci.MaxHealth = (ci.MaxHealth ?? 0) + amt; - if (ci.CurrentHealth > ci.MaxHealth) - ci.CurrentHealth = ci.MaxHealth; + if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth; } break; } @@ -483,8 +397,7 @@ public static class AbilitySystem ci.MovementType = smt.MovementType; break; case SetAttackRangeEffect sar when target is CardInstance ci: - ci.MinAttackRange = sar.Min; - ci.MaxAttackRange = sar.Max; + ci.MinAttackRange = sar.Min; ci.MaxAttackRange = sar.Max; break; case ModifyCostEffect mc when target is CardInstance ci: if (mc.Sp.HasValue) ci.SpCost = Math.Max(0, ci.SpCost + mc.Sp.Value); @@ -493,163 +406,114 @@ public static class AbilitySystem case SetAffinityEffect sa when target is CardInstance ci: ci.Affinity = ResolveAffinity(sa.Affinity, ctx).ToString(); break; - case GrantAdditionalAttackEffect gaa when target is CardInstance ci: - // Tracked as extra attack count on the unit — store on FieldCard for now. - // Future: add ExtraAttacks property. - break; // ── §5.2 Unit flags ──────────────────────────────────────────────── case SetCanMoveEffect scm when target is CardInstance ci: - ci.CanMove = scm.Value; - break; + ci.CanMove = scm.Value; break; case SetCanAttackEffect sca when target is CardInstance ci: - ci.CanAttack = sca.Value; - break; + ci.CanAttack = sca.Value; break; case SetCanDefendEffect scd when target is CardInstance ci: - ci.CanDefend = scd.Value; - break; - case SetCanBeAttackedEffect scba when target is CardInstance ci: - // CanBeAttacked is tracked as flag on CardInstance; add if absent. - break; - case SetCanUseAbilityEffect scua when target is CardInstance ci: - // CanUseAbility is an implicit flag not yet on CardInstance. - break; + ci.CanDefend = scd.Value; break; // ── §5.2 Player flags ───────────────────────────────────────────── case SetCanDrawCardsEffect scdc when target is PlayerState ps: - ps.CanDrawCards = scdc.Value; - break; + ps.CanDrawCards = scdc.Value; break; case SetAccumulatesSPEffect sasp when target is PlayerState ps: - ps.AccumulatesSP = sasp.Value; - break; + ps.AccumulatesSP = sasp.Value; break; case SetCanChannelSpiritEffect sccsp when target is PlayerState ps: - ps.CanChannelSpirit = sccsp.Value; - break; + ps.CanChannelSpirit = sccsp.Value; break; case SetCanSacrificeSpiritEffect scss when target is PlayerState ps: - ps.CanSacrificeSpirit = scss.Value; - break; + ps.CanSacrificeSpirit = scss.Value; break; case SetCanAscendArchSpiritEffect scaas when target is PlayerState ps: - ps.CanAscendArchSpirit = scaas.Value; - break; + ps.CanAscendArchSpirit = scaas.Value; break; case SetCanTransitionArchSpiritEffect sctas when target is PlayerState ps: - ps.CanTransitionArchSpirit = sctas.Value; - break; + ps.CanTransitionArchSpirit = sctas.Value; break; case SetCanChannelRepentanceEffect sccrep when target is PlayerState ps: - ps.CanChannelRepentance = sccrep.Value; - break; + ps.CanChannelRepentance = sccrep.Value; break; case SetCanChannelInstinctEffect sccin when target is PlayerState ps: - ps.CanChannelInstinct = sccin.Value; - break; + ps.CanChannelInstinct = sccin.Value; break; case SetCanChannelRuinEffect sccru when target is PlayerState ps: - ps.CanChannelRuin = sccru.Value; - break; + ps.CanChannelRuin = sccru.Value; break; case SetCanChannelTerramorphaMonoEffect sctm when target is PlayerState ps: - ps.CanChannelTerramorphaMono = sctm.Value; - break; + ps.CanChannelTerramorphaMono = sctm.Value; break; case SetCanChannelTerramorphaDiEffect sctdi when target is PlayerState ps: - ps.CanChannelTerramorphaDi = sctdi.Value; - break; + ps.CanChannelTerramorphaDi = sctdi.Value; break; case SetCanChannelTerramorphaTriEffect scttri when target is PlayerState ps: - ps.CanChannelTerramorphaTri = scttri.Value; - break; + ps.CanChannelTerramorphaTri = scttri.Value; 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); + if (!ci.Genus.Contains(ag.Tag)) ci.Genus.Add(ag.Tag); break; case RemoveGenusEffect rg when target is CardInstance ci: - ci.Genus?.Remove(rg.Tag); - break; + ci.Genus?.Remove(rg.Tag); 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: - ps.SpAccumulationPerTurn = Math.Max(0, - ps.SpAccumulationPerTurn + ResolveValue(mspa.Amount, ctx)); + ps.SpAccumulationBonus += ResolveValue(mspa.Amount, 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: - ps.CardsDrawnPerTurn = Math.Max(0, - ps.CardsDrawnPerTurn + ResolveValue(mcdpt.Amount, ctx)); + ps.DrawPerTurnBonus += ResolveValue(mcdpt.Amount, 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.BaseAffinity1 = ResolveAffinity(sba1.Affinity, ctx); + 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.BaseAffinity2 = ResolveAffinity(sba2.Affinity, ctx); + 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) - tile.PushAffinity(ResolveAffinity(pa.Affinity, ctx)); + 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.PushFinalAffinity(ResolveAffinity(pfa.Affinity, ctx)); + if (tile is not null) tile.Base2 = ResolveAffinity(pfa.Affinity, ctx); break; } // ── §5.7 Zone / card operations ─────────────────────────────────── case DrawCardsEffect dc: - { - var ps = ResolvePlayerForEffect(dc.Player, ctx); - DrawCards(ps, dc.N); + DrawCards(ResolvePlayerForEffect(dc.Player, ctx), dc.N); break; - } case DiscardCardsEffect dce: - { - var ps = ResolvePlayerForEffect(dce.Player, ctx); - DiscardFromHand(ps, dce.N, dce.Filters, ctx); + 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); - owner.Hand.Add(ci); - } + 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); - PlaceInDeck(owner, ci, rtd.Position); - } + if (owner is not null) { RemoveFromAllZones(owner, ci, ctx.State.Board); PlaceInDeck(owner, ci, rtd.Position); } break; } case SendToDiscardEffect when target is CardInstance ci: { var owner = FindCardOwner(ctx.State, ci.InstanceId); - if (owner is not null) - { - RemoveFromAllZones(owner, ci); - owner.Discard.Add(ci); - } + if (owner is not null) { RemoveFromAllZones(owner, ci, ctx.State.Board); owner.Discard.Add(ci); } break; } case ShuffleDeckEffect sde: @@ -669,12 +533,9 @@ public static class AbilitySystem ApplyDamageToUnit(ci, ResolveValue(dd.Amount, ctx), dd.BypassDefense, ctx); break; case HealEffect he when target is CardInstance ci: - { - int amt = ResolveValue(he.Amount, ctx); ci.CurrentHealth = Math.Min(ci.MaxHealth ?? int.MaxValue, - (ci.CurrentHealth ?? 0) + amt); + (ci.CurrentHealth ?? 0) + ResolveValue(he.Amount, ctx)); break; - } case DealDamageToSelfEffect ddself: if (ctx.Source is not null) ApplyDamageToUnit(ctx.Source, ResolveValue(ddself.Amount, ctx), @@ -683,25 +544,19 @@ public static class AbilitySystem // ── §5.9 Displacement ───────────────────────────────────────────── case PushUnitEffect pu when target is FieldCard fc2: - DisplaceUnit(fc2, pu.Tiles, fromSource: true, ctx); - break; + DisplaceUnit(fc2, pu.Tiles, fromSource: true, ctx); break; case PullUnitEffect pull when target is FieldCard fc3: - DisplaceUnit(fc3, pull.Tiles, fromSource: false, ctx); - break; + DisplaceUnit(fc3, pull.Tiles, fromSource: false, ctx); break; // ── §5.10 Control ───────────────────────────────────────────────── - case TakeControlEffect tce when target is FieldCard fc4: + case TakeControlEffect when target is FieldCard fc4: { - // Move unit to controller's field. var originalOwner = FindCardOwner(ctx.State, fc4.InstanceId); - if (originalOwner is not null) - originalOwner.Field.Remove(fc4); - var newOwner = ctx.State.Players[ctx.ActorId]; - newOwner.Field.Add(fc4); + if (originalOwner is not null) originalOwner.Field.Remove(fc4); + ctx.State.Players[ctx.ActorId].Field.Add(fc4); break; } - // Unhandled effects are silently ignored in this pass. default: break; } @@ -710,19 +565,13 @@ public static class AbilitySystem // ── Damage helper ───────────────────────────────────────────────────────── private static void ApplyDamageToUnit( - CardInstance unit, - int rawAmount, - bool bypassDefense, - AbilityContext ctx) + CardInstance unit, int rawAmount, bool bypassDefense, AbilityContext ctx) { - int netDamage = bypassDefense + int net = bypassDefense ? rawAmount : Math.Max(0, rawAmount - (unit.CurrentDefense ?? 0)); - - unit.CurrentHealth = (unit.CurrentHealth ?? 0) - netDamage; - - if (unit.CurrentHealth <= 0) - KillUnit(unit, ctx); + unit.CurrentHealth = (unit.CurrentHealth ?? 0) - net; + if (unit.CurrentHealth <= 0) KillUnit(unit, ctx); } private static void KillUnit(CardInstance unit, AbilityContext ctx) @@ -730,18 +579,16 @@ public static class AbilitySystem var owner = FindCardOwner(ctx.State, unit.InstanceId); if (owner is null) return; - if (unit is FieldCard fc && fc.Position.HasValue && ctx.State.Board is not null) - ctx.State.Board.ClearUnit(fc.Position.Value); - - RemoveFromAllZones(owner, unit); + 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 }, + Kind = TriggerEventKind.UnitDeath, + ActorId = ctx.ActorId, + Data = new TriggerEventData { TargetId = unit.InstanceId }, UnitType = unit.CardType, }); } @@ -749,10 +596,7 @@ public static class AbilitySystem // ── Displacement helper ─────────────────────────────────────────────────── private static void DisplaceUnit( - FieldCard unit, - int tiles, - bool fromSource, - AbilityContext ctx) + 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) @@ -760,25 +604,25 @@ public static class AbilitySystem var srcPos = srcFc.Position.Value; var unitPos = unit.Position.Value; - - // Direction: fromSource = push away from source; !fromSource = pull towards source. int dx = unitPos.X - srcPos.X; int dy = unitPos.Y - srcPos.Y; - if (dx == 0 && dy == 0) return; - // Normalise to unit direction. - int stepX = dx == 0 ? 0 : Math.Sign(dx); - int stepY = dy == 0 ? 0 : Math.Sign(dy); + 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.GetUnit(newPos) is not null) return; + if (!board.IsInBounds(newPos) || !board.GetTile(newPos)!.IsEmpty) return; - board.ClearUnit(unitPos); - board.PlaceUnit(newPos, unit.InstanceId); + 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; } @@ -795,21 +639,12 @@ public static class AbilitySystem } private static void DiscardFromHand( - PlayerState player, - int n, - Filter[]? filters, - AbilityContext ctx) + 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); - } + .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) @@ -820,13 +655,13 @@ public static class AbilitySystem case "random": int idx = new Random().Next(player.Deck.Count + 1); player.Deck.Insert(idx, card); break; - default: // top - player.Deck.Add(card); break; + default: player.Deck.Add(card); break; } } - private static void RemoveFromAllZones(PlayerState player, CardInstance card) + private static void RemoveFromAllZones(PlayerState player, CardInstance card, Board? board) { + if (board is not null) board.RemoveUnit(card.InstanceId); player.Hand.Remove(card); player.Deck.Remove(card); player.Field.Remove(card); @@ -837,44 +672,34 @@ public static class AbilitySystem { 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.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) - { - return playerRef.ToLowerInvariant() switch + => playerRef.ToLowerInvariant() switch { - "enemy" or "opponent" => ctx.State.Players.Values - .First(p => p.AccountId != ctx.ActorId), + "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) + Condition condition, AbilityContext ctx, object subject) { - // Resolve subject override. - if (condition.Subject == "Target") - { - // Use the most recent resolved target in the context. - if (ctx.ResolvedTargets.Count > 0) - subject = ctx.ResolvedTargets.Values.Last().FirstOrDefault() ?? 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) { - // Composite case AndCondition and: return and.Conditions.All(c => EvaluateCondition(c, ctx, subject)); case OrCondition or: @@ -882,7 +707,6 @@ public static class AbilitySystem case XorCondition xor: return xor.Conditions.Count(c => EvaluateCondition(c, ctx, subject)) == 1; - // Unit (§6.1) case HealthBelowCondition hb when subject is CardInstance ci: return (ci.CurrentHealth ?? 0) < hb.N; case HealthAboveCondition ha when subject is CardInstance ci: @@ -892,59 +716,44 @@ public static class AbilitySystem case HasGenusCondition hg when subject is CardInstance ci: return ci.Genus?.Contains(hg.Tag) == true; case HasAbilityCondition hab when subject is CardInstance ci: - { - var abilities = ParseAbilities(ci.AbilitiesJson); - return abilities.Any(a => a.Name == hab.AbilityRef); - } + 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?.CurrentAffinity == iotwa.Affinity; + 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; - // Player (§6.2) - 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 dissal: - return player.Discard.Count >= dissal.N; + 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; - // Turn/timing (§6.4) case IsOwnTurnCondition: return ctx.State.ActivePlayerAccountId == ctx.ActorId; case IsOpponentTurnCondition: return ctx.State.ActivePlayerAccountId != ctx.ActorId; case IsAllyTurnCondition: - return ctx.State.ActivePlayerAccountId == ctx.ActorId; // same as own in 1v1 + return ctx.State.ActivePlayerAccountId == ctx.ActorId; case IsActivePlayerTurnCondition iaptc: return iaptc.Ownership.ToLowerInvariant() == "owner" ? ctx.State.ActivePlayerAccountId == ctx.ActorId : ctx.State.ActivePlayerAccountId != ctx.ActorId; - // Battlefield (§6.5) case UnitCountOnBattlefieldCondition ucob: { - IEnumerable pool; - if (ucob.Ownership.ToLowerInvariant() == "enemy") - pool = ctx.State.Players.Values - .Where(p => p.AccountId != ctx.ActorId) - .SelectMany(p => p.Field); - else - pool = player.Field; + 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); @@ -963,7 +772,7 @@ public static class AbilitySystem } default: - return true; // unknown conditions pass by default + return true; } } @@ -973,110 +782,110 @@ public static class AbilitySystem => filters.All(f => FilterMatches(f, card, ctx)); private static bool FilterMatches(Filter filter, CardInstance card, AbilityContext ctx) - { - switch (filter) + => filter switch { - case CardTypeIsFilter ctif: - return card.CardType == ctif.CardType; - case AffinityMatchesFilter amf: - return card.Affinity == amf.Affinity.ToString(); - case HasFlagFilter hff: - return hff.Flag switch - { - "IsLeader" => card.IsLeader, - "IsExhausted" => card.IsExhausted, - "CanMove" => card.CanMove, - "CanAttack" => card.CanAttack, - _ => false, - }; - case TierIsFilter tif: - return card.Tier == tif.Tier; - case IsSelfFilter: - return ctx.Source is not null && card.InstanceId == ctx.Source.InstanceId; - case HealthBelowFilter hbf: - return (card.CurrentHealth ?? 0) < hbf.N; - case HealthAboveFilter haf: - return (card.CurrentHealth ?? 0) > haf.N; - default: - return 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, + IsSelfFilter => ctx.Source is not null && card.InstanceId == ctx.Source.InstanceId, + HealthBelowFilter hbf => (card.CurrentHealth ?? 0) < hbf.N, + HealthAboveFilter haf => (card.CurrentHealth ?? 0) > haf.N, + _ => true, + }; // ── Trigger matching ────────────────────────────────────────────────────── private static bool TriggerMatches( - TriggerEvent trigger, - TriggerOccurrence occurrence, - GameState state, - string ownerId) - { - return trigger switch + TriggerEvent trigger, TriggerOccurrence occurrence, GameState state, string ownerId) + => trigger switch { - OnTurnStartTrigger t => occurrence.Kind == TriggerEventKind.TurnStart - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnTurnEndTrigger t => occurrence.Kind == TriggerEventKind.TurnEnd - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnUnitDeathTrigger t => occurrence.Kind == TriggerEventKind.UnitDeath - && MatchesUnitType(t.UnitType, occurrence.UnitType) - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnDamageDealtTrigger t => occurrence.Kind == TriggerEventKind.DamageDealt - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnUnitEnterBattlefieldTrigger t => occurrence.Kind == TriggerEventKind.UnitEnterBattlefield - && MatchesUnitType(t.UnitType, occurrence.UnitType) - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnUnitLeaveBattlefieldTrigger t => occurrence.Kind == TriggerEventKind.UnitLeaveBattlefield - && MatchesUnitType(t.UnitType, occurrence.UnitType) - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnSPGainedTrigger t => occurrence.Kind == TriggerEventKind.SPGained - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnSPSpentTrigger t => occurrence.Kind == TriggerEventKind.SPSpent - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnSTGainedTrigger t => occurrence.Kind == TriggerEventKind.STGained - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnSTSpentTrigger t => occurrence.Kind == TriggerEventKind.STSpent - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnCardDrawnTrigger t => occurrence.Kind == TriggerEventKind.CardDrawn - && MatchesOwnership(t.PlayerScope, occurrence.ActorId, ownerId, state), - OnUnitMoveTrigger t => occurrence.Kind == TriggerEventKind.UnitMove - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnUnitAttackTrigger t => occurrence.Kind == TriggerEventKind.UnitAttack - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnSpiritSacrificedTrigger t => occurrence.Kind == TriggerEventKind.SpiritSacrificed - && MatchesOwnership(t.Ownership, occurrence.ActorId, ownerId, state), - OnAscendTrigger => occurrence.Kind == TriggerEventKind.Ascend, - OnTransitionTrigger => occurrence.Kind == TriggerEventKind.Transition, - OnChanneledTrigger t => occurrence.Kind == TriggerEventKind.Channeled - && MatchesCardType(t.CardType, occurrence.CardType), + OnTurnStartTrigger t => + occurrence.Kind == TriggerEventKind.TurnStart + && Own(t.Player, occurrence, ownerId, state), + OnTurnEndTrigger t => + occurrence.Kind == TriggerEventKind.TurnEnd + && Own(t.Player, occurrence, ownerId, state), + OnUnitDeathTrigger t => + occurrence.Kind == TriggerEventKind.UnitDeath + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state), + OnDamageDealtTrigger => + occurrence.Kind == TriggerEventKind.DamageDealt, + OnUnitEnterBattlefieldTrigger t => + occurrence.Kind == TriggerEventKind.UnitEnterBattlefield + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state), + OnUnitLeaveBattlefieldTrigger t => + occurrence.Kind == TriggerEventKind.UnitLeaveBattlefield + && UnitType(t.UnitType, occurrence.UnitType) + && Own(t.Ownership, occurrence, ownerId, state), + OnSPGainedTrigger t => + occurrence.Kind == TriggerEventKind.SPGained + && Own(t.Player, occurrence, ownerId, state), + OnSPSpentTrigger t => + occurrence.Kind == TriggerEventKind.SPSpent + && Own(t.Player, occurrence, ownerId, state), + OnSTGainedTrigger t => + occurrence.Kind == TriggerEventKind.STGained + && Own(t.Player, occurrence, ownerId, state), + OnSTSpentTrigger t => + occurrence.Kind == TriggerEventKind.STSpent + && Own(t.Player, occurrence, ownerId, state), + OnCardDrawnTrigger t => + occurrence.Kind == TriggerEventKind.CardDrawn + && Own(t.Player, occurrence, ownerId, state), + OnUnitMoveTrigger t => + occurrence.Kind == TriggerEventKind.UnitMove + && Own(t.Ownership, occurrence, ownerId, state), + OnUnitAttackTrigger t => + occurrence.Kind == TriggerEventKind.UnitAttack + && Own(t.Ownership, occurrence, ownerId, state), + OnSpiritSacrificedTrigger t => + occurrence.Kind == TriggerEventKind.SpiritSacrificed + && Own(t.Ownership, occurrence, ownerId, state), + OnAscendTrigger t => + occurrence.Kind == TriggerEventKind.Ascend + && Own(t.Ownership, occurrence, ownerId, state), + OnTransitionTrigger t => + occurrence.Kind == TriggerEventKind.Transition + && Own(t.Ownership, occurrence, ownerId, state), + OnChanneledTrigger t => + occurrence.Kind == TriggerEventKind.Channeled + && CardType(t.CardType, occurrence.CardType) + && Own(t.Ownership, occurrence, ownerId, state), _ => false, }; - } - private static bool MatchesOwnership(string? scope, string eventActorId, string unitOwnerId, GameState state) - { - return (scope?.ToLowerInvariant()) switch + private static bool Own(string? scope, TriggerOccurrence occ, string unitOwnerId, GameState _) + => (scope?.ToLowerInvariant()) switch { - null or "any" => true, - "own" or "self" => eventActorId == unitOwnerId, - "enemy" => eventActorId != unitOwnerId, - "ally" => eventActorId == unitOwnerId, + null or "any" => true, + "own" or "self" or "owner" => occ.ActorId == unitOwnerId, + "enemy" => occ.ActorId != unitOwnerId, + "ally" => occ.ActorId == unitOwnerId, _ => true, }; - } - private static bool MatchesUnitType(string? required, string? actual) - => required is null || required == "Any" || required == actual; + private static bool UnitType(string? required, string? actual) + => required is null or "Unit" or "Any" || required == actual; - private static bool MatchesCardType(string? required, string? actual) - => required is null || required == "Any" || required == actual; + private static bool CardType(string? required, string? actual) + => required is null or "Any" || required == actual; - // ── Value resolution ────────────────────────────────────────────────────── + // ── 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; - - // Simple dynamic reference resolution: "EventData.Amount", "Self.Damage", etc. var parts = expr.Ref.Split('.'); return (parts[0], parts.Length > 1 ? parts[1] : "") switch { @@ -1092,14 +901,13 @@ public static class AbilitySystem private static Affinity ResolveAffinity(AffinityExpr expr, AbilityContext ctx) { if (expr.Fixed.HasValue) return expr.Fixed.Value; - if (expr.Ref is null) return Affinity.Neutral; - + 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.Neutral, - _ => Affinity.Neutral, + Enum.TryParse(ctx.Source.Affinity, out var a) ? a : Affinity.Void, + _ => Affinity.Void, }; } } diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index ae05856..f02abe3 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -4,6 +4,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using SOR.Database.Entities.Catalog; using SOR.Database.Enums; +using SOR.Game.Abilities; using SOR.Game.Combat; using SOR.Game.Grid; @@ -230,6 +231,21 @@ public static class GameEngine var field = ToFieldCard(card, coord); player.Field.Add(field); board.PlaceUnit(coord, field.InstanceId, actorId); + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Channeled, + ActorId = actorId, + CardType = "Spirit", + Data = new TriggerEventData { SourceId = field.InstanceId }, + }); + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitEnterBattlefield, + ActorId = actorId, + UnitType = "Spirit", + Data = new TriggerEventData { SourceId = field.InstanceId }, + }); } else if (card.CardType == "Terramorpha") { @@ -264,15 +280,32 @@ public static class GameEngine AffinitySystem.PushAffinity(board.GetTile(t)!, affinity); player.Discard.Add(card); + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Channeled, + ActorId = actorId, + CardType = "Terramorpha", + }); } else { - // Repentance, Instinct, Ruin — pay cost and discard. - // Full effect resolution deferred to AbilitySystem (future). + // Repentance, Instinct, Ruin — pay cost, fire EffectsJson actions, then discard. player.Hand.Remove(card); player.CurrentSp -= card.SpCost; player.CurrentSt -= card.StCost; + + // Fire inline effects if the card has an EffectsJson action list. + AbilitySystem.FireCardEffects(state, actorId, card); + player.Discard.Add(card); + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Channeled, + ActorId = actorId, + CardType = card.CardType, + }); } return state; @@ -333,6 +366,13 @@ public static class GameEngine player.ArchSpirit = newArchSpirit; board.PlaceUnit(coord, newArchSpirit.InstanceId, actorId); + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Ascend, + ActorId = actorId, + Data = new TriggerEventData { SourceId = newArchSpirit.InstanceId }, + }); + return state; } @@ -384,6 +424,13 @@ public static class GameEngine player.ArchSpirit = newArchSpirit; board.PlaceUnit(coord, newArchSpirit.InstanceId, actorId); + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Transition, + ActorId = actorId, + Data = new TriggerEventData { SourceId = newArchSpirit.InstanceId }, + }); + return state; } @@ -449,6 +496,14 @@ public static class GameEngine unit.Position = targetPos; board.MoveUnit(unitInstanceId, targetPos); + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitMove, + ActorId = actorId, + UnitType = unit.CardType, + Data = new TriggerEventData { SourceId = unitInstanceId }, + }); + return state; } @@ -504,10 +559,30 @@ public static class GameEngine var activePlayer = state.Players[actorId]; var opponentPlayer = state.Players[opponentId]; + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitAttack, + ActorId = actorId, + UnitType = attacker.CardType, + Data = new TriggerEventData + { + SourceId = attackerInstanceId, + TargetId = targetInstanceId, + }, + }); + if (attacker.CurrentHealth <= 0) { if (state.Board is not null) state.Board.RemoveUnit(attacker.InstanceId); MoveToDiscard(activePlayer, attacker); + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitDeath, + ActorId = actorId, + UnitType = attacker.CardType, + Data = new TriggerEventData { TargetId = attacker.InstanceId }, + }); } if (target.CurrentHealth <= 0) @@ -521,6 +596,14 @@ public static class GameEngine { if (state.Board is not null) state.Board.RemoveUnit(target.InstanceId); MoveToDiscard(opponentPlayer, target); + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitDeath, + ActorId = opponentId, + UnitType = target.CardType, + Data = new TriggerEventData { TargetId = target.InstanceId }, + }); } } @@ -559,6 +642,14 @@ public static class GameEngine player.Field.Remove(unit); player.Discard.Add(unit); + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.SpiritSacrificed, + ActorId = actorId, + UnitType = unit.CardType, + Data = new TriggerEventData { SourceId = actorId, TargetId = unitInstanceId }, + }); + return state; } @@ -579,12 +670,24 @@ public static class GameEngine ValidateActivePlayer(state, actorId); ValidatePhase(state, GamePhase.Main); - // Reset exhausted for the player ending their turn. + // Reset exhausted and ability uses for the player ending their turn. var active = state.Players[actorId]; foreach (var card in active.Field.OfType()) - card.IsExhausted = false; + { + card.IsExhausted = false; + card.AbilityUsesThisTurn = null; + } if (active.ArchSpirit is not null) - active.ArchSpirit.IsExhausted = false; + { + active.ArchSpirit.IsExhausted = false; + active.ArchSpirit.AbilityUsesThisTurn = null; + } + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.TurnEnd, + ActorId = actorId, + }); // Switch active player. state.ActivePlayerAccountId = GetOpponentId(state, actorId); @@ -605,12 +708,18 @@ public static class GameEngine if (next.ArchSpirit.MaxDefense.HasValue) next.ArchSpirit.CurrentDefense = next.ArchSpirit.MaxDefense; } - next.CurrentSp += rules.SpAccumulationPerTurn; + next.CurrentSp += rules.SpAccumulationPerTurn + next.SpAccumulationBonus; if (rules.SpHasCap && next.CurrentSp > rules.SpCap) next.CurrentSp = rules.SpCap; state.Phase = GamePhase.Draw; + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.TurnStart, + ActorId = state.ActivePlayerAccountId, + }); + return state; } @@ -621,6 +730,32 @@ public static class GameEngine return state; } + /// + /// Activate an Active ability on a field unit owned by the active player. + /// Validates turn / phase, delegates cost + effect resolution to AbilitySystem. + /// + public static GameState ActivateAbility( + GameState state, + string actorId, + string sourceInstanceId, + int abilityIndex, + IReadOnlyList? targets) + { + ValidateActivePlayer(state, actorId); + ValidatePhase(state, GamePhase.Main); + + state = AbilitySystem.ActivateAbility(state, actorId, sourceInstanceId, abilityIndex, targets); + + AbilitySystem.FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitAbilityActivated, + ActorId = actorId, + Data = new TriggerEventData { SourceId = sourceInstanceId }, + }); + + return state; + } + // ── DTO projection ──────────────────────────────────────────────────────── /// @@ -723,6 +858,8 @@ public static class GameEngine Position = null, Tier = archSpiritDef.Tier, PreviousTierId = archSpiritDef.PreviousTierId, + AbilitiesJson = archSpiritDef.AbilitiesJson, + EffectsJson = archSpiritDef.EffectsJson, }; ps.CurrentSp = 0; @@ -760,6 +897,8 @@ public static class GameEngine Tier = def.Tier, PreviousTierId = def.PreviousTierId, TerramorphaMode = def.TerramorphaMode, + AbilitiesJson = def.AbilitiesJson, + EffectsJson = def.EffectsJson, }; private static void DrawCards(PlayerState player, int count) @@ -868,6 +1007,8 @@ public static class GameEngine Tier = source.Tier, PreviousTierId = source.PreviousTierId, TerramorphaMode = source.TerramorphaMode, + AbilitiesJson = source.AbilitiesJson, + EffectsJson = source.EffectsJson, Position = position, }; diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 566d22c..86db6d0 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -67,6 +67,17 @@ public sealed record GameAscendRequest(Guid SessionId, string IncomingCardInstan /// public sealed record GameTransitionRequest(Guid SessionId, string IncomingCardInstanceId); +/// +/// Activate an Active ability on one of the player's field units. +/// AbilityIndex is 0-based into the source unit's AbilitiesJson array. +/// Targets is required when the ability needs player-chosen targets. +/// +public sealed record GameActivateAbilityRequest( + Guid SessionId, + string SourceInstanceId, + int AbilityIndex, + IReadOnlyList? Targets = null); + // ── Custom lobby requests ───────────────────────────────────────────────────── /// Create a new custom lobby. Host provides their deck and optional rule overrides. @@ -125,6 +136,8 @@ public sealed record GameAscendResponse(GameStateDto State); public sealed record GameTransitionResponse(GameStateDto State); +public sealed record GameActivateAbilityResponse(GameStateDto State); + // ── Custom lobby responses ───────────────────────────────────────────────────── public sealed record CreateCustomLobbyResponse( @@ -255,3 +268,15 @@ public sealed record CustomRulesDto( int SpCap, int BoardWidth, int BoardHeight); + +/// +/// A single client-provided target for one action in an ability. +/// Exactly one of InstanceId or Coord should be set, matching the action's TargetType. +/// +public sealed record AbilityTarget( + /// 0-based index of the ability action this target satisfies. + int ActionIndex, + /// Set for unit/card targets. + string? InstanceId = null, + /// Set for tile targets. + CoordDto? Coord = null); diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 2932ae8..1d8afa0 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -34,6 +34,12 @@ public sealed class GameState /// Created during GameEngine.Initialize and populated during the Placement phase. /// public Board? Board { get; set; } + + /// + /// Duration-tracked effects currently active on units or players. + /// Decremented / expired during EndTurn processing. + /// + public List ActiveEffects { get; set; } = new(); } public sealed class PlayerState @@ -61,6 +67,35 @@ public sealed class PlayerState /// public int CurrentSt { get; set; } + /// + /// Per-player SP accumulation bonus added on top of GameRules.SpAccumulationPerTurn. + /// Modified by ModifySPAccumulationEffect. Resets when the effect expires. + /// + public int SpAccumulationBonus { get; set; } + + /// + /// Per-player bonus to cards drawn per turn, stacked on top of GameRules.DrawPerTurn. + /// Modified by ModifyCardsDrawnPerTurnEffect. + /// + public int DrawPerTurnBonus { get; set; } + + // ── Action-restriction flags (set by ability effects) ───────────────────── + + /// False when an effect prohibits drawing cards this turn. + public bool CanDrawCards { get; set; } = true; + /// False when an effect stops SP accumulating at turn start. + public bool AccumulatesSP { get; set; } = true; + public bool CanChannelSpirit { get; set; } = true; + public bool CanSacrificeSpirit { get; set; } = true; + public bool CanAscendArchSpirit { get; set; } = true; + public bool CanTransitionArchSpirit { get; set; } = true; + public bool CanChannelRepentance { get; set; } = true; + public bool CanChannelInstinct { get; set; } = true; + public bool CanChannelRuin { get; set; } = true; + public bool CanChannelTerramorphaMono { get; set; } = true; + public bool CanChannelTerramorphaDi { get; set; } = true; + public bool CanChannelTerramorphaTri { get; set; } = true; + // ── Leader ─────────────────────────────────────────────────────────────── /// @@ -151,6 +186,33 @@ public class CardInstance /// requires when channeled. Mirrored from CardDefinition. /// public TerramorphaMode? TerramorphaMode { get; set; } + + // ── Abilities ───────────────────────────────────────────────────────────── + + /// + /// Snapshot of CardDefinition.AbilitiesJson copied at game start. + /// Allows GameEngine to evaluate triggered/active abilities without DB access. + /// Format: JSON array of AbilityDefinition. + /// + public string? AbilitiesJson { get; set; } + + /// + /// Snapshot of CardDefinition.EffectsJson (for Repentance/Instinct/Ruin cards). + /// Format: JSON array of Action (resolved once when the card is channeled). + /// + public string? EffectsJson { get; set; } + + /// + /// Tracks Active ability uses this turn. Key = ability index, value = use count. + /// Reset to empty at the start of the owning player's turn (in EndTurn). + /// + public Dictionary? AbilityUsesThisTurn { get; set; } + + /// + /// Genus tags on this unit (e.g. "Beast", "Plant"). May be modified by abilities. + /// Null until at least one genus tag is added. + /// + public List? Genus { get; set; } } /// @@ -165,3 +227,27 @@ public sealed class FieldCard : CardInstance /// Remaining movement points this turn. public int CurrentMp { get; set; } } + +/// +/// A duration-tracked effect currently applied to a unit or player. +/// Stored in GameState.ActiveEffects; decremented / expired during EndTurn. +/// +public sealed class ActiveEffect +{ + /// InstanceId of the unit that applied this effect. + public string SourceInstanceId { get; set; } = string.Empty; + + /// + /// InstanceId of the affected unit, or AccountId of the affected player. + /// + public string TargetRef { get; set; } = string.Empty; + + /// Serialized effect JSON (round-trips via AbilitySystem JSON options). + public string EffectJson { get; set; } = "{}"; + + /// Duration model as serialized JSON. + public string DurationJson { get; set; } = "{}"; + + /// Remaining turns for ForNTurns durations. Decremented at turn start. + public int TurnsRemaining { get; set; } +} diff --git a/Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs b/Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs new file mode 100644 index 0000000..8cddd37 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs @@ -0,0 +1,55 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.activate_ability — active player fires an Active ability on one of their field units. +/// +/// AbilityIndex is 0-based into the source unit's AbilitiesJson ability array. +/// Targets is optional; required when the ability needs player-chosen targets. +/// +internal sealed class GameActivateAbilityHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameActivateAbilityHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.activate_ability"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var state = GameEngine.Deserialize(session.StateJson!); + var newState = GameEngine.ActivateAbility( + state, actorId, req.SourceInstanceId, req.AbilityIndex, req.Targets); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.activate_ability", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct); + + return ServerMessage.Reply("game.activate_ability.ack", message.Seq, + new GameActivateAbilityResponse(GameEngine.ToDto(newState, actorId))); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index e2af6dd..cddd8e0 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -31,6 +31,7 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient();