Implement phase-2 prevention/replacement triggers and sequence duration

This commit is contained in:
Shard
2026-03-27 17:44:31 +00:00
parent 9e4fbd12a7
commit e887a8c670
6 changed files with 201 additions and 13 deletions
@@ -1100,7 +1100,7 @@
private static readonly string[] MovementTypeValues = ["Walk", "Flight", "Jump", "Teleport"];
private static readonly string[] DirectionValues = ["North", "South", "East", "West", "NorthEast", "NorthWest", "SouthEast", "SouthWest"];
private static readonly string[] ComparatorValues = ["Equal", "NotEqual", "LessThan", "LessThanOrEqual", "GreaterThan", "GreaterThanOrEqual"];
private static readonly string[] DurationTypeValues = ["Instant", "UntilEndOfTurn", "UntilStartOfOwnerTurn", "UntilStartOfSourceOwnerTurn", "ForNTurns", "WhileSourceOnBattlefield", "PermanentInMatch"];
private static readonly string[] DurationTypeValues = ["Instant", "UntilEndOfTurn", "UntilStartOfOwnerTurn", "UntilStartOfSourceOwnerTurn", "ForNTurns", "UntilEndOfSequence", "WhileSourceOnBattlefield", "PermanentInMatch"];
private static readonly string[] StatTargetValues = ["Current", "Base", "Max"];
private static readonly string[] StatValues = ["Damage", "Defense", "Health", "MP"];
private static readonly string[] PositionValues = ["Top", "Bottom"];
@@ -1125,7 +1125,7 @@
"OnTurnStart", "OnTurnEnd",
"OnChanneled", "OnAscend", "OnTransition",
"OnUnitMove", "OnUnitAttack", "OnUnitAbilityActivated", "OnUnitMPSpent",
"OnDamageDealt", "OnDamagePrevented", "OnHealed",
"OnDamageDealt", "OnDamagePrevented", "OnHealed", "BeforeDamageApplied", "BeforeUnitDeath",
"OnUnitEnterBattlefield", "OnUnitLeaveBattlefield", "OnUnitDeath",
"OnUnitSentToDiscard", "OnSpiritSacrificed", "OnTokenSummoned",
"OnStatModified", "OnAbilityAdded", "OnAbilityRemoved", "OnGenusChanged",
@@ -1142,7 +1142,7 @@
private static readonly EffectGroup[] EffectGroups =
[
new("Damage & Healing", ["DealDamage", "Heal", "DealDamageToSelf", "DOT", "HOT"]),
new("Damage & Healing", ["DealDamage", "Heal", "DealDamageToSelf", "DOT", "HOT", "PreventDeath", "PreventNextDamage", "SetHealthMinimum"]),
new("Stat Modification", ["ModifyHealth", "ModifyDefense", "ModifyDamage", "ModifyMP",
"GrantAdditionalAttack", "SetAttackRange",
"ModifyMinAttackRange", "ModifyMaxAttackRange",
@@ -1184,7 +1184,7 @@
private static readonly HashSet<string> _amountBypassTypes = ["DealDamage", "DealDamageToSelf"];
private static readonly HashSet<string> _amountOnlyTypes = ["Heal", "ModifyDamage", "ModifySP", "ModifyST", "ModifyCardsDrawnPerTurn", "ModifySPAccumulation",
"ModifyMinAttackRange", "ModifyMaxAttackRange"];
"ModifyMinAttackRange", "ModifyMaxAttackRange", "PreventNextDamage"];
private static readonly HashSet<string> _amountStatTypes = ["ModifyHealth", "ModifyDefense", "ModifyMP"];
private static readonly HashSet<string> _valueTypes = [
"SetCanMove", "SetCanAttack", "SetCanDefend", "SetCanBeAttacked",
@@ -1214,6 +1214,8 @@
["OnDamageDealt"] = """{"$type":"OnDamageDealt","SourceOwnership":"Any","TargetOwnership":"Any"}""",
["OnDamagePrevented"] = """{"$type":"OnDamagePrevented","TargetOwnership":"Any"}""",
["OnHealed"] = """{"$type":"OnHealed","TargetOwnership":"Any"}""",
["BeforeDamageApplied"] = """{"$type":"BeforeDamageApplied","SourceOwnership":"Any","TargetOwnership":"Any"}""",
["BeforeUnitDeath"] = """{"$type":"BeforeUnitDeath","UnitType":"Unit","Ownership":"Any"}""",
["OnUnitEnterBattlefield"] = """{"$type":"OnUnitEnterBattlefield","UnitType":"Unit","Ownership":"Any"}""",
["OnUnitLeaveBattlefield"] = """{"$type":"OnUnitLeaveBattlefield","UnitType":"Unit","Ownership":"Any"}""",
["OnUnitDeath"] = """{"$type":"OnUnitDeath","UnitType":"Unit","Ownership":"Any"}""",
@@ -1444,9 +1446,9 @@
{
d.N = ReadInt("N"); d.Player = ReadStr("Player", "Owner");
}
else if (typeKey is "GrantAdditionalAttack" or "SearchDeck" or "RevealCards" or "GrantMovementControl")
else if (typeKey is "GrantAdditionalAttack" or "SearchDeck" or "RevealCards" or "GrantMovementControl" or "SetHealthMinimum")
{
d.N = ReadInt("N");
d.N = ReadInt(typeKey == "SetHealthMinimum" ? "Minimum" : "N");
}
else if (_valueTypes.Contains(typeKey))
{
@@ -1813,7 +1815,7 @@
n["CardType"] = ab.TriggerCardType;
}
// Ownership + UnitType
else if (t is "OnUnitEnterBattlefield" or "OnUnitLeaveBattlefield" or "OnUnitDeath")
else if (t is "OnUnitEnterBattlefield" or "OnUnitLeaveBattlefield" or "OnUnitDeath" or "BeforeUnitDeath")
{
n["Ownership"] = ab.TriggerOwnership;
n["UnitType"] = ab.TriggerUnitType;
@@ -1833,6 +1835,11 @@
if (ab.TriggerDamageType != "Any") n["DamageType"] = ab.TriggerDamageType;
if (ab.TriggerAmount.HasValue) n["Amount"] = ab.TriggerAmount.Value;
}
else if (t == "BeforeDamageApplied")
{
n["SourceOwnership"] = ab.TriggerSourceOwnership;
n["TargetOwnership"] = ab.TriggerTargetOwnership;
}
// TargetOwnership only
else if (t == "OnDamagePrevented")
{
@@ -1913,6 +1920,10 @@
{
node["N"] = d.N;
}
else if (d.TypeKey == "SetHealthMinimum")
{
node["Minimum"] = d.N;
}
else if (_valueTypes.Contains(d.TypeKey))
{
node["Value"] = d.Value;
@@ -2195,6 +2206,10 @@
{
BuildIntInput(__builder, d.N, v => { d.N = v; Compile(); }, 70, "N");
}
else if (t == "SetHealthMinimum")
{
BuildIntInput(__builder, d.N, v => { d.N = v; Compile(); }, 90, "Minimum");
}
else if (_valueTypes.Contains(t))
{
BuildCheckbox(__builder, "Value", d.Value, v => { d.Value = v; Compile(); });
@@ -2412,7 +2427,7 @@
v => { ab.TriggerCardType = v; Compile(); }, 120);
}
// Ownership + UnitType
else if (t is "OnUnitEnterBattlefield" or "OnUnitLeaveBattlefield" or "OnUnitDeath")
else if (t is "OnUnitEnterBattlefield" or "OnUnitLeaveBattlefield" or "OnUnitDeath" or "BeforeUnitDeath")
{
BuildSelect(__builder, OwnershipValues, ab.TriggerOwnership,
v => { ab.TriggerOwnership = v; Compile(); }, 100);
@@ -2445,6 +2460,17 @@
BuildOptionalAmountInput(__builder, ab.TriggerAmount,
v => { ab.TriggerAmount = v; Compile(); });
}
else if (t == "BeforeDamageApplied")
{
BuildSelect(__builder, OwnershipValues, ab.TriggerSourceOwnership,
v => { ab.TriggerSourceOwnership = v; Compile(); }, 100);
__builder.OpenElement(50, "span");
__builder.AddAttribute(51, "class", "text-muted small");
__builder.AddContent(52, "→");
__builder.CloseElement();
BuildSelect(__builder, OwnershipValues, ab.TriggerTargetOwnership,
v => { ab.TriggerTargetOwnership = v; Compile(); }, 100);
}
// TargetOwnership only
else if (t == "OnDamagePrevented")
{
@@ -62,6 +62,9 @@ public enum TriggerEventKind
UnitAttack,
UnitAbilityActivated,
DamageDealt,
DamagePrevented,
BeforeDamageApplied,
BeforeUnitDeath,
UnitDeath,
UnitSentToDiscard,
SpiritSacrificed,
+148 -5
View File
@@ -36,6 +36,13 @@ public static class AbilitySystem
// Runtime limiter for Triggered abilities: (source instance, ability key, turn) -> count
private static readonly Dictionary<(string SourceInstanceId, string AbilityKey, int Turn), int> _triggerCountsPerTurn = new();
// Transient prevention markers.
private static readonly Dictionary<string, int?> _preventNextDamageByUnit = new();
private static readonly HashSet<string> _preventDeathUnits = new();
// Top-level ability/action sequence depth for UntilEndOfSequence cleanup.
private static int _sequenceDepth = 0;
// ── Parsing ────────────────────────────────────────────────────────────────
public static AbilityDefinition[] ParseAbilities(string? json)
@@ -431,9 +438,22 @@ public static class AbilitySystem
HashSet<string>? restrictTargets = null,
DurationModel? forceDuration = null)
{
for (int i = 0; i < actions.Length; i++)
ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i,
requireClientTargets, activationRange, restrictTargets, forceDuration);
_sequenceDepth++;
try
{
for (int i = 0; i < actions.Length; i++)
ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i,
requireClientTargets, activationRange, restrictTargets, forceDuration);
}
finally
{
_sequenceDepth--;
if (_sequenceDepth <= 0)
{
_sequenceDepth = 0;
ExpireEndOfSequenceEffects(ctx.State);
}
}
}
private static void ExecuteSingleAction(
@@ -1253,6 +1273,41 @@ public static class AbilitySystem
TrackTick(new HealEffect { Amount = V(ResolveValue(hot.Amount, ctx)) },
ci.InstanceId, hot.Duration, ctx);
break;
case PreventDeathEffect when target is CardInstance ci:
{
_preventDeathUnits.Add(ci.InstanceId);
var d = duration is null || duration.Type == DurationType.Instant
? new DurationModel { Type = DurationType.UntilEndOfSequence }
: duration;
TrackEffect(new ClearPreventDeathEffect(), ci.InstanceId, d, ctx);
break;
}
case PreventNextDamageEffect pnd when target is CardInstance ci:
{
var cap = pnd.MaxAmount is null ? (int?)null : ResolveValue(pnd.MaxAmount, ctx);
_preventNextDamageByUnit[ci.InstanceId] = cap;
var d = duration is null || duration.Type == DurationType.Instant
? new DurationModel { Type = DurationType.UntilEndOfSequence }
: duration;
TrackEffect(new ClearPreventNextDamageEffect(), ci.InstanceId, d, ctx);
break;
}
case ClearPreventDeathEffect when target is CardInstance ci:
{
_preventDeathUnits.Remove(ci.InstanceId);
break;
}
case ClearPreventNextDamageEffect when target is CardInstance ci:
{
_preventNextDamageByUnit.Remove(ci.InstanceId);
break;
}
case SetHealthMinimumEffect shm when target is CardInstance ci:
{
var cur = ci.CurrentHealth ?? 0;
if (cur < shm.Minimum) ci.CurrentHealth = shm.Minimum;
break;
}
// ── §5.9 Displacement ─────────────────────────────────────────────
case PushUnitEffect pu when target is FieldCard fc2:
@@ -1475,9 +1530,46 @@ public static class AbilitySystem
private static void ApplyDamageToUnit(
CardInstance unit, int rawAmount, bool bypassDefense, AbilityContext ctx)
{
// Pre-damage replacement/prevention window.
FireTrigger(ctx.State, new TriggerOccurrence
{
Kind = TriggerEventKind.BeforeDamageApplied,
ActorId = ctx.ActorId,
Data = new TriggerEventData { SourceId = ctx.Source?.InstanceId, TargetId = unit.InstanceId, Amount = rawAmount },
UnitType = unit.CardType,
});
var amount = rawAmount;
if (_preventNextDamageByUnit.TryGetValue(unit.InstanceId, out var cap))
{
var prevented = cap is null ? amount : Math.Min(amount, Math.Max(0, cap.Value));
amount -= prevented;
if (cap is not null)
{
var remain = cap.Value - prevented;
if (remain > 0) _preventNextDamageByUnit[unit.InstanceId] = remain;
else _preventNextDamageByUnit.Remove(unit.InstanceId);
}
else
{
_preventNextDamageByUnit.Remove(unit.InstanceId);
}
if (prevented > 0)
{
FireTrigger(ctx.State, new TriggerOccurrence
{
Kind = TriggerEventKind.DamagePrevented,
ActorId = ctx.ActorId,
Data = new TriggerEventData { SourceId = ctx.Source?.InstanceId, TargetId = unit.InstanceId, Amount = prevented },
UnitType = unit.CardType,
});
}
}
int net = bypassDefense
? rawAmount
: Math.Max(0, rawAmount - (unit.CurrentDefense ?? 0));
? amount
: Math.Max(0, amount - (unit.CurrentDefense ?? 0));
unit.CurrentHealth = (unit.CurrentHealth ?? 0) - net;
if (unit.CurrentHealth <= 0) KillUnit(unit, ctx, ctx.Source?.InstanceId);
}
@@ -1487,6 +1579,21 @@ public static class AbilitySystem
var owner = FindCardOwner(ctx.State, unit.InstanceId);
if (owner is null) return;
// Pre-death replacement/prevention window.
FireTrigger(ctx.State, new TriggerOccurrence
{
Kind = TriggerEventKind.BeforeUnitDeath,
ActorId = owner.AccountId,
Data = new TriggerEventData { SourceId = killerInstanceId, TargetId = unit.InstanceId },
UnitType = unit.CardType,
});
if (_preventDeathUnits.Remove(unit.InstanceId))
{
unit.CurrentHealth = Math.Max(unit.CurrentHealth ?? 0, 1);
return;
}
// Cancel deferred effects whose source is this unit.
ctx.State.PendingDeferredEffects.RemoveAll(p => p.SourceInstanceId == unit.InstanceId);
@@ -1871,6 +1978,17 @@ public static class AbilitySystem
&& (t.CausedBy is null || Own(t.CausedBy, occurrence, ownerId, state, uid)),
OnDamageDealtTrigger =>
occurrence.Kind == TriggerEventKind.DamageDealt,
OnDamagePreventedTrigger t =>
occurrence.Kind == TriggerEventKind.DamagePrevented
&& UnitOwnerMatches(t.TargetOwnership, occurrence.Data?.TargetId, state, ownerId),
BeforeDamageAppliedTrigger t =>
occurrence.Kind == TriggerEventKind.BeforeDamageApplied
&& Own(t.SourceOwnership, occurrence, ownerId, state, uid)
&& UnitOwnerMatches(t.TargetOwnership, occurrence.Data?.TargetId, state, ownerId),
BeforeUnitDeathTrigger t =>
occurrence.Kind == TriggerEventKind.BeforeUnitDeath
&& UnitType(t.UnitType, occurrence.UnitType)
&& UnitOwnerMatches(t.Ownership, occurrence.Data?.TargetId, state, ownerId),
OnUnitEnterBattlefieldTrigger t =>
occurrence.Kind == TriggerEventKind.UnitEnterBattlefield
&& UnitType(t.UnitType, occurrence.UnitType)
@@ -2206,6 +2324,10 @@ public static class AbilitySystem
}
break;
case DurationType.UntilEndOfSequence:
// handled by ExpireEndOfSequenceEffects after top-level action resolution
break;
case DurationType.WhileCondition:
if (dur.Condition is not null)
{
@@ -2231,6 +2353,27 @@ public static class AbilitySystem
return state;
}
private static GameState ExpireEndOfSequenceEffects(GameState state)
{
var toRemove = new List<ActiveEffect>();
foreach (var ae in state.ActiveEffects)
{
TrackedDuration? td;
try { td = JsonSerializer.Deserialize<TrackedDuration>(ae.DurationJson, _jsonOpts); }
catch { continue; }
if (td?.Duration?.Type != DurationType.UntilEndOfSequence) continue;
if (!td.IsTick)
ApplyReversal(state, ae, td.OwnerAccountId);
toRemove.Add(ae);
}
foreach (var ae in toRemove)
state.ActiveEffects.Remove(ae);
return state;
}
private static bool MatchPlayerScope(
string scope, string currentPlayerId, string ownerAccountId)
=> scope.ToLowerInvariant() switch
@@ -13,6 +13,8 @@ public enum DurationType
UntilStartOfSourceOwnerTurn,
/// <summary>Expires after exactly N turns have elapsed.</summary>
ForNTurns,
/// <summary>Expires at the end of the current top-level ability/action resolution sequence.</summary>
UntilEndOfSequence,
/// <summary>Active while a condition evaluates to true; expires when it becomes false.</summary>
WhileCondition,
/// <summary>Active while the ability's source unit is on the battlefield; revoked on leave/death.</summary>
@@ -80,6 +80,11 @@ using SOR.Database.Enums;
[PolyType(typeof(DealDamageToSelfEffect), "DealDamageToSelf")]
[PolyType(typeof(DOTEffect), "DOT")]
[PolyType(typeof(HOTEffect), "HOT")]
[PolyType(typeof(PreventDeathEffect), "PreventDeath")]
[PolyType(typeof(PreventNextDamageEffect), "PreventNextDamage")]
[PolyType(typeof(SetHealthMinimumEffect), "SetHealthMinimum")]
[PolyType(typeof(ClearPreventDeathEffect), "__ClearPreventDeath")]
[PolyType(typeof(ClearPreventNextDamageEffect), "__ClearPreventNextDamage")]
// §5.9 Displacement
[PolyType(typeof(PushUnitEffect), "PushUnit")]
[PolyType(typeof(PullUnitEffect), "PullUnit")]
@@ -197,6 +202,11 @@ public sealed class HealEffect : Effect { public ValueExpr Amount {
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; }
public sealed class PreventDeathEffect : Effect { }
public sealed class PreventNextDamageEffect : Effect { public ValueExpr? MaxAmount { get; set; } }
public sealed class SetHealthMinimumEffect : Effect { public int Minimum { get; set; } = 1; }
public sealed class ClearPreventDeathEffect : Effect { }
public sealed class ClearPreventNextDamageEffect : Effect { }
// ── §5.9 Displacement ─────────────────────────────────────────────────────────
@@ -25,6 +25,8 @@ namespace SOR.Game.Abilities.Models;
[PolyType(typeof(OnDamageDealtTrigger), "OnDamageDealt")]
[PolyType(typeof(OnDamagePreventedTrigger), "OnDamagePrevented")]
[PolyType(typeof(OnHealedTrigger), "OnHealed")]
[PolyType(typeof(BeforeUnitDeathTrigger), "BeforeUnitDeath")]
[PolyType(typeof(BeforeDamageAppliedTrigger), "BeforeDamageApplied")]
// §8.6 Unit lifecycle
[PolyType(typeof(OnUnitEnterBattlefieldTrigger), "OnUnitEnterBattlefield")]
[PolyType(typeof(OnUnitLeaveBattlefieldTrigger), "OnUnitLeaveBattlefield")]
@@ -98,6 +100,8 @@ public sealed class OnDamageDealtTrigger : TriggerEvent
}
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; } }
public sealed class BeforeUnitDeathTrigger : TriggerEvent { public string UnitType { get; set; } = "Unit"; public string Ownership { get; set; } = "Any"; public Filter? Filter { get; set; } }
public sealed class BeforeDamageAppliedTrigger : TriggerEvent { public string SourceOwnership { get; set; } = "Any"; public string TargetOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } }
// ── §8.6 Unit lifecycle ───────────────────────────────────────────────────────