Files
sor/Server/src/SOR.Game/GameState.cs
T
92d2e34a68 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>
2026-02-26 21:28:41 -05:00

324 lines
15 KiB
C#

namespace SOR.Game;
using System.Text.Json.Serialization;
using SOR.Database.Enums;
using SOR.Game.Grid;
/// <summary>
/// Full live game state — serialized as JSONB in GameSession.StateJson.
/// The GameEngine owns all mutations; handlers call into it exclusively.
/// </summary>
public sealed class GameState
{
public Guid SessionId { get; set; }
public GamePhase Phase { get; set; } = GamePhase.Setup;
public int TurnNumber { get; set; } = 1;
/// <summary>AccountId (as string) of the player whose turn it currently is.</summary>
public string ActivePlayerAccountId { get; set; } = string.Empty;
/// <summary>AccountId (as string) of the first player (P1). Determines placement row.</summary>
public string PlayerOneAccountId { get; set; } = string.Empty;
/// <summary>Per-player state, keyed by AccountId.ToString().</summary>
public Dictionary<string, PlayerState> Players { get; set; } = new();
/// <summary>Running sequence number for action log / StateVersion.</summary>
public int NextActionSequence { get; set; } = 1;
/// <summary>Rules snapshot applied to this game session.</summary>
public GameRules Rules { get; set; } = GameRules.Default;
/// <summary>
/// The battlefield grid. Null only before the game session is initialized.
/// Created during GameEngine.Initialize and populated during the Placement phase.
/// </summary>
public Board? Board { get; set; }
/// <summary>
/// Duration-tracked effects currently active on units or players.
/// Decremented / expired during EndTurn processing.
/// </summary>
public List<ActiveEffect> ActiveEffects { get; set; } = new();
/// <summary>
/// Deferred effects (from ApplyOnEventEffect) waiting to fire when their trigger occurs.
/// Consumed on firing; cancelled when source unit leaves the battlefield.
/// </summary>
public List<PendingDeferredEffect> PendingDeferredEffects { get; set; } = new();
}
public sealed class PlayerState
{
public string AccountId { get; set; } = string.Empty;
// ── Zones ────────────────────────────────────────────────────────────────
public List<CardInstance> Hand { get; set; } = new();
public List<CardInstance> Deck { get; set; } = new();
public List<CardInstance> Field { get; set; } = new();
public List<CardInstance> Discard { get; set; } = new();
// ── Resources ────────────────────────────────────────────────────────────
/// <summary>
/// Spirit Points — starts at 0, gains SpAccumulationPerTurn each turn.
/// Accumulates indefinitely; never resets between turns.
/// </summary>
public int CurrentSp { get; set; }
/// <summary>
/// Sacrifice Tokens — earned by sacrificing Spirits (§6.15).
/// Starts at 0; never granted per turn.
/// </summary>
public int CurrentSt { get; set; }
/// <summary>
/// Per-player SP accumulation bonus added on top of GameRules.SpAccumulationPerTurn.
/// Modified by ModifySPAccumulationEffect. Resets when the effect expires.
/// </summary>
public int SpAccumulationBonus { get; set; }
/// <summary>
/// Per-player bonus to cards drawn per turn, stacked on top of GameRules.DrawPerTurn.
/// Modified by ModifyCardsDrawnPerTurnEffect.
/// </summary>
public int DrawPerTurnBonus { get; set; }
// ── Action-restriction flags (set by ability effects) ─────────────────────
/// <summary>False when an effect prohibits drawing cards this turn.</summary>
public bool CanDrawCards { get; set; } = true;
/// <summary>False when an effect stops SP accumulating at turn start.</summary>
public bool AccumulatesSP { get; set; } = true;
public bool CanChannelSpirit { get; set; } = true;
public bool CanSacrificeSpirit { get; set; } = true;
public bool CanAscendArchSpirit { get; set; } = true;
public bool CanTransitionArchSpirit { get; set; } = true;
public bool CanChannelRepentance { get; set; } = true;
public bool CanChannelInstinct { get; set; } = true;
public bool CanChannelRuin { get; set; } = true;
public bool CanChannelTerramorphaMono { get; set; } = true;
public bool CanChannelTerramorphaDi { get; set; } = true;
public bool CanChannelTerramorphaTri { get; set; } = true;
// ── Leader ───────────────────────────────────────────────────────────────
/// <summary>
/// The player's ArchSpirit — placed during the Placement phase.
/// If destroyed the game ends (this player loses).
/// </summary>
public FieldCard? ArchSpirit { get; set; }
}
/// <summary>
/// A card instance in any zone. Carries mutable combat and positional state.
///
/// [JsonPolymorphic] is required so that FieldCard sub-type properties
/// survive the GameState JSONB serialize/deserialize round-trip.
/// </summary>
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$t")]
[JsonDerivedType(typeof(CardInstance), "c")]
[JsonDerivedType(typeof(FieldCard), "f")]
public class CardInstance
{
/// <summary>Unique instance ID within the game session (not a DB id).</summary>
public string InstanceId { get; set; } = Guid.NewGuid().ToString("N")[..8];
// ── Definition mirror ─────────────────────────────────────────────────────
public Guid CardDefinitionId { get; set; }
public string Name { get; set; } = string.Empty;
public string CardType { get; set; } = string.Empty;
public string Affinity { get; set; } = string.Empty;
public string Rarity { get; set; } = string.Empty;
public int SpCost { get; set; }
public int StCost { get; set; }
// ── Combat stats ──────────────────────────────────────────────────────────
public int? MaxHealth { get; set; }
public int? CurrentHealth { get; set; }
public int? MaxDefense { get; set; }
public int? CurrentDefense { get; set; }
public int? Damage { get; set; }
// ── Movement ──────────────────────────────────────────────────────────────
public MovementType? MovementType { get; set; }
public int? MaxMp { get; set; }
public bool CanMove { get; set; }
// ── Attack ────────────────────────────────────────────────────────────────
public int? MinAttackRange { get; set; }
public int? MaxAttackRange { get; set; }
public bool RequiresLos { get; set; }
// ── Channeling ────────────────────────────────────────────────────────────
public int? MinChannelRange { get; set; }
public int? MaxChannelRange { get; set; }
// ── State flags ───────────────────────────────────────────────────────────
/// <summary>True if this unit has already attacked or used an ability this turn.</summary>
public bool IsExhausted { get; set; }
/// <summary>True for the player's ArchSpirit (the win-condition target).</summary>
public bool IsLeader { get; set; }
public bool CanAttack { get; set; }
public bool CanDefend { get; set; }
// ── Ascend / Transition ───────────────────────────────────────────────────
/// <summary>
/// For ArchSpirit cards: tier number (1 = base). Mirrored from CardDefinition
/// to enable ascension chain validation in the engine without a DB round-trip.
/// </summary>
public int? Tier { get; set; }
/// <summary>
/// For Tier 2+ ArchSpirits: the CardDefinitionId of the Tier (N-1) predecessor.
/// Null for Tier 1 and all non-ArchSpirit cards.
/// </summary>
public Guid? PreviousTierId { get; set; }
// ── Terramorpha ────────────────────────────────────────────────────────────
/// <summary>
/// For Terramorpha cards only: how many tiles (and adjacency chain) this card
/// requires when channeled. Mirrored from CardDefinition.
/// </summary>
public TerramorphaMode? TerramorphaMode { get; set; }
// ── Abilities ─────────────────────────────────────────────────────────────
/// <summary>
/// Snapshot of CardDefinition.AbilitiesJson copied at game start.
/// Allows GameEngine to evaluate triggered/active abilities without DB access.
/// Format: JSON array of AbilityDefinition.
/// </summary>
public string? AbilitiesJson { get; set; }
/// <summary>
/// Snapshot of CardDefinition.EffectsJson (for Repentance/Instinct/Ruin cards).
/// Format: JSON array of Action (resolved once when the card is channeled).
/// </summary>
public string? EffectsJson { get; set; }
/// <summary>
/// Tracks Active ability uses this turn. Key = ability index, value = use count.
/// Reset to empty at the start of the owning player's turn (in EndTurn).
/// </summary>
public Dictionary<int, int>? AbilityUsesThisTurn { get; set; }
/// <summary>
/// Genus tags on this unit (e.g. "Beast", "Plant"). May be modified by abilities.
/// Null until at least one genus tag is added.
/// </summary>
public List<string>? Genus { get; set; }
// ── Unit restriction flags (set by ability effects) ───────────────────────
/// <summary>False when an effect prevents this unit from being targeted by attacks.</summary>
public bool CanBeAttacked { get; set; } = true;
/// <summary>False when an effect prevents this unit from being blocked in combat.</summary>
public bool CanBeBlocked { get; set; } = true;
/// <summary>False when an effect prevents this unit from being path-obstructed.</summary>
public bool CanBeObstructed { get; set; } = true;
/// <summary>False when an effect prevents this unit from using abilities.</summary>
public bool CanUseAbility { get; set; } = true;
/// <summary>False when this unit cannot be sacrificed.</summary>
public bool CanBeSacrificed { get; set; } = true;
// ── Extra attacks ─────────────────────────────────────────────────────────
/// <summary>
/// Additional attacks this unit may declare this turn before becoming exhausted.
/// Granted by GrantAdditionalAttackEffect. Decremented on each extra attack; reset at turn start.
/// </summary>
public int ExtraAttacksRemaining { get; set; }
// ── Sacrifice override ────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
public int? FixedSacrificeReturn { get; set; }
// ── Disabled abilities ────────────────────────────────────────────────────
/// <summary>
/// Ability names that are temporarily disabled on this unit.
/// Null until at least one ability is disabled.
/// </summary>
public List<string>? DisabledAbilities { get; set; }
// ── Reveal ────────────────────────────────────────────────────────────────
/// <summary>True if this card has been revealed to all players.</summary>
public bool IsRevealed { get; set; }
}
/// <summary>
/// A CardInstance that is on the field (placed by ChannelCard or PlaceArchSpirit).
/// Carries positional state (tile coordinate) and remaining movement points.
/// </summary>
public sealed class FieldCard : CardInstance
{
/// <summary>Current tile position on the board. Null until placed.</summary>
public Coord? Position { get; set; }
/// <summary>Remaining movement points this turn.</summary>
public int CurrentMp { get; set; }
}
/// <summary>
/// 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.
/// </summary>
public sealed class PendingDeferredEffect
{
/// <summary>InstanceId of the unit that created this deferred effect.</summary>
public string SourceInstanceId { get; set; } = string.Empty;
/// <summary>AccountId of the player who owns the source unit.</summary>
public string OwnerAccountId { get; set; } = string.Empty;
/// <summary>Serialized TriggerEvent JSON — the event to watch for.</summary>
public string TriggerJson { get; set; } = "{}";
/// <summary>InstanceId (card) or AccountId (player) of the entity to apply effects to.</summary>
public string TargetRef { get; set; } = string.Empty;
/// <summary>Serialized Effect[] JSON — effects applied to TargetRef when the trigger fires.</summary>
public string EffectsJson { get; set; } = "[]";
}
/// <summary>
/// A duration-tracked effect currently applied to a unit or player.
/// Stored in GameState.ActiveEffects; decremented / expired during EndTurn.
/// </summary>
public sealed class ActiveEffect
{
/// <summary>InstanceId of the unit that applied this effect.</summary>
public string SourceInstanceId { get; set; } = string.Empty;
/// <summary>
/// InstanceId of the affected unit, or AccountId of the affected player.
/// </summary>
public string TargetRef { get; set; } = string.Empty;
/// <summary>Serialized effect JSON (round-trips via AbilitySystem JSON options).</summary>
public string EffectJson { get; set; } = "{}";
/// <summary>Duration model as serialized JSON.</summary>
public string DurationJson { get; set; } = "{}";
/// <summary>Remaining turns for ForNTurns durations. Decremented at turn start.</summary>
public int TurnsRemaining { get; set; }
}