Files
sor/Server/src/SOR.Game/GameState.cs
T
2026-07-02 13:09:05 -04:00

518 lines
24 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>
/// Account IDs in seat / turn order. Empty for legacy 1v1 games (fall back to Players.Keys order).
/// </summary>
public List<string> SeatOrder { get; set; } = new();
/// <summary>"FFA" | "Teams" | "MultiTeam". Used for ability ownership resolution.</summary>
public string GameMode { get; set; } = "FFA";
/// <summary>
/// Maps TeamIndex → CSS-style hex color string (e.g. "4488FF").
/// Populated at initialization from the built-in palette; empty for legacy 1v1 games.
/// </summary>
public Dictionary<int, string> TeamColors { 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();
// ── Ability runtime state ─────────────────────────────────────────────────
// Formerly static fields on AbilitySystem. Kept on the state so they are
// per-game, serialize with StateJson, and roll back when a handler fails.
/// <summary>Active PreventNextDamage shields: unit InstanceId → remaining absorb cap (null = unlimited).</summary>
public Dictionary<string, int?> PreventNextDamageByUnit { get; set; } = new();
/// <summary>Active PreventDeath markers, keyed by unit InstanceId.</summary>
public Dictionary<string, PreventDeathMarker> PreventDeathMarkers { get; set; } = new();
/// <summary>Triggered-ability uses this turn, keyed "instanceId:abilityKey:turnNumber". Pruned at turn start.</summary>
public Dictionary<string, int> TriggerUsesThisTurn { get; set; } = new();
/// <summary>Triggered-ability uses for the whole game, keyed "instanceId:abilityKey".</summary>
public Dictionary<string, int> TriggerUsesThisGame { get; set; } = new();
/// <summary>
/// Current top-level ability resolution depth (UntilEndOfSequence bookkeeping).
/// Always returns to 0 by the end of each handler invocation.
/// </summary>
public int SequenceDepth { get; set; }
// ── Multi-player helpers ──────────────────────────────────────────────────
/// <summary>Seat IDs in order, skipping eliminated players.</summary>
public IEnumerable<string> ActiveSeats()
=> SeatOrder.Count > 0
? SeatOrder.Where(id => Players.TryGetValue(id, out var p) && !p.IsEliminated)
: Players.Keys.Where(id => !Players[id].IsEliminated);
/// <summary>Returns the next non-eliminated player in seat order after <paramref name="actorId"/>.</summary>
public string GetNextActiveSeat(string actorId)
{
var active = ActiveSeats().ToList();
if (active.Count == 0) return actorId;
var idx = active.IndexOf(actorId);
return active[(idx + 1) % active.Count];
}
/// <summary>Returns account IDs of all non-eliminated players not on the same team as <paramref name="actorId"/>.</summary>
public IEnumerable<string> GetEnemyIds(string actorId)
{
var myTeam = Players.TryGetValue(actorId, out var p) ? p.TeamIndex : -1;
return Players.Values
.Where(x => x.TeamIndex != myTeam && !x.IsEliminated)
.Select(x => x.AccountId);
}
/// <summary>True when both players are on the same team (or are the same player).</summary>
public bool AreAllies(string a, string b)
{
if (!Players.TryGetValue(a, out var pa) || !Players.TryGetValue(b, out var pb)) return false;
return pa.TeamIndex == pb.TeamIndex;
}
/// <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();
/// <summary>
/// Non-null when a Triggered ability has fired but requires a human target selection
/// before it can complete. The game is effectively "paused" until the owning player
/// submits a <c>game.triggered_target</c> response.
/// </summary>
public Abilities.Models.PendingTriggeredTarget? PendingTriggeredTarget { get; set; }
/// <summary>
/// Non-null when an Active ability's cost requires interactive card/unit selection
/// (CostPickMode.SelfPick / EnemyPick etc.). The game is effectively "paused" until
/// the picker submits a <c>game.cost_pick</c> response.
/// </summary>
public Abilities.Models.PendingCostPick? PendingCostPick { get; set; }
/// <summary>
/// Non-null when a CostGroup with OR/XOR logic requires a player to choose which
/// cost option to pay. Paused until the chooser submits a <c>game.cost_group_pick</c>.
/// </summary>
public Abilities.Models.PendingCostGroupPick? PendingCostGroupPick { get; set; }
/// <summary>
/// Non-null when an ActionGroup with OR/XOR logic requires a player to choose which
/// child (action or nested group) to execute. Paused until chooser submits
/// a <c>game.action_group_pick</c>.
/// </summary>
public Abilities.Models.PendingActionGroupPick? PendingActionGroupPick { get; set; }
/// <summary>
/// Non-null when a ChooseOne action's ChooserRole is Opponent/Ally and the non-activating
/// player must select a branch. Paused until chooser submits a <c>game.branch_pick</c>.
/// </summary>
public Abilities.Models.PendingBranchPick? PendingBranchPick { get; set; }
/// <summary>
/// Non-null when an effect needs a human to select a specific tile
/// (e.g. CloneSpiritAsToken TargetTile destination, RelocateRuin).
/// Paused until the chooser submits a <c>game.tile_pick</c> response.
/// </summary>
public Abilities.Models.PendingTilePick? PendingTilePick { get; set; }
/// <summary>
/// Non-null when an effect needs a human to select a player
/// (e.g. ChannelCardFromZone with UnderControlOf: Choice).
/// Paused until the chooser submits a <c>game.player_pick</c> response.
/// </summary>
public Abilities.Models.PendingPlayerPick? PendingPlayerPick { get; set; }
/// <summary>
/// Non-null when cards have been revealed face-up and a player must choose their
/// ordering (e.g. StackDeckEffect interactive path).
/// Paused until the chooser submits a <c>game.reveal_choice_pick</c> response.
/// </summary>
public Abilities.Models.PendingRevealChoicePick? PendingRevealChoicePick { get; set; }
/// <summary>
/// Non-null when a leaf Action has Chooser=Opponent/Ally and the non-activating player
/// must select the targets for that action before its effects execute.
/// Paused until the chooser submits a <c>game.target_pick</c> response.
/// </summary>
public Abilities.Models.PendingTargetPick? PendingTargetPick { get; set; }
/// <summary>
/// Returns true when any interactive pause is in effect (ability execution must stop).
/// </summary>
public bool HasPendingInteraction() =>
PendingCostPick is not null ||
PendingCostGroupPick is not null ||
PendingActionGroupPick is not null ||
PendingBranchPick is not null ||
PendingTilePick is not null ||
PendingPlayerPick is not null ||
PendingRevealChoicePick is not null ||
PendingTargetPick is not null;
}
/// <summary>
/// Options captured from a <c>PreventDeathEffect</c> when it is applied to a unit.
/// Consumed the first time the unit would die (or take lethal damage, for DamageIgnored).
/// </summary>
public sealed class PreventDeathMarker
{
/// <summary>After preventing death, set the unit's HP to this value. Null = 1.</summary>
public int? DamageTakenSetToHp { get; set; }
/// <summary>When true, the lethal hit's damage is fully ignored (unit takes 0).</summary>
public bool DamageIgnored { get; set; }
}
public sealed class PlayerState
{
public string AccountId { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty;
/// <summary>0-based position in the turn order. Set during game initialization.</summary>
public int SeatIndex { get; set; } = 0;
/// <summary>Team affiliation. FFA = same as SeatIndex (everyone on own team). Shared value = allies.</summary>
public int TeamIndex { get; set; } = 0;
/// <summary>True when this player's ArchSpirit has been destroyed in a multi-player game.</summary>
public bool IsEliminated { get; set; } = false;
// ── 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;
/// <summary>
/// Bonus/penalty to cards drawn THIS turn only (reset at end of turn).
/// Modified by ModifyCardsDrawnThisTurnEffect.
/// </summary>
public int CardsDrawnThisTurnBonus { get; set; }
/// <summary>
/// Number of upcoming turns this player will skip (decremented at turn-start).
/// Set by SkipTurnEffect.
/// </summary>
public int SkipTurnCount { get; set; }
// ── 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; }
/// <summary>
/// Override attack type set by ChangeAttackTypeEffect. Null = use card definition default.
/// </summary>
public AttackType? AttackType { 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>
/// 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; }
// ── Visual assets (used primarily for SpiritToken rendering) ─────────────
/// <summary>URL of the 2-D card art image (used by client for token display).</summary>
public string? Art2dUrl { get; set; }
/// <summary>URL of the 3-D model GLTF/GLB (used by client for token rendering).</summary>
public string? ModelUrl { 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 Action[] JSON — actions executed when the trigger fires.
/// Kept for backward-compatibility; superseded by <see cref="ActionGroupJson"/> when present.
/// </summary>
public string ActionsJson { get; set; } = "[]";
/// <summary>
/// Serialized ActionGroup? JSON — full recursive action tree. When non-null, used in
/// preference to <see cref="ActionsJson"/>.
/// </summary>
public string? ActionGroupJson { 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; }
/// <summary>Human-readable label describing the original applied effect (e.g. "ATK +2", "Rooted").</summary>
public string Label { get; set; } = string.Empty;
}