diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 79b4c42..bba6774 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -370,6 +370,8 @@ public static class AbilitySystem ci.MaxHealth = (ci.MaxHealth ?? 0) + amt; if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth; } + TrackEffect(new ModifyHealthEffect { Amount = V(-amt), StatTarget = mh.StatTarget }, + ci.InstanceId, duration, ctx); break; } case ModifyDefenseEffect md when target is CardInstance ci: @@ -379,11 +381,17 @@ public static class AbilitySystem ci.CurrentDefense = Math.Max(0, (ci.CurrentDefense ?? 0) + amt); else ci.MaxDefense = (ci.MaxDefense ?? 0) + amt; + TrackEffect(new ModifyDefenseEffect { Amount = V(-amt), StatTarget = md.StatTarget }, + ci.InstanceId, duration, ctx); break; } case ModifyDamageEffect mdam when target is CardInstance ci: - ci.Damage = Math.Max(0, (ci.Damage ?? 0) + ResolveValue(mdam.Amount, ctx)); + { + int amt = ResolveValue(mdam.Amount, ctx); + ci.Damage = Math.Max(0, (ci.Damage ?? 0) + amt); + TrackEffect(new ModifyDamageEffect { Amount = V(-amt) }, ci.InstanceId, duration, ctx); break; + } case ModifyMPEffect mmp when target is CardInstance ci: { int amt = ResolveValue(mmp.Amount, ctx); @@ -391,77 +399,179 @@ public static class AbilitySystem fc.CurrentMp = Math.Max(0, fc.CurrentMp + amt); else ci.MaxMp = Math.Max(0, (ci.MaxMp ?? 0) + amt); + TrackEffect(new ModifyMPEffect { Amount = V(-amt), StatTarget = mmp.StatTarget }, + ci.InstanceId, duration, ctx); break; } case SetMovementTypeEffect smt when target is CardInstance ci: + { + var orig = ci.MovementType; ci.MovementType = smt.MovementType; + if (orig.HasValue) + TrackEffect(new SetMovementTypeEffect { MovementType = orig.Value }, + ci.InstanceId, duration, ctx); break; + } case SetAttackRangeEffect sar when target is CardInstance ci: + { + int? origMin = ci.MinAttackRange, origMax = ci.MaxAttackRange; ci.MinAttackRange = sar.Min; ci.MaxAttackRange = sar.Max; + if (origMin.HasValue && origMax.HasValue) + TrackEffect(new SetAttackRangeEffect { Min = origMin.Value, Max = origMax.Value }, + ci.InstanceId, duration, ctx); break; + } case ModifyCostEffect mc when target is CardInstance ci: + { if (mc.Sp.HasValue) ci.SpCost = Math.Max(0, ci.SpCost + mc.Sp.Value); if (mc.St.HasValue) ci.StCost = Math.Max(0, ci.StCost + mc.St.Value); + TrackEffect(new ModifyCostEffect + { + Sp = mc.Sp.HasValue ? -mc.Sp.Value : null, + St = mc.St.HasValue ? -mc.St.Value : null, + }, ci.InstanceId, duration, ctx); break; + } case SetAffinityEffect sa when target is CardInstance ci: + { + var origAff = ci.Affinity; ci.Affinity = ResolveAffinity(sa.Affinity, ctx).ToString(); + if (Enum.TryParse(origAff, out var parsed)) + TrackEffect(new SetAffinityEffect { Affinity = new AffinityExpr { Fixed = parsed } }, + ci.InstanceId, duration, ctx); break; + } // ── §5.2 Unit flags ──────────────────────────────────────────────── case SetCanMoveEffect scm when target is CardInstance ci: - ci.CanMove = scm.Value; break; + { + bool orig = ci.CanMove; ci.CanMove = scm.Value; + TrackEffect(new SetCanMoveEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } case SetCanAttackEffect sca when target is CardInstance ci: - ci.CanAttack = sca.Value; break; + { + bool orig = ci.CanAttack; ci.CanAttack = sca.Value; + TrackEffect(new SetCanAttackEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } case SetCanDefendEffect scd when target is CardInstance ci: - ci.CanDefend = scd.Value; break; + { + bool orig = ci.CanDefend; ci.CanDefend = scd.Value; + TrackEffect(new SetCanDefendEffect { Value = orig }, ci.InstanceId, duration, ctx); + break; + } // ── §5.2 Player flags ───────────────────────────────────────────── case SetCanDrawCardsEffect scdc when target is PlayerState ps: - ps.CanDrawCards = scdc.Value; break; + { + bool orig = ps.CanDrawCards; ps.CanDrawCards = scdc.Value; + TrackEffect(new SetCanDrawCardsEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetAccumulatesSPEffect sasp when target is PlayerState ps: - ps.AccumulatesSP = sasp.Value; break; + { + bool orig = ps.AccumulatesSP; ps.AccumulatesSP = sasp.Value; + TrackEffect(new SetAccumulatesSPEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelSpiritEffect sccsp when target is PlayerState ps: - ps.CanChannelSpirit = sccsp.Value; break; + { + bool orig = ps.CanChannelSpirit; ps.CanChannelSpirit = sccsp.Value; + TrackEffect(new SetCanChannelSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanSacrificeSpiritEffect scss when target is PlayerState ps: - ps.CanSacrificeSpirit = scss.Value; break; + { + bool orig = ps.CanSacrificeSpirit; ps.CanSacrificeSpirit = scss.Value; + TrackEffect(new SetCanSacrificeSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanAscendArchSpiritEffect scaas when target is PlayerState ps: - ps.CanAscendArchSpirit = scaas.Value; break; + { + bool orig = ps.CanAscendArchSpirit; ps.CanAscendArchSpirit = scaas.Value; + TrackEffect(new SetCanAscendArchSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanTransitionArchSpiritEffect sctas when target is PlayerState ps: - ps.CanTransitionArchSpirit = sctas.Value; break; + { + bool orig = ps.CanTransitionArchSpirit; ps.CanTransitionArchSpirit = sctas.Value; + TrackEffect(new SetCanTransitionArchSpiritEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelRepentanceEffect sccrep when target is PlayerState ps: - ps.CanChannelRepentance = sccrep.Value; break; + { + bool orig = ps.CanChannelRepentance; ps.CanChannelRepentance = sccrep.Value; + TrackEffect(new SetCanChannelRepentanceEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelInstinctEffect sccin when target is PlayerState ps: - ps.CanChannelInstinct = sccin.Value; break; + { + bool orig = ps.CanChannelInstinct; ps.CanChannelInstinct = sccin.Value; + TrackEffect(new SetCanChannelInstinctEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelRuinEffect sccru when target is PlayerState ps: - ps.CanChannelRuin = sccru.Value; break; + { + bool orig = ps.CanChannelRuin; ps.CanChannelRuin = sccru.Value; + TrackEffect(new SetCanChannelRuinEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelTerramorphaMonoEffect sctm when target is PlayerState ps: - ps.CanChannelTerramorphaMono = sctm.Value; break; + { + bool orig = ps.CanChannelTerramorphaMono; ps.CanChannelTerramorphaMono = sctm.Value; + TrackEffect(new SetCanChannelTerramorphaMonoEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelTerramorphaDiEffect sctdi when target is PlayerState ps: - ps.CanChannelTerramorphaDi = sctdi.Value; break; + { + bool orig = ps.CanChannelTerramorphaDi; ps.CanChannelTerramorphaDi = sctdi.Value; + TrackEffect(new SetCanChannelTerramorphaDiEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } case SetCanChannelTerramorphaTriEffect scttri when target is PlayerState ps: - ps.CanChannelTerramorphaTri = scttri.Value; break; + { + bool orig = ps.CanChannelTerramorphaTri; ps.CanChannelTerramorphaTri = scttri.Value; + TrackEffect(new SetCanChannelTerramorphaTriEffect { Value = orig }, ps.AccountId, duration, ctx); + break; + } // ── §5.4 Genus ──────────────────────────────────────────────────── case AddGenusEffect ag when target is CardInstance ci: + { ci.Genus ??= []; if (!ci.Genus.Contains(ag.Tag)) ci.Genus.Add(ag.Tag); + TrackEffect(new RemoveGenusEffect { Tag = ag.Tag }, ci.InstanceId, duration, ctx); break; + } case RemoveGenusEffect rg when target is CardInstance ci: - ci.Genus?.Remove(rg.Tag); break; + { + ci.Genus?.Remove(rg.Tag); + TrackEffect(new AddGenusEffect { Tag = rg.Tag }, ci.InstanceId, duration, ctx); + break; + } // ── §5.5 Player resources ───────────────────────────────────────── case ModifySPEffect msp when target is PlayerState ps: ps.CurrentSp = Math.Max(0, ps.CurrentSp + ResolveValue(msp.Amount, ctx)); break; case ModifySPAccumulationEffect mspa when target is PlayerState ps: - ps.SpAccumulationBonus += ResolveValue(mspa.Amount, ctx); + { + int amt = ResolveValue(mspa.Amount, ctx); + ps.SpAccumulationBonus += amt; + TrackEffect(new ModifySPAccumulationEffect { Amount = V(-amt) }, ps.AccountId, duration, ctx); break; + } case ModifySTEffect mst when target is PlayerState ps: ps.CurrentSt = Math.Max(0, ps.CurrentSt + ResolveValue(mst.Amount, ctx)); break; case ModifyCardsDrawnPerTurnEffect mcdpt when target is PlayerState ps: - ps.DrawPerTurnBonus += ResolveValue(mcdpt.Amount, ctx); + { + int amt = ResolveValue(mcdpt.Amount, ctx); + ps.DrawPerTurnBonus += amt; + TrackEffect(new ModifyCardsDrawnPerTurnEffect { Amount = V(-amt) }, ps.AccountId, duration, ctx); break; + } // ── §5.6 Tile modification ──────────────────────────────────────── case SetBaseAffinity1Effect sba1 when target is Coord coord: @@ -541,6 +651,14 @@ public static class AbilitySystem ApplyDamageToUnit(ctx.Source, ResolveValue(ddself.Amount, ctx), ddself.BypassDefense, ctx); break; + case DOTEffect dot when target is CardInstance ci: + TrackTick(new DealDamageEffect { Amount = V(ResolveValue(dot.Amount, ctx)), BypassDefense = dot.BypassDefense }, + ci.InstanceId, dot.Duration, ctx); + break; + case HOTEffect hot when target is CardInstance ci: + TrackTick(new HealEffect { Amount = V(ResolveValue(hot.Amount, ctx)) }, + ci.InstanceId, hot.Duration, ctx); + break; // ── §5.9 Displacement ───────────────────────────────────────────── case PushUnitEffect pu when target is FieldCard fc2: @@ -910,4 +1028,229 @@ public static class AbilitySystem _ => Affinity.Void, }; } + + // ── Duration tracking ────────────────────────────────────────────────────── + + private static ValueExpr V(int n) => new() { Fixed = n }; + + /// Internal metadata envelope stored in ActiveEffect.DurationJson. + private sealed class TrackedDuration + { + public DurationModel Duration { get; set; } = new(); + public string OwnerAccountId { get; set; } = string.Empty; + /// True for DOT/HOT tick effects (apply each turn); false for reversal effects. + public bool IsTick { get; set; } + } + + /// + /// Stores a reversal effect to be applied when the duration expires. + /// No-op for Instant or PermanentInMatch durations. + /// + private static void TrackEffect( + Effect reversal, + string targetRef, + DurationModel? duration, + AbilityContext ctx) + { + if (duration is null + || duration.Type is DurationType.Instant or DurationType.PermanentInMatch) + return; + + ctx.State.ActiveEffects.Add(new ActiveEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? "", + TargetRef = targetRef, + EffectJson = JsonSerializer.Serialize(reversal, _jsonOpts), + DurationJson = JsonSerializer.Serialize(new TrackedDuration + { + Duration = duration, + OwnerAccountId = ctx.ActorId, + }, _jsonOpts), + TurnsRemaining = duration.N ?? 0, + }); + } + + /// + /// Stores a tick effect (DOT/HOT) to be applied each turn for the duration. + /// + private static void TrackTick( + Effect tickEffect, + string targetRef, + DurationModel duration, + AbilityContext ctx) + { + if (duration.Type is DurationType.Instant or DurationType.PermanentInMatch) + return; + + ctx.State.ActiveEffects.Add(new ActiveEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? "", + TargetRef = targetRef, + EffectJson = JsonSerializer.Serialize(tickEffect, _jsonOpts), + DurationJson = JsonSerializer.Serialize(new TrackedDuration + { + Duration = duration, + OwnerAccountId = ctx.ActorId, + IsTick = true, + }, _jsonOpts), + TurnsRemaining = duration.N ?? 0, + }); + } + + /// + /// Fires DOT/HOT tick effects for the given player's turn. + /// Call at TurnEnd before expiry processing. + /// + public static GameState TickActiveEffects(GameState state, string activePlayerId) + { + foreach (var ae in state.ActiveEffects.ToList()) + { + TrackedDuration? td; + try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } + catch { continue; } + if (td?.IsTick != true) continue; + + Effect? eff; + try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); } + catch { continue; } + if (eff is null) continue; + + var tgt = state.Players.Values + .SelectMany(p => p.Field) + .FirstOrDefault(c => c.InstanceId == ae.TargetRef); + if (tgt is null) continue; + + var src = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId); + + ExecuteEffect(eff, tgt, DurationModel.Instant, new AbilityContext + { + State = state, + ActorId = td.OwnerAccountId, + Source = src, + }); + } + return state; + } + + /// + /// Expires duration-tracked effects at a turn boundary. + /// Call with =true at end of 's + /// turn, and false at start of 's turn (after player switch). + /// + public static GameState ExpireActiveEffects( + GameState state, + string currentPlayerId, + bool isEndOfTurn) + { + var toRemove = new List(); + foreach (var ae in state.ActiveEffects) + { + TrackedDuration? td; + try { td = JsonSerializer.Deserialize(ae.DurationJson, _jsonOpts); } + catch { continue; } + if (td is null) continue; + + var dur = td.Duration; + switch (dur.Type) + { + case DurationType.UntilEndOfTurn: + if (isEndOfTurn + && (dur.PlayerScope is null + || MatchPlayerScope(dur.PlayerScope, currentPlayerId, td.OwnerAccountId))) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + break; + + case DurationType.UntilStartOfOwnerTurn: + case DurationType.UntilStartOfSourceOwnerTurn: + if (!isEndOfTurn && currentPlayerId == td.OwnerAccountId) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + break; + + case DurationType.ForNTurns: + if (isEndOfTurn) + { + ae.TurnsRemaining--; + if (ae.TurnsRemaining <= 0) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + } + break; + + case DurationType.WhileCondition: + if (dur.Condition is not null) + { + var src = state.Players.Values + .SelectMany(p => p.Field) + .FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId); + var condCtx = new AbilityContext + { + State = state, + ActorId = td.OwnerAccountId, + Source = src, + }; + if (!EvaluateCondition(dur.Condition, condCtx, src ?? (object)state)) + { + if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId); + toRemove.Add(ae); + } + } + break; + } + } + foreach (var ae in toRemove) state.ActiveEffects.Remove(ae); + return state; + } + + private static bool MatchPlayerScope( + string scope, string currentPlayerId, string ownerAccountId) + => scope.ToLowerInvariant() switch + { + "owner" or "self" => currentPlayerId == ownerAccountId, + "enemy" => currentPlayerId != ownerAccountId, + _ => true, + }; + + private static void ApplyReversal(GameState state, ActiveEffect ae, string ownerAccountId) + { + Effect? eff; + try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); } + catch { return; } + if (eff is null) return; + + // Find target by instanceId (any zone) or by accountId (player). + object? tgt = null; + foreach (var p in state.Players.Values) + { + tgt = (CardInstance?)( + p.Field.FirstOrDefault(c => c.InstanceId == ae.TargetRef) + ?? p.Hand.FirstOrDefault(c => c.InstanceId == ae.TargetRef) + ?? p.Deck.FirstOrDefault(c => c.InstanceId == ae.TargetRef) + ?? p.Discard.FirstOrDefault(c => c.InstanceId == ae.TargetRef)); + if (tgt is not null) break; + if (p.AccountId == ae.TargetRef) { tgt = p; break; } + } + if (tgt is null) return; + + var src = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == ae.SourceInstanceId); + + // Execute with Instant duration so the reversal does not itself get tracked. + ExecuteEffect(eff, tgt, DurationModel.Instant, new AbilityContext + { + State = state, + ActorId = ownerAccountId, + Source = src, + }); + } } diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index f02abe3..250c0f2 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -689,6 +689,10 @@ public static class GameEngine ActorId = actorId, }); + // Tick DOT/HOT effects, then expire UntilEndOfTurn and ForNTurns effects. + AbilitySystem.TickActiveEffects(state, actorId); + AbilitySystem.ExpireActiveEffects(state, actorId, isEndOfTurn: true); + // Switch active player. state.ActivePlayerAccountId = GetOpponentId(state, actorId); state.TurnNumber++; @@ -714,6 +718,9 @@ public static class GameEngine state.Phase = GamePhase.Draw; + // Expire UntilStartOfOwnerTurn effects now that the new active player is set. + AbilitySystem.ExpireActiveEffects(state, state.ActivePlayerAccountId, isEndOfTurn: false); + AbilitySystem.FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.TurnStart,