diff --git a/Server/src/SOR.Game/Abilities/AbilityContext.cs b/Server/src/SOR.Game/Abilities/AbilityContext.cs new file mode 100644 index 0000000..397f99c --- /dev/null +++ b/Server/src/SOR.Game/Abilities/AbilityContext.cs @@ -0,0 +1,87 @@ +namespace SOR.Game.Abilities; + +using SOR.Game.Abilities.Models; +using SOR.Game.Grid; + +/// +/// Captures the runtime state and bookkeeping needed to evaluate a single ability activation +/// or triggered ability firing — including the source unit, owner, and any chained target results. +/// +public sealed class AbilityContext +{ + public required GameState State { get; init; } + public required string ActorId { get; init; } + + /// The unit (ArchSpirit or Spirit) that owns the ability being resolved. + public CardInstance? Source { get; init; } + + /// + /// Resolved targets keyed by action index (0-based). + /// Populated incrementally as actions resolve, enabling chained targeting. + /// Each value is a list of the resolved target objects (CardInstance, Coord, or string for playerId). + /// + public Dictionary> ResolvedTargets { get; } = new(); + + /// + /// Optional payload from the triggering event — available to Triggered ability actions. + /// + public TriggerEventData? EventData { get; init; } +} + +/// +/// Payload data from the event that caused a Triggered ability to fire. +/// Fields are populated according to the event type; unused fields are null. +/// +public sealed class TriggerEventData +{ + /// Numeric magnitude of the event (damage amount, SP gained, etc.). + public int? Amount { get; init; } + /// Instance ID of the unit/player that caused the event. + public string? SourceId { get; init; } + /// Instance ID of the unit/player the event acted upon. + public string? TargetId { get; init; } +} + +/// +/// Discriminates which kind of entity a runtime trigger event is carrying. +/// Used by AbilitySystem.FireTrigger to match against AbilityDefinition.TriggerEvent. +/// +public enum TriggerEventKind +{ + TurnStart, + TurnEnd, + Channeled, + Ascend, + Transition, + UnitMove, + UnitAttack, + UnitAbilityActivated, + DamageDealt, + UnitDeath, + SpiritSacrificed, + UnitEnterBattlefield, + UnitLeaveBattlefield, + SPGained, + SPSpent, + STGained, + STSpent, + CardDrawn, + TileAffinityChanged, +} + +/// +/// Describes a single triggered-event occurrence, used when calling +/// . +/// +public sealed class TriggerOccurrence +{ + public required TriggerEventKind Kind { get; init; } + /// The player whose units/actions caused this event. + public required string ActorId { get; init; } + /// Optional event data (damage amount, source/target IDs, etc.). + public TriggerEventData? Data { get; init; } + /// For unit-related events: the card type string ("Spirit", "ArchSpirit", etc.). + public string? UnitType { get; init; } + /// For channeling events: the card type string ("Spirit", "Terramorpha", etc.). + public string? CardType { get; init; } +} diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index f63b3ee..bc5dcc4 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -1,16 +1,1105 @@ namespace SOR.Game.Abilities; +using System.Text.Json; +using SOR.Database.Enums; +using SOR.Game.Abilities.Models; +using SOR.Game.Grid; + /// -/// Ability activation and resolution stub. +/// Evaluates and resolves ability activations and triggered ability firings. /// -/// Full ability model is defined in Shared/context-files/abilities.md. -/// Types: Activated, Triggered, Static, Instinct. -/// Costs: SP, ST, discard, mill, self-damage, etc. -/// Targets: units, tiles, players, zones. -/// Durations: UntilEndOfTurn, UntilStartOfOwnerTurn, ForNTurns, WhileCondition, PermanentInMatch. -/// -/// TODO: Implement full ability model in a future pass. +/// 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 shared across all parse calls ───────────────────────────── + + private static readonly JsonSerializerOptions _jsonOpts = new() + { + PropertyNameCaseInsensitive = true, + }; + + // ── 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. + /// Returns the mutated game state. + /// + public static GameState ActivateAbility( + GameState state, + string actorId, + string sourceInstanceId, + 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) + ?? throw new GameException("UNIT_NOT_FOUND"); + + 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"); + + var def = abilities[abilityIndex]; + + 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, + }; + + // 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; + } + + // ── Triggered ability firing ─────────────────────────────────────────────── + + /// + /// Called from GameEngine mutation methods to fire any Triggered abilities + /// that match the given occurrence. Scans every unit on the battlefield. + /// + 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(); + 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)) 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); + } + } + + // 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) + { + 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"); + 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; + } + } + } + } + + // ── Action execution ────────────────────────────────────────────────────── + + private static void ExecuteActions( + Models.Action[] actions, + AbilityContext ctx, + IReadOnlyList? clientTargets) + { + for (int i = 0; i < actions.Length; i++) + ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i); + } + + private static void ExecuteSingleAction( + Models.Action action, + AbilityContext ctx, + 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 + + // 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 ───────────────────────────────────────────────────── + + private static List ResolveTargets( + TargetSelector selector, + AbilityContext ctx, + IReadOnlyList? clientTargets, + int actionIndex) + { + var state = ctx.State; + var player = state.Players[ctx.ActorId]; + + // For player targets — return the player state objects. + if (selector.Type == TargetType.Player) + { + return selector.Ownership switch + { + TargetOwnership.Owner or TargetOwnership.Self => + [player], + TargetOwnership.Enemy => + 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 []; + return clientTargets + .Where(t => t.ActionIndex == actionIndex && t.Coord is not null) + .Select(t => (object)new Coord(t.Coord!.X, t.Coord!.Y)) + .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(); + + // 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(); + if (clientIds.Count > 0) + candidates = candidates + .Where(c => c is CardInstance ci && clientIds.Contains(ci.InstanceId)) + .ToList(); + } + + // Enforce count. + 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 BuildCandidates( + 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 + _ => state.Players.Keys, + }; + + foreach (var ownerId in ownerIds) + { + 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.AnyZone: + 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(), + _ => all, + }; + } + + // ── Effect execution ────────────────────────────────────────────────────── + + private static void ExecuteEffect( + 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 ───────────────────────────────────────── + 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; + // clamp + 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; + } + 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; + break; + } + case ModifyDamageEffect mdam when target is CardInstance ci: + ci.Damage = Math.Max(0, (ci.Damage ?? 0) + ResolveValue(mdam.Amount, 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); + break; + } + case SetMovementTypeEffect smt when target is CardInstance ci: + ci.MovementType = smt.MovementType; + break; + case SetAttackRangeEffect sar when target is CardInstance ci: + 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); + if (mc.St.HasValue) ci.StCost = Math.Max(0, ci.StCost + mc.St.Value); + break; + 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; + case SetCanAttackEffect sca when target is CardInstance ci: + 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; + + // ── §5.2 Player flags ───────────────────────────────────────────── + case SetCanDrawCardsEffect scdc when target is PlayerState ps: + ps.CanDrawCards = scdc.Value; + break; + case SetAccumulatesSPEffect sasp when target is PlayerState ps: + ps.AccumulatesSP = sasp.Value; + break; + case SetCanChannelSpiritEffect sccsp when target is PlayerState ps: + ps.CanChannelSpirit = sccsp.Value; + break; + case SetCanSacrificeSpiritEffect scss when target is PlayerState ps: + ps.CanSacrificeSpirit = scss.Value; + break; + case SetCanAscendArchSpiritEffect scaas when target is PlayerState ps: + ps.CanAscendArchSpirit = scaas.Value; + break; + case SetCanTransitionArchSpiritEffect sctas when target is PlayerState ps: + ps.CanTransitionArchSpirit = sctas.Value; + break; + case SetCanChannelRepentanceEffect sccrep when target is PlayerState ps: + ps.CanChannelRepentance = sccrep.Value; + break; + case SetCanChannelInstinctEffect sccin when target is PlayerState ps: + ps.CanChannelInstinct = sccin.Value; + break; + case SetCanChannelRuinEffect sccru when target is PlayerState ps: + ps.CanChannelRuin = sccru.Value; + break; + case SetCanChannelTerramorphaMonoEffect sctm when target is PlayerState ps: + ps.CanChannelTerramorphaMono = sctm.Value; + break; + case SetCanChannelTerramorphaDiEffect sctdi when target is PlayerState ps: + ps.CanChannelTerramorphaDi = sctdi.Value; + break; + case SetCanChannelTerramorphaTriEffect scttri when target is PlayerState ps: + 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); + break; + case RemoveGenusEffect rg when target is CardInstance ci: + 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)); + 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)); + 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); + 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); + 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)); + break; + } + case PushFinalAffinityEffect pfa when target is Coord coord: + { + var tile = ctx.State.Board?.GetTile(coord); + if (tile is not null) + tile.PushFinalAffinity(ResolveAffinity(pfa.Affinity, ctx)); + break; + } + + // ── §5.7 Zone / card operations ─────────────────────────────────── + case DrawCardsEffect dc: + { + var ps = ResolvePlayerForEffect(dc.Player, ctx); + DrawCards(ps, dc.N); + break; + } + case DiscardCardsEffect dce: + { + var ps = ResolvePlayerForEffect(dce.Player, ctx); + DiscardFromHand(ps, 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); + } + 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); + } + 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); + } + 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; + } + + // ── §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: + { + int amt = ResolveValue(he.Amount, ctx); + ci.CurrentHealth = Math.Min(ci.MaxHealth ?? int.MaxValue, + (ci.CurrentHealth ?? 0) + amt); + break; + } + case DealDamageToSelfEffect ddself: + if (ctx.Source is not null) + ApplyDamageToUnit(ctx.Source, ResolveValue(ddself.Amount, ctx), + ddself.BypassDefense, 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; + + // ── §5.10 Control ───────────────────────────────────────────────── + case TakeControlEffect tce 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); + break; + } + + // Unhandled effects are silently ignored in this pass. + default: + break; + } + } + + // ── Damage helper ───────────────────────────────────────────────────────── + + private static void ApplyDamageToUnit( + CardInstance unit, + int rawAmount, + bool bypassDefense, + AbilityContext ctx) + { + int netDamage = bypassDefense + ? rawAmount + : Math.Max(0, rawAmount - (unit.CurrentDefense ?? 0)); + + unit.CurrentHealth = (unit.CurrentHealth ?? 0) - netDamage; + + 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; + + if (unit is FieldCard fc && fc.Position.HasValue && ctx.State.Board is not null) + ctx.State.Board.ClearUnit(fc.Position.Value); + + RemoveFromAllZones(owner, unit); + 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; + + // 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); + 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; + + board.ClearUnit(unitPos); + board.PlaceUnit(newPos, unit.InstanceId); + 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: // top + player.Deck.Add(card); break; + } + } + + private static void RemoveFromAllZones(PlayerState player, CardInstance card) + { + 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) + { + return 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) + { + // 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; + } + + 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: + return or.Conditions.Any(c => EvaluateCondition(c, ctx, subject)); + 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: + 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: + { + var abilities = ParseAbilities(ci.AbilitiesJson); + return abilities.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; + } + 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; + + // 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 + 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; + + 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; // unknown conditions pass by default + } + } + + // ── 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) + { + switch (filter) + { + 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; + } + } + + // ── Trigger matching ────────────────────────────────────────────────────── + + private static bool TriggerMatches( + TriggerEvent trigger, + TriggerOccurrence occurrence, + GameState state, + string ownerId) + { + return 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), + _ => false, + }; + } + + private static bool MatchesOwnership(string? scope, string eventActorId, string unitOwnerId, GameState state) + { + return (scope?.ToLowerInvariant()) switch + { + null or "any" => true, + "own" or "self" => eventActorId == unitOwnerId, + "enemy" => eventActorId != unitOwnerId, + "ally" => eventActorId == unitOwnerId, + _ => true, + }; + } + + private static bool MatchesUnitType(string? required, string? actual) + => required is null || required == "Any" || required == actual; + + private static bool MatchesCardType(string? required, string? actual) + => required is null || required == "Any" || required == actual; + + // ── Value 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 + { + ("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.Neutral; + + 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, + }; + } } diff --git a/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs b/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs new file mode 100644 index 0000000..f7b06b7 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs @@ -0,0 +1,47 @@ +namespace SOR.Game.Abilities.Models; + +/// Ability type determines activation model and required fields. +public enum AbilityType +{ + /// Manually activated by the controlling player. Costs optional range and UsesPerTurn. + Active, + /// Always active while the unit is in play and conditions are met. No activation, no cost. + Passive, + /// Always-on area effect anchored to a unit's position. Evaluated per-turn and on unit entry. + Aura, + /// Automatically fires when a matching TriggerEvent occurs. + Triggered, +} + +/// +/// The top-level definition of a unit ability or card effect. +/// Stored as JSONB in CardDefinition.AbilitiesJson (array) and CardDefinition.EffectsJson. +/// +/// All four ability types share the Action/Effect/Condition model. +/// Type-specific fields are non-null only for the relevant type. +/// +public sealed class AbilityDefinition +{ + public AbilityType Type { get; set; } + public Condition[]? ActivationConditions { get; set; } + public Action[] Actions { get; set; } = []; + + // ── Active only ────────────────────────────────────────────────────────── + public CostEntry[]? Cost { get; set; } + public AbilityRange? Range { get; set; } + /// How many times this Active ability may be used per turn (default 1). + public int UsesPerTurn { get; set; } = 1; + + // ── Aura only ──────────────────────────────────────────────────────────── + public AbilityRange? AuraRange { get; set; } + + // ── Triggered only ─────────────────────────────────────────────────────── + /// The event that fires this ability. Must be set for Triggered type. + public TriggerEvent? TriggerEvent { get; set; } + + /// + /// Optional display name shown in the admin tool and client ability list. + /// Not required for game logic. + /// + public string? Name { get; set; } +} diff --git a/Server/src/SOR.Game/Abilities/Models/Action.cs b/Server/src/SOR.Game/Abilities/Models/Action.cs new file mode 100644 index 0000000..fc45a60 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/Action.cs @@ -0,0 +1,126 @@ +namespace SOR.Game.Abilities.Models; + +// ── Value expression ────────────────────────────────────────────────────────── + +/// +/// An integer value that may be a fixed constant or a dynamic runtime reference. +/// Dynamic references (§4.5) use dot-path notation, e.g.: +/// "EventData.Amount", "Self.Damage", "Action1.Target.Defense" +/// +public sealed class ValueExpr +{ + public int? Fixed { get; set; } + public string? Ref { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + public bool IsDynamic => Ref is not null; + + public static implicit operator ValueExpr(int n) => new() { Fixed = n }; +} + +/// +/// An affinity value that may be fixed or a dynamic reference. +/// E.g.: "Self.Affinity", "Action1.Target.Affinity". +/// +public sealed class AffinityExpr +{ + public SOR.Database.Enums.Affinity? Fixed { get; set; } + public string? Ref { get; set; } +} + +// ── Target selector ─────────────────────────────────────────────────────────── + +public enum TargetScope { Hand, Deck, Discard, Battlefield, Player, AnyZone } +public enum TargetType { Unit, ArchSpirit, Spirit, SpiritToken, Ruin, Tile, Card, Player } +public enum TargetOwnership { Self, Owner, Ally, Enemy, Any, Random, Target } + +public sealed class TargetCount +{ + /// Exact number of targets; or the maximum when UpTo=true. + public int N { get; set; } = 1; + /// Player may select fewer than N valid targets. + public bool UpTo { get; set; } + /// Target all valid entities (N is ignored). + public bool All { get; set; } +} + +/// +/// Defines how targets are resolved for a single Action. +/// Scope + Type + Ownership narrow the pool; Filters refine further. +/// +public sealed class TargetSelector +{ + public TargetScope Scope { get; set; } + public TargetType Type { get; set; } + public TargetOwnership Ownership { get; set; } + public TargetCount Count { get; set; } = new(); + public Filter[]? Filters { get; set; } +} + +// ── Action ──────────────────────────────────────────────────────────────────── + +/// +/// The atomic unit of targeting and effect delivery within an ability. +/// All effects within one action share the same target and duration. +/// Actions within an ability resolve sequentially; a prior action's resolved +/// target is accessible in subsequent actions via chained targeting filters. +/// +public sealed class Action +{ + public TargetSelector Target { get; set; } = new(); + public Condition[]? Conditions { get; set; } + public Effect[] Effects { get; set; } = []; + public DurationModel? Duration { get; set; } +} + +// ── ChooseOne ───────────────────────────────────────────────────────────────── + +/// +/// Presents the controlling player with a set of mutually exclusive action branches. +/// Exactly one branch is selected and its actions resolve; other branches are skipped. +/// ChooseOne may appear anywhere an Action[] is accepted. +/// +public sealed class ChooseOne +{ + public Branch[] Branches { get; set; } = []; +} + +public sealed class Branch +{ + public string Label { get; set; } = string.Empty; + public Action[] Actions { get; set; } = []; +} + +// ── Cost entry ──────────────────────────────────────────────────────────────── + +public enum CostType +{ + SpiritPoints, + SacrificeTokens, + DiscardFromHand, + MillTopOfDeck, + MillBottomOfDeck, + SendSpiritFromBattlefieldToDiscard, + DealDamageToOwnArchSpirit, + DealDamageToOwnSpirit, +} + +/// +/// A single cost element for an Active ability. +/// Multiple CostEntry items must all be paid simultaneously before the ability resolves. +/// +public sealed class CostEntry +{ + public CostType Type { get; set; } + public int Amount { get; set; } = 1; + /// Optional filter for targeted costs (e.g. "Discard a Spirit card from hand"). + public Filter[]? Filters { get; set; } +} + +// ── Ability range ───────────────────────────────────────────────────────────── + +public sealed class AbilityRange +{ + public int Min { get; set; } = 1; + public int Max { get; set; } = 1; +} diff --git a/Server/src/SOR.Game/Abilities/Models/Conditions.cs b/Server/src/SOR.Game/Abilities/Models/Conditions.cs new file mode 100644 index 0000000..2eec29e --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/Conditions.cs @@ -0,0 +1,132 @@ +namespace SOR.Game.Abilities.Models; + +using System.Text.Json.Serialization; +using SOR.Database.Enums; + +// ── Condition base ──────────────────────────────────────────────────────────── + +/// +/// A boolean predicate evaluated against a subject entity. +/// The default subject is Self (the source unit or ability owner). +/// Override with Subject = "Target" to evaluate against the current action's resolved target. +/// +[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] +// Composite +[JsonDerivedType(typeof(AndCondition), "AND")] +[JsonDerivedType(typeof(OrCondition), "OR")] +[JsonDerivedType(typeof(XorCondition), "XOR")] +// Unit (§6.1) +[JsonDerivedType(typeof(HealthBelowCondition), "HealthBelow")] +[JsonDerivedType(typeof(HealthAboveCondition), "HealthAbove")] +[JsonDerivedType(typeof(DefenseIsCondition), "DefenseIs")] +[JsonDerivedType(typeof(HasGenusCondition), "HasGenus")] +[JsonDerivedType(typeof(HasAbilityCondition), "HasAbility")] +[JsonDerivedType(typeof(IsOnTileWithAffinityCondition), "IsOnTileWithAffinity")] +[JsonDerivedType(typeof(IsAdjacentToCondition), "IsAdjacentTo")] +[JsonDerivedType(typeof(WithinRangeOfCondition), "WithinRangeOf")] +[JsonDerivedType(typeof(MovementTypeIsCondition), "MovementTypeIs")] +// Player (§6.2) +[JsonDerivedType(typeof(SPAtLeastCondition), "SPAtLeast")] +[JsonDerivedType(typeof(SPAtMostCondition), "SPAtMost")] +[JsonDerivedType(typeof(STAtLeastCondition), "STAtLeast")] +[JsonDerivedType(typeof(STAtMostCondition), "STAtMost")] +[JsonDerivedType(typeof(HandSizeAtLeastCondition), "HandSizeAtLeast")] +[JsonDerivedType(typeof(HandSizeAtMostCondition), "HandSizeAtMost")] +[JsonDerivedType(typeof(DeckSizeAtLeastCondition), "DeckSizeAtLeast")] +[JsonDerivedType(typeof(DiscardSizeAtLeastCondition), "DiscardSizeAtLeast")] +// Tile (§6.3) +[JsonDerivedType(typeof(TileAffinityMatchesCondition), "TileAffinityMatches")] +[JsonDerivedType(typeof(TileIsOccupiedCondition), "TileIsOccupied")] +[JsonDerivedType(typeof(TileIsUnoccupiedCondition), "TileIsUnoccupied")] +// Turn/timing (§6.4) +[JsonDerivedType(typeof(IsOwnTurnCondition), "IsOwnTurn")] +[JsonDerivedType(typeof(IsOpponentTurnCondition), "IsOpponentTurn")] +[JsonDerivedType(typeof(IsAllyTurnCondition), "IsAllyTurn")] +[JsonDerivedType(typeof(IsActivePlayerTurnCondition), "IsActivePlayerTurn")] +// Battlefield (§6.5) +[JsonDerivedType(typeof(UnitCountOnBattlefieldCondition), "UnitCountOnBattlefield")] +[JsonDerivedType(typeof(CardInZoneCondition), "CardInZone")] +public abstract class Condition +{ + /// + /// Which entity to evaluate this condition against. + /// "Self" (default) = the source unit / ability owner. + /// "Target" = the current action's resolved target. + /// + public string Subject { get; set; } = "Self"; +} + +// ── Composite conditions ────────────────────────────────────────────────────── + +public sealed class AndCondition : Condition { public Condition[] Conditions { get; set; } = []; } +public sealed class OrCondition : Condition { public Condition[] Conditions { get; set; } = []; } +public sealed class XorCondition : Condition { public Condition[] Conditions { get; set; } = []; } + +// ── Unit conditions (§6.1) ──────────────────────────────────────────────────── + +public sealed class HealthBelowCondition : Condition { public int N { get; set; } } +public sealed class HealthAboveCondition : Condition { public int N { get; set; } } +public sealed class DefenseIsCondition : Condition { public int N { get; set; } } +public sealed class HasGenusCondition : Condition { public string Tag { get; set; } = string.Empty; } +/// Unit must have an ability with the given reference name. +public sealed class HasAbilityCondition : Condition { public string AbilityRef { get; set; } = string.Empty; } +public sealed class IsOnTileWithAffinityCondition : Condition { public Affinity Affinity { get; set; } } + +public sealed class IsAdjacentToCondition : Condition +{ + public string UnitType { get; set; } = "Unit"; + public string Ownership { get; set; } = "Any"; +} + +public sealed class WithinRangeOfCondition : Condition +{ + /// Reference to another action's target, e.g. "Action1.Target". + public string Target { get; set; } = string.Empty; + public int Min { get; set; } = 1; + public int Max { get; set; } = 1; +} + +public sealed class MovementTypeIsCondition : Condition { public MovementType MovementType { get; set; } } + +// ── Player conditions (§6.2) ────────────────────────────────────────────────── + +public sealed class SPAtLeastCondition : Condition { public int N { get; set; } } +public sealed class SPAtMostCondition : Condition { public int N { get; set; } } +public sealed class STAtLeastCondition : Condition { public int N { get; set; } } +public sealed class STAtMostCondition : Condition { public int N { get; set; } } +public sealed class HandSizeAtLeastCondition : Condition { public int N { get; set; } } +public sealed class HandSizeAtMostCondition : Condition { public int N { get; set; } } +public sealed class DeckSizeAtLeastCondition : Condition { public int N { get; set; } } +public sealed class DiscardSizeAtLeastCondition : Condition { public int N { get; set; } } + +// ── Tile conditions (§6.3) ──────────────────────────────────────────────────── + +public sealed class TileAffinityMatchesCondition : Condition { public Affinity Affinity { get; set; } } +public sealed class TileIsOccupiedCondition : Condition { public string? UnitType { get; set; } } +public sealed class TileIsUnoccupiedCondition : Condition { } + +// ── Turn/timing conditions (§6.4) ──────────────────────────────────────────── + +public sealed class IsOwnTurnCondition : Condition { } +public sealed class IsOpponentTurnCondition : Condition { } +public sealed class IsAllyTurnCondition : Condition { } +public sealed class IsActivePlayerTurnCondition : Condition { public string Ownership { get; set; } = "Owner"; } + +// ── Battlefield conditions (§6.5) ───────────────────────────────────────────── + +public enum Comparator { Equal, NotEqual, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual } + +public sealed class UnitCountOnBattlefieldCondition : Condition +{ + public string Ownership { get; set; } = "Enemy"; + public string UnitType { get; set; } = "Unit"; + public Comparator Comparator { get; set; } = Comparator.GreaterThanOrEqual; + public int N { get; set; } +} + +public sealed class CardInZoneCondition : Condition +{ + /// Reference to a specific card instance ID or definition ID. + public string CardRef { get; set; } = string.Empty; + public string Zone { get; set; } = "Hand"; +} diff --git a/Server/src/SOR.Game/Abilities/Models/DurationModel.cs b/Server/src/SOR.Game/Abilities/Models/DurationModel.cs new file mode 100644 index 0000000..1c4e765 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/DurationModel.cs @@ -0,0 +1,45 @@ +namespace SOR.Game.Abilities.Models; + +/// How long an applied effect persists. +public enum DurationType +{ + /// One-time change; no ongoing tracking required. + Instant, + /// Expires at the end of the current active player's turn. + UntilEndOfTurn, + /// Expires at the start of the ability-owner's next turn. + UntilStartOfOwnerTurn, + /// Expires at the start of the source unit's owner's next turn. + UntilStartOfSourceOwnerTurn, + /// Expires after exactly N turns have elapsed. + ForNTurns, + /// Active while a condition evaluates to true; expires when it becomes false. + WhileCondition, + /// Persists for the entire match; never expires. + PermanentInMatch, +} + +/// +/// Duration descriptor attached to every Action in the ability model. +/// Governs how long the action's effects remain active. +/// +public sealed class DurationModel +{ + public DurationType Type { get; set; } = DurationType.Instant; + + /// Turn count for . + public int? N { get; set; } + + /// Condition evaluated each turn for . + public Condition? Condition { get; set; } + + /// + /// Optional ownership scope for timing anchors. + /// E.g., "Owner" scopes "UntilEndOfTurn" to the ability-owner's turn end specifically. + /// + public string? PlayerScope { get; set; } + + public static DurationModel Instant => new() { Type = DurationType.Instant }; + public static DurationModel Permanent => new() { Type = DurationType.PermanentInMatch }; + public static DurationModel EndOfTurn => new() { Type = DurationType.UntilEndOfTurn }; +} diff --git a/Server/src/SOR.Game/Abilities/Models/Effects.cs b/Server/src/SOR.Game/Abilities/Models/Effects.cs new file mode 100644 index 0000000..f2c32c5 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/Effects.cs @@ -0,0 +1,232 @@ +namespace SOR.Game.Abilities.Models; + +using System.Text.Json.Serialization; +using SOR.Database.Enums; + +// ── Effect base ─────────────────────────────────────────────────────────────── + +/// +/// The atomic unit of game-state mutation delivered to a resolved target. +/// All effects share a DurationModel (from their containing Action). +/// +[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] +// §5.1 Stat modification +[JsonDerivedType(typeof(ModifyHealthEffect), "ModifyHealth")] +[JsonDerivedType(typeof(ModifyDefenseEffect), "ModifyDefense")] +[JsonDerivedType(typeof(ModifyDamageEffect), "ModifyDamage")] +[JsonDerivedType(typeof(ModifyMPEffect), "ModifyMP")] +[JsonDerivedType(typeof(SetMovementTypeEffect), "SetMovementType")] +[JsonDerivedType(typeof(SetAttackRangeEffect), "SetAttackRange")] +[JsonDerivedType(typeof(ModifyCostEffect), "ModifyCost")] +[JsonDerivedType(typeof(SetAffinityEffect), "SetAffinity")] +[JsonDerivedType(typeof(GrantAdditionalAttackEffect), "GrantAdditionalAttack")] +[JsonDerivedType(typeof(SetStatModMultiplierEffect), "SetStatModMultiplier")] +// §5.2 Flag modification — unit +[JsonDerivedType(typeof(SetCanMoveEffect), "SetCanMove")] +[JsonDerivedType(typeof(SetCanAttackEffect), "SetCanAttack")] +[JsonDerivedType(typeof(SetCanDefendEffect), "SetCanDefend")] +[JsonDerivedType(typeof(SetCanBeAttackedEffect), "SetCanBeAttacked")] +[JsonDerivedType(typeof(SetCanBeBlockedEffect), "SetCanBeBlocked")] +[JsonDerivedType(typeof(SetCanBeObstructedEffect), "SetCanBeObstructed")] +[JsonDerivedType(typeof(SetCanUseAbilityEffect), "SetCanUseAbility")] +[JsonDerivedType(typeof(SetCanBeSacrificedEffect), "SetCanBeSacrificed")] +// §5.2 Flag modification — player +[JsonDerivedType(typeof(SetCanDrawCardsEffect), "SetCanDrawCards")] +[JsonDerivedType(typeof(SetAccumulatesSPEffect), "SetAccumulatesSP")] +[JsonDerivedType(typeof(SetCanChannelSpiritEffect), "SetCanChannelSpirit")] +[JsonDerivedType(typeof(SetCanSacrificeSpiritEffect), "SetCanSacrificeSpirit")] +[JsonDerivedType(typeof(SetCanAscendArchSpiritEffect), "SetCanAscendArchSpirit")] +[JsonDerivedType(typeof(SetCanTransitionArchSpiritEffect), "SetCanTransitionArchSpirit")] +[JsonDerivedType(typeof(SetCanChannelRepentanceEffect), "SetCanChannelRepentance")] +[JsonDerivedType(typeof(SetCanChannelInstinctEffect), "SetCanChannelInstinct")] +[JsonDerivedType(typeof(SetCanChannelRuinEffect), "SetCanChannelRuin")] +[JsonDerivedType(typeof(SetCanChannelTerramorphaMonoEffect), "SetCanChannelTerramorphaMono")] +[JsonDerivedType(typeof(SetCanChannelTerramorphaDiEffect), "SetCanChannelTerramorphaDi")] +[JsonDerivedType(typeof(SetCanChannelTerramorphaTriEffect), "SetCanChannelTerramorphaTri")] +// §5.3 Ability modification +[JsonDerivedType(typeof(AddAbilityEffect), "AddAbility")] +[JsonDerivedType(typeof(RemoveAbilityEffect), "RemoveAbility")] +[JsonDerivedType(typeof(EnableAbilityEffect), "EnableAbility")] +[JsonDerivedType(typeof(DisableAbilityEffect),"DisableAbility")] +// §5.4 Genus modification +[JsonDerivedType(typeof(AddGenusEffect), "AddGenus")] +[JsonDerivedType(typeof(RemoveGenusEffect), "RemoveGenus")] +// §5.5 Player resource modification +[JsonDerivedType(typeof(ModifySPEffect), "ModifySP")] +[JsonDerivedType(typeof(ModifySPAccumulationEffect), "ModifySPAccumulation")] +[JsonDerivedType(typeof(ModifySTEffect), "ModifyST")] +[JsonDerivedType(typeof(ModifyCardsDrawnPerTurnEffect), "ModifyCardsDrawnPerTurn")] +// §5.6 Tile modification +[JsonDerivedType(typeof(SetBaseAffinity1Effect), "SetBaseAffinity1")] +[JsonDerivedType(typeof(SetBaseAffinity2Effect), "SetBaseAffinity2")] +[JsonDerivedType(typeof(PushAffinityEffect), "PushAffinity")] +[JsonDerivedType(typeof(PushFinalAffinityEffect), "PushFinalAffinity")] +// §5.7 Zone / card operations +[JsonDerivedType(typeof(DrawCardsEffect), "DrawCards")] +[JsonDerivedType(typeof(DiscardCardsEffect), "DiscardCards")] +[JsonDerivedType(typeof(ReturnToHandEffect), "ReturnToHand")] +[JsonDerivedType(typeof(ReturnToDeckEffect), "ReturnToDeck")] +[JsonDerivedType(typeof(ReturnToBattlefieldEffect), "ReturnToBattlefield")] +[JsonDerivedType(typeof(SendToDiscardEffect), "SendToDiscard")] +[JsonDerivedType(typeof(SearchDeckEffect), "SearchDeck")] +[JsonDerivedType(typeof(ShuffleDeckEffect), "ShuffleDeck")] +[JsonDerivedType(typeof(RevealCardsEffect), "RevealCards")] +[JsonDerivedType(typeof(PlaceOnDeckEffect), "PlaceOnDeck")] +[JsonDerivedType(typeof(ChannelCardEffect), "ChannelCard")] +// §5.8 Combat / damage +[JsonDerivedType(typeof(DealDamageEffect), "DealDamage")] +[JsonDerivedType(typeof(HealEffect), "Heal")] +[JsonDerivedType(typeof(DealDamageToSelfEffect), "DealDamageToSelf")] +[JsonDerivedType(typeof(DOTEffect), "DOT")] +[JsonDerivedType(typeof(HOTEffect), "HOT")] +// §5.9 Displacement +[JsonDerivedType(typeof(PushUnitEffect), "PushUnit")] +[JsonDerivedType(typeof(PullUnitEffect), "PullUnit")] +[JsonDerivedType(typeof(DisplaceUnitEffect), "DisplaceUnit")] +// §5.10 Control +[JsonDerivedType(typeof(TakeControlEffect), "TakeControl")] +[JsonDerivedType(typeof(GrantMovementControlEffect), "GrantMovementControl")] +[JsonDerivedType(typeof(SetFixedSacrificeReturnEffect),"SetFixedSacrificeReturn")] +// §5.11 Token +[JsonDerivedType(typeof(SummonTokenEffect), "SummonToken")] +// §5.12 Deferred +[JsonDerivedType(typeof(ApplyOnEventEffect), "ApplyOnEvent")] +public abstract class Effect { } + +// ── §5.1 Stat modification ──────────────────────────────────────────────────── + +public enum StatTarget { Current, Max } + +public sealed class ModifyHealthEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } +public sealed class ModifyDefenseEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } +public sealed class ModifyDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyMPEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } + +public sealed class SetMovementTypeEffect : Effect { public MovementType MovementType { get; set; } } +public sealed class SetAttackRangeEffect : Effect { public int Min { get; set; } public int Max { get; set; } } +public sealed class ModifyCostEffect : Effect { public int? Sp { get; set; } public int? St { get; set; } } +public sealed class SetAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class GrantAdditionalAttackEffect : Effect { public int N { get; set; } = 1; } +public sealed class SetStatModMultiplierEffect : Effect { public string Stat { get; set; } = string.Empty; public double Multiplier { get; set; } = 1.0; } + +// ── §5.2 Flag modification — unit ───────────────────────────────────────────── + +public sealed class SetCanMoveEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanAttackEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanDefendEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeAttackedEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeBlockedEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeObstructedEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanUseAbilityEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanBeSacrificedEffect : Effect { public bool Value { get; set; } } + +// ── §5.2 Flag modification — player ─────────────────────────────────────────── + +public sealed class SetCanDrawCardsEffect : Effect { public bool Value { get; set; } } +public sealed class SetAccumulatesSPEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanSacrificeSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanAscendArchSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanTransitionArchSpiritEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelRepentanceEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelInstinctEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelRuinEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelTerramorphaMonoEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelTerramorphaDiEffect : Effect { public bool Value { get; set; } } +public sealed class SetCanChannelTerramorphaTriEffect : Effect { public bool Value { get; set; } } + +// ── §5.3 Ability modification ───────────────────────────────────────────────── + +public sealed class AddAbilityEffect : Effect { public AbilityDefinition AbilityDef { get; set; } = new(); } +/// AbilityRef is the ability name (matches AbilityDefinition.Name). +public sealed class RemoveAbilityEffect : Effect { public string AbilityRef { get; set; } = string.Empty; } +public sealed class EnableAbilityEffect : Effect { public string AbilityRef { get; set; } = string.Empty; } +public sealed class DisableAbilityEffect: Effect { public string AbilityRef { get; set; } = string.Empty; } + +// ── §5.4 Genus modification ─────────────────────────────────────────────────── + +public sealed class AddGenusEffect : Effect { public string Tag { get; set; } = string.Empty; } +public sealed class RemoveGenusEffect : Effect { public string Tag { get; set; } = string.Empty; } + +// ── §5.5 Player resource modification ───────────────────────────────────────── + +public sealed class ModifySPEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifySPAccumulationEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifySTEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyCardsDrawnPerTurnEffect: Effect { public ValueExpr Amount { get; set; } = new(); } + +// ── §5.6 Tile modification ──────────────────────────────────────────────────── + +public sealed class SetBaseAffinity1Effect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class SetBaseAffinity2Effect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class PushAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } +public sealed class PushFinalAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } + +// ── §5.7 Zone / card operations ─────────────────────────────────────────────── + +public sealed class DrawCardsEffect : Effect { public int N { get; set; } = 1; public string Player { get; set; } = "Owner"; } +public sealed class DiscardCardsEffect : Effect { public int N { get; set; } = 1; public string Player { get; set; } = "Owner"; public Filter[]? Filters { get; set; } } +public sealed class ReturnToHandEffect : Effect { } // target is the card (from action target) +public sealed class ReturnToDeckEffect : Effect { public string Position { get; set; } = "top"; } // top | bottom | random +public sealed class ReturnToBattlefieldEffect : Effect { public string? Controller { get; set; } public Filter[]? TileFilter { get; set; } } +public sealed class SendToDiscardEffect: Effect { } +public sealed class SearchDeckEffect : Effect +{ + public Filter[]? Filters { get; set; } + public int Count { get; set; } = 1; + /// Action applied to each found card (SearchResult references current card). + public Action? ThenAction { get; set; } +} +public sealed class ShuffleDeckEffect : Effect { public string Player { get; set; } = "Owner"; } +public sealed class RevealCardsEffect : Effect { public int N { get; set; } = 1; public string ToOwnership { get; set; } = "Any"; } +public sealed class PlaceOnDeckEffect : Effect { public string Position { get; set; } = "top"; } +public sealed class ChannelCardEffect : Effect +{ + public bool PayCost { get; set; } = true; + public double? CostMultiplier { get; set; } +} + +// ── §5.8 Combat / damage ────────────────────────────────────────────────────── + +public sealed class DealDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); public bool BypassDefense { get; set; } } +public sealed class HealEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class DealDamageToSelfEffect : Effect { public ValueExpr Amount { get; set; } = new(); public bool BypassDefense { get; set; } } +public sealed class DOTEffect : Effect { public ValueExpr Amount { get; set; } = new(); public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; public bool BypassDefense { get; set; } } +public sealed class HOTEffect : Effect { public ValueExpr Amount { get; set; } = new(); public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; } + +// ── §5.9 Displacement ───────────────────────────────────────────────────────── + +public sealed class PushUnitEffect : Effect { public int Tiles { get; set; } = 1; } +public sealed class PullUnitEffect : Effect { public int Tiles { get; set; } = 1; } +public sealed class DisplaceUnitEffect : Effect { public int Tiles { get; set; } = 1; public string Direction { get; set; } = "North"; } + +// ── §5.10 Control effects ───────────────────────────────────────────────────── + +public sealed class TakeControlEffect : Effect { public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; } +public sealed class GrantMovementControlEffect : Effect { public int N { get; set; } = 1; } +/// Overrides the sacrifice formula: controller receives exactly StAmount ST instead. +public sealed class SetFixedSacrificeReturnEffect : Effect { public int StAmount { get; set; } } + +// ── §5.11 Token summoning ───────────────────────────────────────────────────── + +/// +/// Summons a SpiritToken onto a player-selected tile meeting the filter. +/// TokenDefJson is a JSONB blob matching a mini-CardDefinition for the token. +/// +public sealed class SummonTokenEffect : Effect +{ + public string TokenDefJson { get; set; } = "{}"; + public Filter[]? TileFilter { get; set; } +} + +// ── §5.12 Deferred effects ──────────────────────────────────────────────────── + +/// +/// Schedules effects to fire once the next time the specified trigger event occurs. +/// Consumed after firing. Cancelled if source leaves battlefield before event fires. +/// +public sealed class ApplyOnEventEffect : Effect +{ + public TriggerEvent Trigger { get; set; } = null!; + public Effect[] Effects { get; set; } = []; +} diff --git a/Server/src/SOR.Game/Abilities/Models/Filters.cs b/Server/src/SOR.Game/Abilities/Models/Filters.cs new file mode 100644 index 0000000..c4cda24 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/Filters.cs @@ -0,0 +1,125 @@ +namespace SOR.Game.Abilities.Models; + +using System.Text.Json.Serialization; +using SOR.Database.Enums; + +// ── Filter base ─────────────────────────────────────────────────────────────── + +/// +/// Narrows which entities a TargetSelector or condition matches. +/// Unit/card filters apply to spirits and ArchSpirits; tile filters to board tiles. +/// +[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] +// ── Unit / card filters ────────────────────────────────────────────────────── +[JsonDerivedType(typeof(GenusContainsFilter), "GenusContains")] +[JsonDerivedType(typeof(AffinityMatchesFilter), "AffinityMatches")] +[JsonDerivedType(typeof(HealthBelowFilter), "HealthBelow")] +[JsonDerivedType(typeof(HealthAboveFilter), "HealthAbove")] +[JsonDerivedType(typeof(DamageRangeFilter), "DamageRange")] +[JsonDerivedType(typeof(DefenseRangeFilter), "DefenseRange")] +[JsonDerivedType(typeof(MPRangeFilter), "MPRange")] +[JsonDerivedType(typeof(HasFlagFilter), "HasFlag")] +[JsonDerivedType(typeof(TierIsFilter), "TierIs")] +[JsonDerivedType(typeof(IsAdjacentToSourceFilter), "IsAdjacentToSource")] +[JsonDerivedType(typeof(CardTypeIsFilter), "CardTypeIs")] +[JsonDerivedType(typeof(CardSPCostRangeFilter), "CardSPCostRange")] +[JsonDerivedType(typeof(CardSTCostRangeFilter), "CardSTCostRange")] +[JsonDerivedType(typeof(WithinRangeFilter), "WithinRange")] +[JsonDerivedType(typeof(IsSelfFilter), "IsSelf")] +// ── Tile filters ───────────────────────────────────────────────────────────── +[JsonDerivedType(typeof(TileAffinityMatchesFilter), "TileAffinityMatches")] +[JsonDerivedType(typeof(TileIsOccupiedFilter), "TileIsOccupied")] +[JsonDerivedType(typeof(TileIsUnoccupiedFilter), "TileIsUnoccupied")] +[JsonDerivedType(typeof(TileWithinRangeFilter), "TileWithinRange")] +[JsonDerivedType(typeof(TileIsAdjacentToUnitFilter), "TileIsAdjacentToUnit")] +[JsonDerivedType(typeof(TileIsOnPlayerSideFilter), "TileIsOnPlayerSide")] +[JsonDerivedType(typeof(TileIsInArchSpiritChannelRangeFilter), "TileIsInArchSpiritChannelRange")] +public abstract class Filter { } + +// ── Unit / card filter implementations ─────────────────────────────────────── + +/// Unit's genus array must contain the given tag. +public sealed class GenusContainsFilter : Filter +{ + public string Tag { get; set; } = string.Empty; +} + +/// Unit's affinity must match. +public sealed class AffinityMatchesFilter : Filter +{ + public Affinity Affinity { get; set; } +} + +public sealed class HealthBelowFilter : Filter { public int N { get; set; } } +public sealed class HealthAboveFilter : Filter { public int N { get; set; } } + +public sealed class DamageRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } +public sealed class DefenseRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } +public sealed class MPRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +/// +/// Unit must have the specified boolean flag set to true. +/// Flag names: CanAttack, CanMove, CanDefend, CanBeAttacked, CanBeBlocked, CanBeSacrificed, etc. +/// +public sealed class HasFlagFilter : Filter +{ + public string Flag { get; set; } = string.Empty; +} + +/// ArchSpirit must be at the specified tier number. +public sealed class TierIsFilter : Filter +{ + public int Tier { get; set; } +} + +/// Target unit must be orthogonally adjacent to the ability's source unit. +public sealed class IsAdjacentToSourceFilter : Filter { } + +public sealed class CardTypeIsFilter : Filter +{ + public CardType CardType { get; set; } +} + +public sealed class CardSPCostRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } +public sealed class CardSTCostRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +/// Unit must be within Min..Max Manhattan distance of the ability's source unit. +public sealed class WithinRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +/// Matches only the exact unit that owns this ability (not all friendly units). +public sealed class IsSelfFilter : Filter { } + +// ── Tile filter implementations ─────────────────────────────────────────────── + +public sealed class TileAffinityMatchesFilter : Filter +{ + public Affinity Affinity { get; set; } +} + +/// Tile must be occupied; optionally restrict to a specific unit type. +public sealed class TileIsOccupiedFilter : Filter +{ + public string? UnitType { get; set; } // "Spirit" | "ArchSpirit" | "SpiritToken" | null (any) +} + +public sealed class TileIsUnoccupiedFilter : Filter { } + +public sealed class TileWithinRangeFilter : Filter { public int Min { get; set; } public int Max { get; set; } } + +public sealed class TileIsAdjacentToUnitFilter : Filter +{ + public string Ownership { get; set; } = "Any"; // TargetOwnership as string + public Filter? UnitFilter { get; set; } +} + +/// Tile falls within the starting placement side of the specified player ownership group. +public sealed class TileIsOnPlayerSideFilter : Filter +{ + public string Ownership { get; set; } = "Owner"; +} + +/// Tile is within the active ArchSpirit's channeling range for the specified player. +public sealed class TileIsInArchSpiritChannelRangeFilter : Filter +{ + public string Ownership { get; set; } = "Owner"; +} diff --git a/Server/src/SOR.Game/Abilities/Models/Triggers.cs b/Server/src/SOR.Game/Abilities/Models/Triggers.cs new file mode 100644 index 0000000..ac92685 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/Triggers.cs @@ -0,0 +1,150 @@ +namespace SOR.Game.Abilities.Models; + +using System.Text.Json.Serialization; + +// ── TriggerEvent base ───────────────────────────────────────────────────────── + +/// +/// Specifies the game event that causes a Triggered ability to fire. +/// Every event supports an optional ownership scope applied to the acting entity +/// and most accept an optional filter for further narrowing. +/// +[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] +// §8.1 Turn phase +[JsonDerivedType(typeof(OnTurnStartTrigger), "OnTurnStart")] +[JsonDerivedType(typeof(OnTurnEndTrigger), "OnTurnEnd")] +// §8.2 Channeling +[JsonDerivedType(typeof(OnChanneledTrigger), "OnChanneled")] +// §8.3 ArchSpirit tier actions +[JsonDerivedType(typeof(OnAscendTrigger), "OnAscend")] +[JsonDerivedType(typeof(OnTransitionTrigger), "OnTransition")] +// §8.4 Unit actions +[JsonDerivedType(typeof(OnUnitMoveTrigger), "OnUnitMove")] +[JsonDerivedType(typeof(OnUnitAttackTrigger), "OnUnitAttack")] +[JsonDerivedType(typeof(OnUnitAbilityActivatedTrigger), "OnUnitAbilityActivated")] +[JsonDerivedType(typeof(OnUnitMPSpentTrigger), "OnUnitMPSpent")] +// §8.5 Damage and healing +[JsonDerivedType(typeof(OnDamageDealtTrigger), "OnDamageDealt")] +[JsonDerivedType(typeof(OnDamagePreventedTrigger), "OnDamagePrevented")] +[JsonDerivedType(typeof(OnHealedTrigger), "OnHealed")] +// §8.6 Unit lifecycle +[JsonDerivedType(typeof(OnUnitEnterBattlefieldTrigger), "OnUnitEnterBattlefield")] +[JsonDerivedType(typeof(OnUnitLeaveBattlefieldTrigger), "OnUnitLeaveBattlefield")] +[JsonDerivedType(typeof(OnUnitDeathTrigger), "OnUnitDeath")] +[JsonDerivedType(typeof(OnUnitSentToDiscardTrigger), "OnUnitSentToDiscard")] +[JsonDerivedType(typeof(OnSpiritSacrificedTrigger), "OnSpiritSacrificed")] +[JsonDerivedType(typeof(OnTokenSummonedTrigger), "OnTokenSummoned")] +// §8.7 Unit state changes +[JsonDerivedType(typeof(OnStatModifiedTrigger), "OnStatModified")] +[JsonDerivedType(typeof(OnAbilityAddedTrigger), "OnAbilityAdded")] +[JsonDerivedType(typeof(OnAbilityRemovedTrigger), "OnAbilityRemoved")] +[JsonDerivedType(typeof(OnGenusChangedTrigger), "OnGenusChanged")] +// §8.8 Ruin +[JsonDerivedType(typeof(OnRuinActivationTrigger), "OnRuinActivation")] +[JsonDerivedType(typeof(OnUnitOccupyRuinTrigger), "OnUnitOccupyRuin")] +// §8.9 Tile +[JsonDerivedType(typeof(OnTileAffinityChangedTrigger), "OnTileAffinityChanged")] +// §8.10 Player resources +[JsonDerivedType(typeof(OnSPGainedTrigger), "OnSPGained")] +[JsonDerivedType(typeof(OnSPSpentTrigger), "OnSPSpent")] +[JsonDerivedType(typeof(OnSTGainedTrigger), "OnSTGained")] +[JsonDerivedType(typeof(OnSTSpentTrigger), "OnSTSpent")] +// §8.11 Card zone events +[JsonDerivedType(typeof(OnCardDrawnTrigger), "OnCardDrawn")] +[JsonDerivedType(typeof(OnCardDiscardedTrigger), "OnCardDiscarded")] +[JsonDerivedType(typeof(OnCardReturnedToHandTrigger), "OnCardReturnedToHand")] +[JsonDerivedType(typeof(OnCardReturnedToDeckTrigger), "OnCardReturnedToDeck")] +[JsonDerivedType(typeof(OnDeckShuffledTrigger), "OnDeckShuffled")] +[JsonDerivedType(typeof(OnCardsRevealedTrigger), "OnCardsRevealed")] +// §8.12 Effect and targeting lifecycle +[JsonDerivedType(typeof(OnTargetedByAbilityTrigger), "OnTargetedByAbility")] +[JsonDerivedType(typeof(OnEffectAppliedTrigger), "OnEffectApplied")] +[JsonDerivedType(typeof(OnEnterAuraRangeTrigger), "OnEnterAuraRange")] +[JsonDerivedType(typeof(OnLeaveAuraRangeTrigger), "OnLeaveAuraRange")] +public abstract class TriggerEvent { } + +// ── §8.1 Turn phase ─────────────────────────────────────────────────────────── + +public sealed class OnTurnStartTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; } +public sealed class OnTurnEndTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; } + +// ── §8.2 Channeling ─────────────────────────────────────────────────────────── + +public sealed class OnChanneledTrigger : TriggerEvent +{ + public string CardType { get; set; } = "Spirit"; + public string Ownership { get; set; } = "Owner"; + public Filter? Filter { get; set; } +} + +// ── §8.3 ArchSpirit tier actions ────────────────────────────────────────────── + +public sealed class OnAscendTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; } +public sealed class OnTransitionTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; } + +// ── §8.4 Unit actions ───────────────────────────────────────────────────────── + +public sealed class OnUnitMoveTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnUnitAttackTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnUnitAbilityActivatedTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnUnitMPSpentTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } public int? Amount { get; set; } } + +// ── §8.5 Damage and healing ─────────────────────────────────────────────────── + +public sealed class OnDamageDealtTrigger : TriggerEvent +{ + public string SourceOwnership { get; set; } = "Any"; + public string TargetOwnership { get; set; } = "Any"; + public string DamageType { get; set; } = "Any"; // "HP" | "Defense" | "Any" + public int? Amount { get; set; } +} +public sealed class OnDamagePreventedTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnHealedTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } public int? Amount { get; set; } } + +// ── §8.6 Unit lifecycle ─────────────────────────────────────────────────────── + +public sealed class OnUnitEnterBattlefieldTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnUnitLeaveBattlefieldTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnUnitDeathTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnUnitSentToDiscardTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } public string? CausedBy { get; set; } } +public sealed class OnSpiritSacrificedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnTokenSummonedTrigger : TriggerEvent { public string Ownership { get; set; } = "Owner"; public Filter? Filter { get; set; } } + +// ── §8.7 Unit state changes ─────────────────────────────────────────────────── + +public sealed class OnStatModifiedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } public string? Stat { get; set; } } +public sealed class OnAbilityAddedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnAbilityRemovedTrigger: TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnGenusChangedTrigger : TriggerEvent { public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } } + +// ── §8.8 Ruin ──────────────────────────────────────────────────────────────── + +public sealed class OnRuinActivationTrigger : TriggerEvent { public string RuinOwnership { get; set; } = "Any"; public string? OccupantOwnership { get; set; } } +public sealed class OnUnitOccupyRuinTrigger : TriggerEvent { public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } + +// ── §8.9 Tile ──────────────────────────────────────────────────────────────── + +public sealed class OnTileAffinityChangedTrigger : TriggerEvent { public Filter? Filter { get; set; } } + +// ── §8.10 Player resources ──────────────────────────────────────────────────── + +public sealed class OnSPGainedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } +public sealed class OnSPSpentTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } +public sealed class OnSTGainedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } +public sealed class OnSTSpentTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public int? Amount { get; set; } } + +// ── §8.11 Card zone events ──────────────────────────────────────────────────── + +public sealed class OnCardDrawnTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnCardDiscardedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } public string? Cause { get; set; } } +public sealed class OnCardReturnedToHandTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnCardReturnedToDeckTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } +public sealed class OnDeckShuffledTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; } +public sealed class OnCardsRevealedTrigger : TriggerEvent { public string Player { get; set; } = "Owner"; public Filter? Filter { get; set; } } + +// ── §8.12 Effect and targeting lifecycle ────────────────────────────────────── + +public sealed class OnTargetedByAbilityTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Owner"; public string SourceOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnEffectAppliedTrigger : TriggerEvent { public string TargetOwnership { get; set; } = "Owner"; public string SourceOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnEnterAuraRangeTrigger : TriggerEvent { public string AuraOwnership { get; set; } = "Owner"; public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } } +public sealed class OnLeaveAuraRangeTrigger : TriggerEvent { public string AuraOwnership { get; set; } = "Owner"; public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } }