Implement missing ability effect handlers and gameplay rules

- 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 <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-02-26 21:28:41 -05:00
co-authored by Claude Happy
parent 7c89f4d0db
commit 92d2e34a68
3 changed files with 441 additions and 15 deletions
+348 -7
View File
@@ -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<TriggerEvent>(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<Effect[]>(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<FieldCard>()
.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;
}
/// <summary>
/// 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<AbilityTarget>? clientTargets)
IReadOnlyList<AbilityTarget>? 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<AbilityTarget>? 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<AbilityTarget>? 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),
};
/// <summary>
/// Applies affinity-based filter matching to a board tile.
/// Non-affinity filters are silently accepted (they apply to cards, not tiles).
/// </summary>
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<Affinity>(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")