From 92d2e34a68d980ede535dd3b4548ad9c7e8658a5 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 26 Feb 2026 21:28:41 -0500 Subject: [PATCH] Implement missing ability effect handlers and gameplay rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GameState: add CardInstance fields — CanBeAttacked, CanBeBlocked, CanBeObstructed, CanUseAbility, CanBeSacrificed, ExtraAttacksRemaining, FixedSacrificeReturn, DisabledAbilities, IsRevealed - GameState: add PendingDeferredEffect model + GameState.PendingDeferredEffects - GameEngine.Attack: enforce CanBeAttacked; ExtraAttacksRemaining (extra attacks decrement rather than exhausting) - GameEngine.Sacrifice: enforce CanBeSacrificed; use FixedSacrificeReturn override when set - GameEngine.EndTurn: reset ExtraAttacksRemaining to 0 with other resets AbilitySystem effect handlers (18 new): §5.1 GrantAdditionalAttackEffect §5.2 SetCanBeAttacked/Blocked/Obstructed/UseAbility/BeSacrificed §5.3 AddAbility/RemoveAbility/EnableAbility/DisableAbility §5.7 ReturnToBattlefield, SearchDeck, RevealCards, PlaceOnDeck §5.9 DisplaceUnit (absolute direction: N/S/E/W/NE/NW/SE/SW) §5.10 GrantMovementControl, SetFixedSacrificeReturn §5.12 ApplyOnEvent (deferred; fires once on trigger; cancelled on source death) AbilitySystem additions: - ActivateAbility: enforce CanUseAbility + DisabledAbilities - FireCardEffects / ActivateAbility: requireClientTargets=true for mandatory explicit-target validation (gameplay-todo.md) - ResolveTargets: empty candidates when clientTargets=null + mandatory selector, causing INSUFFICIENT_TARGETS for required but missing targets - FireTrigger: drain PendingDeferredEffects that match the current event - KillUnit: cancel PendingDeferredEffects whose source is dying - ParseDirection, TileMatchesFilters helpers - CreateTokenFieldCard: copy new CardInstance flag fields 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 | 355 +++++++++++++++++- Server/src/SOR.Game/GameEngine.cs | 31 +- Server/src/SOR.Game/GameState.cs | 70 ++++ 3 files changed, 441 insertions(+), 15 deletions(-) diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 377769c..1ab1783 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -57,6 +57,9 @@ public static class AbilitySystem if (source.IsExhausted) throw new GameException("UNIT_EXHAUSTED"); + if (!source.CanUseAbility) + throw new GameException("UNIT_CANNOT_USE_ABILITY"); + var abilities = ParseAbilities(source.AbilitiesJson); if (abilityIndex < 0 || abilityIndex >= abilities.Length) throw new GameException("ABILITY_INDEX_OUT_OF_RANGE"); @@ -66,6 +69,9 @@ public static class AbilitySystem if (def.Type != AbilityType.Active) throw new GameException("ABILITY_NOT_ACTIVE"); + if (def.Name is not null && source.DisabledAbilities?.Contains(def.Name) == true) + throw new GameException("ABILITY_DISABLED"); + source.AbilityUsesThisTurn ??= new(); source.AbilityUsesThisTurn.TryGetValue(abilityIndex, out int usedThisTurn); if (usedThisTurn >= def.UsesPerTurn) @@ -83,7 +89,7 @@ public static class AbilitySystem source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; - ExecuteActions(def.Actions, ctx, clientTargets); + ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true); return state; } @@ -100,7 +106,7 @@ public static class AbilitySystem 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); + ExecuteActions(actions, ctx, clientTargets, requireClientTargets: true); return state; } @@ -139,9 +145,56 @@ public static class AbilitySystem } } } + + // ── Check pending deferred effects ──────────────────────────────────── + var toFire = state.PendingDeferredEffects + .Where(p => + { + TriggerEvent? t; + try { t = JsonSerializer.Deserialize(p.TriggerJson, _jsonOpts); } + catch { return false; } + return t is not null && TriggerMatches(t, occurrence, state, p.OwnerAccountId); + }) + .ToList(); + + foreach (var pending in toFire) + { + state.PendingDeferredEffects.Remove(pending); + + Effect[]? deferredEffects; + try { deferredEffects = JsonSerializer.Deserialize(pending.EffectsJson, _jsonOpts); } + catch { continue; } + if (deferredEffects is null) continue; + + var tgt = FindDeferredTarget(state, pending.TargetRef); + if (tgt is null) continue; + + var dSrc = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + var dCtx = new AbilityContext { State = state, ActorId = pending.OwnerAccountId, Source = dSrc }; + foreach (var eff in deferredEffects) + ExecuteEffect(eff, tgt, DurationModel.Instant, dCtx); + } + return state; } + private static object? FindDeferredTarget(GameState state, string targetRef) + { + foreach (var player in state.Players.Values) + { + var ci = (CardInstance?)( + player.Field.FirstOrDefault(c => c.InstanceId == targetRef) + ?? player.Hand.FirstOrDefault(c => c.InstanceId == targetRef) + ?? player.Deck.FirstOrDefault(c => c.InstanceId == targetRef) + ?? player.Discard.FirstOrDefault(c => c.InstanceId == targetRef)); + if (ci is not null) return ci; + if (player.AccountId == targetRef) return player; + } + return null; + } + /// /// At the start of each turn: for every Ruin on the battlefield whose tile is occupied /// by a Spirit or ArchSpirit, pick ONE of the Ruin's OnRuinActivationTrigger abilities @@ -292,24 +345,26 @@ public static class AbilitySystem private static void ExecuteActions( Models.Action[] actions, AbilityContext ctx, - IReadOnlyList? clientTargets) + IReadOnlyList? clientTargets, + bool requireClientTargets = false) { for (int i = 0; i < actions.Length; i++) - ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i); + ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i, requireClientTargets); } private static void ExecuteSingleAction( Models.Action action, AbilityContext ctx, IReadOnlyList? clientTargets, - int actionIndex) + int actionIndex, + bool requireClientTargets = false) { if (action.Conditions is { Length: > 0 }) foreach (var cond in action.Conditions) if (!EvaluateCondition(cond, ctx, ctx.Source!)) return; - var resolved = ResolveTargets(action.Target, ctx, clientTargets, actionIndex); + var resolved = ResolveTargets(action.Target, ctx, clientTargets, actionIndex, requireClientTargets); ctx.ResolvedTargets[actionIndex] = resolved; foreach (var target in resolved) @@ -323,7 +378,8 @@ public static class AbilitySystem TargetSelector selector, AbilityContext ctx, IReadOnlyList? clientTargets, - int actionIndex) + int actionIndex, + bool requireClientTargets = false) { var state = ctx.State; @@ -361,6 +417,11 @@ public static class AbilitySystem if (clientIds.Count > 0) candidates = candidates.Where(c => clientIds.Contains(c.InstanceId)).ToList(); } + else if (requireClientTargets && !selector.Count.All && !selector.Count.UpTo && selector.Count.N > 0) + { + // Mandatory explicit-target action with no client selection provided — fail fast. + candidates = []; + } if (!selector.Count.All) { @@ -508,6 +569,13 @@ public static class AbilitySystem ci.InstanceId, duration, ctx); break; } + case GrantAdditionalAttackEffect gaa when target is CardInstance ci: + { + ci.ExtraAttacksRemaining += gaa.N; + if (ci.ExtraAttacksRemaining < 0) ci.ExtraAttacksRemaining = 0; + TrackEffect(new GrantAdditionalAttackEffect { N = -gaa.N }, ci.InstanceId, duration, ctx); + break; + } // ── §5.2 Unit flags ──────────────────────────────────────────────── case SetCanMoveEffect scm when target is CardInstance ci: @@ -528,6 +596,36 @@ public static class AbilitySystem TrackEffect(new SetCanDefendEffect { Value = orig }, ci.InstanceId, duration, ctx); break; } + case SetCanBeAttackedEffect scba when target is CardInstance ci: + { + bool orig = ci.CanBeAttacked; ci.CanBeAttacked = scba.Value; + TrackEffect(new SetCanBeAttackedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeBlockedEffect scbb when target is CardInstance ci: + { + bool orig = ci.CanBeBlocked; ci.CanBeBlocked = scbb.Value; + TrackEffect(new SetCanBeBlockedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeObstructedEffect scbo when target is CardInstance ci: + { + bool orig = ci.CanBeObstructed; ci.CanBeObstructed = scbo.Value; + TrackEffect(new SetCanBeObstructedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanUseAbilityEffect scua when target is CardInstance ci: + { + bool orig = ci.CanUseAbility; ci.CanUseAbility = scua.Value; + TrackEffect(new SetCanUseAbilityEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } + case SetCanBeSacrificedEffect scbs when target is CardInstance ci: + { + bool orig = ci.CanBeSacrificed; ci.CanBeSacrificed = scbs.Value; + TrackEffect(new SetCanBeSacrificedEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } // ── §5.2 Player flags ───────────────────────────────────────────── case SetCanDrawCardsEffect scdc when target is PlayerState ps: @@ -603,6 +701,46 @@ public static class AbilitySystem break; } + // ── §5.3 Ability modification ────────────────────────────────────── + case AddAbilityEffect addab when target is CardInstance ci: + { + var existing = ParseAbilities(ci.AbilitiesJson).ToList(); + existing.Add(addab.AbilityDef); + ci.AbilitiesJson = JsonSerializer.Serialize(existing, _jsonOpts); + if (!string.IsNullOrWhiteSpace(addab.AbilityDef.Name)) + TrackEffect(new RemoveAbilityEffect { AbilityRef = addab.AbilityDef.Name }, + ci.InstanceId, duration, ctx); + break; + } + case RemoveAbilityEffect remab when target is CardInstance ci: + { + var existing = ParseAbilities(ci.AbilitiesJson).ToList(); + var removed = existing.FirstOrDefault(a => a.Name == remab.AbilityRef); + if (removed is not null) + { + existing.Remove(removed); + ci.AbilitiesJson = JsonSerializer.Serialize(existing, _jsonOpts); + TrackEffect(new AddAbilityEffect { AbilityDef = removed }, ci.InstanceId, duration, ctx); + } + break; + } + case EnableAbilityEffect enab when target is CardInstance ci: + { + ci.DisabledAbilities?.Remove(enab.AbilityRef); + TrackEffect(new DisableAbilityEffect { AbilityRef = enab.AbilityRef }, + ci.InstanceId, duration, ctx); + break; + } + case DisableAbilityEffect disab when target is CardInstance ci: + { + ci.DisabledAbilities ??= []; + if (!ci.DisabledAbilities.Contains(disab.AbilityRef)) + ci.DisabledAbilities.Add(disab.AbilityRef); + TrackEffect(new EnableAbilityEffect { AbilityRef = disab.AbilityRef }, + ci.InstanceId, duration, ctx); + break; + } + // ── §5.4 Genus ──────────────────────────────────────────────────── case AddGenusEffect ag when target is CardInstance ci: { @@ -687,12 +825,108 @@ public static class AbilitySystem if (owner is not null) { RemoveFromAllZones(owner, ci, ctx.State.Board); PlaceInDeck(owner, ci, rtd.Position); } break; } + case ReturnToBattlefieldEffect rtb when target is CardInstance ci: + { + var board = ctx.State.Board; + if (board is null) break; + + var emptyTiles = board.Tiles.Values.Where(t => t.IsEmpty).ToList(); + if (rtb.TileFilter is { Length: > 0 }) + emptyTiles = emptyTiles.Where(t => TileMatchesFilters(rtb.TileFilter, t, ctx)).ToList(); + if (emptyTiles.Count == 0) break; + + var destTile = emptyTiles[Random.Shared.Next(emptyTiles.Count)]; + var ownerPs = rtb.Controller?.ToLowerInvariant() == "enemy" + ? ctx.State.Players.Values.First(p => p.AccountId != ctx.ActorId) + : ctx.State.Players[ctx.ActorId]; + + var originalOwner = FindCardOwner(ctx.State, ci.InstanceId); + if (originalOwner is not null) RemoveFromAllZones(originalOwner, ci, board); + + FieldCard fc; + if (ci is FieldCard existingFc) + { + existingFc.Position = destTile.Coord; + existingFc.CurrentMp = existingFc.MaxMp ?? 0; + fc = existingFc; + } + else + { + fc = new FieldCard + { + InstanceId = ci.InstanceId, + CardDefinitionId = ci.CardDefinitionId, + Name = ci.Name, + CardType = ci.CardType, + Affinity = ci.Affinity, + Rarity = ci.Rarity, + SpCost = ci.SpCost, + StCost = ci.StCost, + MaxHealth = ci.MaxHealth, + CurrentHealth = ci.MaxHealth, + MaxDefense = ci.MaxDefense, + CurrentDefense = ci.MaxDefense, + Damage = ci.Damage, + CanAttack = ci.CanAttack, + CanDefend = ci.CanDefend, + CanMove = ci.CanMove, + MovementType = ci.MovementType, + MaxMp = ci.MaxMp, + MinAttackRange = ci.MinAttackRange, + MaxAttackRange = ci.MaxAttackRange, + RequiresLos = ci.RequiresLos, + AbilitiesJson = ci.AbilitiesJson, + CanBeAttacked = ci.CanBeAttacked, + CanBeBlocked = ci.CanBeBlocked, + CanBeObstructed = ci.CanBeObstructed, + CanUseAbility = ci.CanUseAbility, + CanBeSacrificed = ci.CanBeSacrificed, + Position = destTile.Coord, + CurrentMp = ci.MaxMp ?? 0, + }; + } + + ownerPs.Field.Add(fc); + board.PlaceUnit(destTile.Coord, fc.InstanceId, ownerPs.AccountId); + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.UnitEnterBattlefield, + ActorId = ownerPs.AccountId, + UnitType = fc.CardType, + Data = new TriggerEventData { SourceId = fc.InstanceId }, + }); + EvaluateAurasOnEnter(ctx.State, fc.InstanceId); + break; + } case SendToDiscardEffect when target is CardInstance ci: { var owner = FindCardOwner(ctx.State, ci.InstanceId); if (owner is not null) { RemoveFromAllZones(owner, ci, ctx.State.Board); owner.Discard.Add(ci); } break; } + case SearchDeckEffect sde: + { + var ps = ResolvePlayerForEffect("Owner", ctx); + var found = ps.Deck + .Where(c => sde.Filters is null || FiltersMatch(sde.Filters, c, ctx)) + .Take(sde.Count).ToList(); + foreach (var card in found) + { + ps.Deck.Remove(card); + if (sde.ThenAction is not null) + { + var innerCtx = new AbilityContext + { State = ctx.State, ActorId = ctx.ActorId, Source = ctx.Source }; + foreach (var eff in sde.ThenAction.Effects) + ExecuteEffect(eff, card, sde.ThenAction.Duration, innerCtx); + } + else + { + ps.Hand.Add(card); + } + } + break; + } case ShuffleDeckEffect sde: { var ps = ResolvePlayerForEffect(sde.Player, ctx); @@ -704,6 +938,19 @@ public static class AbilitySystem } break; } + case RevealCardsEffect when target is CardInstance ci: + ci.IsRevealed = true; + break; + case PlaceOnDeckEffect pod when target is CardInstance ci: + { + var owner = FindCardOwner(ctx.State, ci.InstanceId); + if (owner is not null) + { + RemoveFromAllZones(owner, ci, ctx.State.Board); + PlaceInDeck(owner, ci, pod.Position); + } + break; + } // ── §5.8 Combat / damage ────────────────────────────────────────── case DealDamageEffect dd when target is CardInstance ci: @@ -732,6 +979,23 @@ public static class AbilitySystem DisplaceUnit(fc2, pu.Tiles, fromSource: true, ctx); break; case PullUnitEffect pull when target is FieldCard fc3: DisplaceUnit(fc3, pull.Tiles, fromSource: false, ctx); break; + case DisplaceUnitEffect du when target is FieldCard fc5: + { + if (!fc5.Position.HasValue || ctx.State.Board is null) break; + var (dx, dy) = ParseDirection(du.Direction); + if (dx == 0 && dy == 0) break; + var oldPos5 = fc5.Position.Value; + var newPos5 = new Coord(oldPos5.X + dx * du.Tiles, oldPos5.Y + dy * du.Tiles); + if (!ctx.State.Board.IsInBounds(newPos5) || !ctx.State.Board.GetTile(newPos5)!.IsEmpty) break; + var duOwner = ctx.State.Players.Values + .FirstOrDefault(p => p.Field.Any(f => f.InstanceId == fc5.InstanceId)); + if (duOwner is null) break; + ctx.State.Board.RemoveUnit(fc5.InstanceId); + ctx.State.Board.PlaceUnit(newPos5, fc5.InstanceId, duOwner.AccountId); + fc5.Position = newPos5; + EvaluateAuraTransitions(ctx.State, fc5.InstanceId, oldPos5, newPos5); + break; + } // ── §5.10 Control ───────────────────────────────────────────────── case TakeControlEffect when target is FieldCard fc4: @@ -741,6 +1005,22 @@ public static class AbilitySystem ctx.State.Players[ctx.ActorId].Field.Add(fc4); break; } + case GrantMovementControlEffect gmc when target is FieldCard fc6: + { + fc6.CurrentMp += gmc.N; + TrackEffect(new ModifyMPEffect { Amount = V(-gmc.N), StatTarget = StatTarget.Current }, + fc6.InstanceId, duration, ctx); + break; + } + case SetFixedSacrificeReturnEffect sfsr when target is CardInstance ci: + { + int? orig = ci.FixedSacrificeReturn; + // Negative StAmount is a sentinel meaning "clear override" (used in reversals). + ci.FixedSacrificeReturn = sfsr.StAmount >= 0 ? sfsr.StAmount : (int?)null; + TrackEffect(new SetFixedSacrificeReturnEffect { StAmount = orig ?? -1 }, + ci.InstanceId, duration, ctx); + break; + } // ── §5.11 Token summoning ───────────────────────────────────────── case SummonTokenEffect ste when target is Coord coord: @@ -772,6 +1052,24 @@ public static class AbilitySystem break; } + // ── §5.12 Deferred ──────────────────────────────────────────────── + case ApplyOnEventEffect aoe: + { + string targetRef = target is CardInstance ci3 ? ci3.InstanceId + : target is PlayerState ps3 ? ps3.AccountId + : string.Empty; + if (string.IsNullOrEmpty(targetRef)) break; + ctx.State.PendingDeferredEffects.Add(new PendingDeferredEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + OwnerAccountId = ctx.ActorId, + TriggerJson = JsonSerializer.Serialize(aoe.Trigger, _jsonOpts), + TargetRef = targetRef, + EffectsJson = JsonSerializer.Serialize(aoe.Effects, _jsonOpts), + }); + break; + } + default: break; } @@ -792,6 +1090,13 @@ public static class AbilitySystem CanAttack = proto.CanAttack, CanDefend = proto.CanDefend, CanMove = proto.CanMove, + CanBeAttacked = proto.CanBeAttacked, + CanBeBlocked = proto.CanBeBlocked, + CanBeObstructed = proto.CanBeObstructed, + CanUseAbility = proto.CanUseAbility, + CanBeSacrificed = proto.CanBeSacrificed, + DisabledAbilities = proto.DisabledAbilities is null + ? null : [.. proto.DisabledAbilities], MovementType = proto.MovementType, MaxMp = proto.MaxMp, CurrentMp = proto.MaxMp ?? 0, @@ -803,6 +1108,39 @@ public static class AbilitySystem Position = position, }; + // ── Displacement helpers ────────────────────────────────────────────────── + + private static (int dx, int dy) ParseDirection(string dir) => dir.ToUpperInvariant() switch + { + "NORTH" or "N" => (0, 1), + "SOUTH" or "S" => (0, -1), + "EAST" or "E" => ( 1, 0), + "WEST" or "W" => (-1, 0), + "NORTHEAST" or "NE" => ( 1, 1), + "NORTHWEST" or "NW" => (-1, 1), + "SOUTHEAST" or "SE" => ( 1, -1), + "SOUTHWEST" or "SW" => (-1, -1), + _ => (0, 0), + }; + + /// + /// Applies affinity-based filter matching to a board tile. + /// Non-affinity filters are silently accepted (they apply to cards, not tiles). + /// + private static bool TileMatchesFilters(Filter[] filters, Tile tile, AbilityContext ctx) + { + foreach (var f in filters) + { + if (f is AffinityMatchesFilter amf) + { + var resolved = AffinitySystem.Resolve(tile.Base1, tile.Base2); + if (!Enum.TryParse(amf.Affinity.ToString(), out var expected) + || resolved != expected) return false; + } + } + return true; + } + // ── Damage helper ───────────────────────────────────────────────────────── private static void ApplyDamageToUnit( @@ -820,6 +1158,9 @@ public static class AbilitySystem var owner = FindCardOwner(ctx.State, unit.InstanceId); if (owner is null) return; + // Cancel deferred effects whose source is this unit. + ctx.State.PendingDeferredEffects.RemoveAll(p => p.SourceInstanceId == unit.InstanceId); + // Fire leave-aura triggers before removing from board. EvaluateAurasOnLeave(ctx.State, unit.InstanceId); if (unit.CardType == "Ruin") diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index 73176fd..caa266b 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -613,6 +613,8 @@ public static class GameEngine if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED"); if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK"); + if (!target.CanBeAttacked) throw new GameException("TARGET_CANNOT_BE_ATTACKED"); + // Range + LOS validation when board is active. if (state.Board is not null && attacker.Position.HasValue && target.Position.HasValue) { @@ -634,7 +636,11 @@ public static class GameEngine if (target.CurrentHealth > 0 && target.CanAttack && !target.IsExhausted) ApplyDamage(attacker, target.Damage ?? 0); - attacker.IsExhausted = true; + // Consume extra attack or exhaust normally. + if (attacker.ExtraAttacksRemaining > 0) + attacker.ExtraAttacksRemaining--; + else + attacker.IsExhausted = true; bool gameOver = false; var activePlayer = state.Players[actorId]; @@ -706,7 +712,8 @@ public static class GameEngine .FirstOrDefault(c => c.InstanceId == unitInstanceId) ?? throw new GameException("UNIT_NOT_ON_FIELD"); - if (unit.IsLeader) throw new GameException("CANNOT_SACRIFICE_ARCH_SPIRIT"); + if (unit.IsLeader) throw new GameException("CANNOT_SACRIFICE_ARCH_SPIRIT"); + if (!unit.CanBeSacrificed) throw new GameException("UNIT_CANNOT_BE_SACRIFICED"); var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT"); if (archSpirit.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED"); @@ -715,8 +722,14 @@ public static class GameEngine if (!unit.Position.Value.IsOrthogonallyAdjacentTo(archSpirit.Position.Value)) throw new GameException("UNIT_NOT_ADJACENT_TO_ARCH_SPIRIT"); - var sacValue = SacrificeSystem.GetSacrificeValue(unit.StCost, unit.SpCost); - var stReturn = SacrificeSystem.GetSTReturn(player.CurrentSt, sacValue); + int stReturn; + if (unit.FixedSacrificeReturn.HasValue && unit.FixedSacrificeReturn.Value >= 0) + stReturn = unit.FixedSacrificeReturn.Value; + else + { + var sacValue = SacrificeSystem.GetSacrificeValue(unit.StCost, unit.SpCost); + stReturn = SacrificeSystem.GetSTReturn(player.CurrentSt, sacValue); + } player.CurrentSt += stReturn; AbilitySystem.EvaluateAurasOnLeave(state, unitInstanceId); @@ -756,13 +769,15 @@ public static class GameEngine var active = state.Players[actorId]; foreach (var card in active.Field.OfType()) { - card.IsExhausted = false; - card.AbilityUsesThisTurn = null; + card.IsExhausted = false; + card.AbilityUsesThisTurn = null; + card.ExtraAttacksRemaining = 0; } if (active.ArchSpirit is not null) { - active.ArchSpirit.IsExhausted = false; - active.ArchSpirit.AbilityUsesThisTurn = null; + active.ArchSpirit.IsExhausted = false; + active.ArchSpirit.AbilityUsesThisTurn = null; + active.ArchSpirit.ExtraAttacksRemaining = 0; } AbilitySystem.FireTrigger(state, new TriggerOccurrence diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 1d8afa0..5e2fe67 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -40,6 +40,12 @@ public sealed class GameState /// Decremented / expired during EndTurn processing. /// public List ActiveEffects { get; set; } = new(); + + /// + /// Deferred effects (from ApplyOnEventEffect) waiting to fire when their trigger occurs. + /// Consumed on firing; cancelled when source unit leaves the battlefield. + /// + public List PendingDeferredEffects { get; set; } = new(); } public sealed class PlayerState @@ -213,6 +219,48 @@ public class CardInstance /// Null until at least one genus tag is added. /// public List? Genus { get; set; } + + // ── Unit restriction flags (set by ability effects) ─────────────────────── + + /// False when an effect prevents this unit from being targeted by attacks. + public bool CanBeAttacked { get; set; } = true; + /// False when an effect prevents this unit from being blocked in combat. + public bool CanBeBlocked { get; set; } = true; + /// False when an effect prevents this unit from being path-obstructed. + public bool CanBeObstructed { get; set; } = true; + /// False when an effect prevents this unit from using abilities. + public bool CanUseAbility { get; set; } = true; + /// False when this unit cannot be sacrificed. + public bool CanBeSacrificed { get; set; } = true; + + // ── Extra attacks ───────────────────────────────────────────────────────── + + /// + /// Additional attacks this unit may declare this turn before becoming exhausted. + /// Granted by GrantAdditionalAttackEffect. Decremented on each extra attack; reset at turn start. + /// + public int ExtraAttacksRemaining { get; set; } + + // ── Sacrifice override ──────────────────────────────────────────────────── + + /// + /// When non-null and ≥ 0, overrides the normal ST sacrifice formula for this unit. + /// Null = use normal formula. -1 = sentinel "no override" for reversal tracking. + /// + public int? FixedSacrificeReturn { get; set; } + + // ── Disabled abilities ──────────────────────────────────────────────────── + + /// + /// Ability names that are temporarily disabled on this unit. + /// Null until at least one ability is disabled. + /// + public List? DisabledAbilities { get; set; } + + // ── Reveal ──────────────────────────────────────────────────────────────── + + /// True if this card has been revealed to all players. + public bool IsRevealed { get; set; } } /// @@ -228,6 +276,28 @@ public sealed class FieldCard : CardInstance public int CurrentMp { get; set; } } +/// +/// A deferred effect (from ApplyOnEventEffect) scheduled to fire once when its trigger event occurs. +/// Consumed after firing; cancelled if the source unit leaves the battlefield before the event fires. +/// +public sealed class PendingDeferredEffect +{ + /// InstanceId of the unit that created this deferred effect. + public string SourceInstanceId { get; set; } = string.Empty; + + /// AccountId of the player who owns the source unit. + public string OwnerAccountId { get; set; } = string.Empty; + + /// Serialized TriggerEvent JSON — the event to watch for. + public string TriggerJson { get; set; } = "{}"; + + /// InstanceId (card) or AccountId (player) of the entity to apply effects to. + public string TargetRef { get; set; } = string.Empty; + + /// Serialized Effect[] JSON — effects applied to TargetRef when the trigger fires. + public string EffectsJson { get; set; } = "[]"; +} + /// /// A duration-tracked effect currently applied to a unit or player. /// Stored in GameState.ActiveEffects; decremented / expired during EndTurn.