namespace SOR.Game; using System.Text.Json; using SOR.Database.Entities.Catalog; using SOR.Database.Enums; /// /// Pure game logic — no database access, no DI. Takes a GameState, mutates it, /// returns the updated state. Handlers are responsible for loading and saving. /// /// Rules applied (per gameplay.md + user spec): /// - Opening hand: all players draw OpeningHandSize cards at game start. /// - P1 skips the Draw phase on turn 1 (FirstPlayerSkipsDraw). /// P2 draws 1 at the start of their turn → 7 cards total by their first turn. /// - SP: starts at 0, accumulates SpAccumulationPerTurn per turn. Never resets. /// - ST: starts at 0, earned only through sacrifice — never granted per turn. /// - No entry sickness: units can attack/move/ability the turn they are summoned. /// - Defense restores to MaxDefense at the start of each turn (§6.9.3). /// - Win condition: ArchSpirit destruction. /// public static class GameEngine { private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web) { WriteIndented = false }; // ── Serialization ───────────────────────────────────────────────────────── public static GameState Deserialize(string json) => JsonSerializer.Deserialize(json, _json) ?? throw new InvalidOperationException("Failed to deserialize GameState."); public static string Serialize(GameState state) => JsonSerializer.Serialize(state, _json); public static GameRules DeserializeRules(string json) => JsonSerializer.Deserialize(json, _json) ?? GameRules.Default; // ── Initialization ──────────────────────────────────────────────────────── /// /// Build the initial GameState from card definition data for both players. /// /// Both players draw OpeningHandSize cards into their opening hand. /// ArchSpirit cards are placed on the field as leaders (not in the deck pile). /// SP and ST start at 0 for all players. /// /// If FirstPlayerSkipsDraw is true (the default), P1's first turn begins at /// Main phase — they already drew their opening hand. P2 gets a Draw phase at /// the start of their first turn, giving them one additional card (7 total). /// public static GameState Initialize( Guid sessionId, Guid p1AccountId, IEnumerable<(CardDefinition def, int qty)> p1Deck, Guid p1ArchSpiritDefId, CardDefinition p1ArchSpirit, Guid p2AccountId, IEnumerable<(CardDefinition def, int qty)> p2Deck, Guid p2ArchSpiritDefId, CardDefinition p2ArchSpirit, GameRules? rules = null) { rules ??= GameRules.Default; var state = new GameState { SessionId = sessionId, TurnNumber = 1, ActivePlayerAccountId = p1AccountId.ToString(), Rules = rules, }; state.Players[p1AccountId.ToString()] = BuildPlayerState(p1AccountId, p1Deck, p1ArchSpirit); state.Players[p2AccountId.ToString()] = BuildPlayerState(p2AccountId, p2Deck, p2ArchSpirit); // Both players draw their opening hand. DrawCards(state.Players[p1AccountId.ToString()], rules.OpeningHandSize); DrawCards(state.Players[p2AccountId.ToString()], rules.OpeningHandSize); // P1's first turn: skip Draw phase (they drew their opening hand already). // P2's first turn will begin at Draw phase — they draw 1 more card there. state.Phase = rules.FirstPlayerSkipsDraw ? GamePhase.Main : GamePhase.Draw; return state; } // ── Actions ─────────────────────────────────────────────────────────────── /// /// Draw the top card from the active player's deck into hand. /// Returns null if the deck is empty (no mill — just no draw). /// public static (GameState state, CardInstance? drawn) Draw(GameState state, string actorId) { ValidateActivePlayer(state, actorId); ValidatePhase(state, GamePhase.Draw, GamePhase.Main); var player = state.Players[actorId]; if (player.Deck.Count == 0) return (state, null); var card = player.Deck[0]; player.Deck.RemoveAt(0); player.Hand.Add(card); if (state.Phase == GamePhase.Draw) state.Phase = GamePhase.Main; return (state, card); } /// /// Play a card from hand onto the field (non-ArchSpirit cards only). /// Deducts SP/ST cost. Units can attack, move, and use abilities immediately /// (no entry sickness). /// public static GameState PlayCard(GameState state, string actorId, string cardInstanceId) { ValidateActivePlayer(state, actorId); ValidatePhase(state, GamePhase.Main); var player = state.Players[actorId]; var card = player.Hand.FirstOrDefault(c => c.InstanceId == cardInstanceId) ?? throw new GameException("CARD_NOT_IN_HAND"); if (player.CurrentSp < card.SpCost) throw new GameException("INSUFFICIENT_SP"); if (player.CurrentSt < card.StCost) throw new GameException("INSUFFICIENT_ST"); player.Hand.Remove(card); player.CurrentSp -= card.SpCost; player.CurrentSt -= card.StCost; var field = new FieldCard { InstanceId = card.InstanceId, CardDefinitionId = card.CardDefinitionId, Name = card.Name, CardType = card.CardType, Affinity = card.Affinity, Rarity = card.Rarity, SpCost = card.SpCost, StCost = card.StCost, MaxHealth = card.MaxHealth, CurrentHealth = card.MaxHealth, MaxDefense = card.MaxDefense, CurrentDefense = card.MaxDefense, Damage = card.Damage, CanAttack = card.CanAttack, CanDefend = card.CanDefend, IsExhausted = false, IsLeader = false, }; player.Field.Add(field); return state; } /// /// Declare an attack from one of the active player's field cards against an /// opponent's field card (or their ArchSpirit). /// /// Combat: attacker damage hits defender's defense first; overflow hits health. /// Defender counter-attacks (damage hits attacker's health directly if no defense). /// Destroyed units move to the Discard pile. /// If the defending ArchSpirit is destroyed the game ends. /// public static (GameState state, bool gameOver) Attack( GameState state, string actorId, string attackerInstanceId, string targetInstanceId) { ValidateActivePlayer(state, actorId); ValidatePhase(state, GamePhase.Main); var opponentId = GetOpponentId(state, actorId); var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId); var target = GetFieldCard(state.Players[opponentId], targetInstanceId); if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED"); if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK"); // Attacker hits target. ApplyDamage(target, attacker.Damage ?? 0); // Target counter-attacks if able (and still alive). if (target.CurrentHealth > 0 && target.CanAttack && !target.IsExhausted) ApplyDamage(attacker, target.Damage ?? 0); attacker.IsExhausted = true; // Clean up destroyed cards. bool gameOver = false; var activePlayer = state.Players[actorId]; var opponentPlayer = state.Players[opponentId]; if (attacker.CurrentHealth <= 0) MoveToDiscard(activePlayer, attacker); if (target.CurrentHealth <= 0) { if (target.IsLeader) { // ArchSpirit destroyed — game over. state.Phase = GamePhase.GameOver; gameOver = true; } else { MoveToDiscard(opponentPlayer, target); } } return (state, gameOver); } /// /// End the active player's turn. /// - Resets IsExhausted on all active player field cards. /// - Restores CurrentDefense to MaxDefense for all active player field cards (§6.9.3). /// - Switches the active player. /// - Accumulates SP for the next player (+SpAccumulationPerTurn; never resets). /// - Sets phase to Draw for the next player's turn. /// public static GameState EndTurn(GameState state, string actorId) { ValidateActivePlayer(state, actorId); ValidatePhase(state, GamePhase.Main); // Refresh active player's field cards at end of their turn. var active = state.Players[actorId]; foreach (var card in active.Field) { card.IsExhausted = false; if (card.MaxDefense.HasValue) card.CurrentDefense = card.MaxDefense; } if (active.ArchSpirit is not null) { active.ArchSpirit.IsExhausted = false; if (active.ArchSpirit.MaxDefense.HasValue) active.ArchSpirit.CurrentDefense = active.ArchSpirit.MaxDefense; } // Switch active player. state.ActivePlayerAccountId = GetOpponentId(state, actorId); // Next player's turn: advance counter, accumulate SP. var next = state.Players[state.ActivePlayerAccountId]; var rules = state.Rules; state.TurnNumber++; // SP accumulates — never resets between turns. next.CurrentSp += rules.SpAccumulationPerTurn; if (rules.SpHasCap && next.CurrentSp > rules.SpCap) next.CurrentSp = rules.SpCap; state.Phase = GamePhase.Draw; return state; } /// Mark the game as over with the conceding player as the loser. public static GameState Concede(GameState state, string actorId) { state.Phase = GamePhase.GameOver; return state; } // ── DTO projection ──────────────────────────────────────────────────────── /// /// Build a client-safe GameStateDto for a specific player's perspective. /// Opponent's hand is hidden (null); only the count is shown. /// public static GameStateDto ToDto(GameState state, string viewerAccountId) { var players = state.Players.Values.Select(p => { var isSelf = p.AccountId == viewerAccountId; return new PlayerStateDto( AccountId : Guid.Parse(p.AccountId), HandCount : p.Hand.Count, DeckCount : p.Deck.Count, Hand : isSelf ? p.Hand.Select(ToCardDto) : null, Field : p.Field.Select(ToCardDto), Discard : p.Discard.Select(ToCardDto), ArchSpirit : p.ArchSpirit != null ? ToCardDto(p.ArchSpirit) : null, CurrentSp : p.CurrentSp, CurrentSt : p.CurrentSt); }); return new GameStateDto( SessionId : state.SessionId, Phase : state.Phase.ToString(), ActivePlayerAccountId : state.ActivePlayerAccountId, TurnNumber : state.TurnNumber, Players : players); } // ── ELO ────────────────────────────────────────────────────────────────── /// /// Compute ELO rank score deltas after a game. /// Returns (winnerDelta, loserDelta) — both are positive values indicating change magnitude. /// public static (int winnerDelta, int loserDelta) ComputeEloDelta(int winnerScore, int loserScore) { const double K = 32.0; var expected = 1.0 / (1.0 + Math.Pow(10, (loserScore - winnerScore) / 400.0)); var winnerDelta = (int)Math.Round(K * (1.0 - expected)); var loserDelta = (int)Math.Round(K * expected); return (Math.Max(1, winnerDelta), Math.Max(1, loserDelta)); } // ── Helpers ─────────────────────────────────────────────────────────────── private static PlayerState BuildPlayerState( Guid accountId, IEnumerable<(CardDefinition def, int qty)> deckCards, CardDefinition archSpiritDef) { var ps = new PlayerState { AccountId = accountId.ToString() }; // Build deck pile (expand by quantity). var pile = new List(); foreach (var (def, qty) in deckCards) { for (int i = 0; i < qty; i++) pile.Add(DefinitionToInstance(def)); } // Shuffle. var rng = new Random(); for (int i = pile.Count - 1; i > 0; i--) { int j = rng.Next(i + 1); (pile[i], pile[j]) = (pile[j], pile[i]); } ps.Deck = pile; // ArchSpirit starts on the field as the leader. ps.ArchSpirit = new FieldCard { InstanceId = $"arch_{accountId:N}"[..8], CardDefinitionId = archSpiritDef.Id, Name = archSpiritDef.Name, CardType = archSpiritDef.CardType.ToString(), Affinity = archSpiritDef.Affinity.ToString(), Rarity = archSpiritDef.Rarity.ToString(), MaxHealth = archSpiritDef.MaxHealth, CurrentHealth = archSpiritDef.MaxHealth, MaxDefense = archSpiritDef.MaxDefense, CurrentDefense = archSpiritDef.MaxDefense, Damage = archSpiritDef.Damage, CanAttack = archSpiritDef.CanAttack ?? false, CanDefend = archSpiritDef.CanDefend ?? false, IsLeader = true, }; // SP and ST start at 0 for all players. ps.CurrentSp = 0; ps.CurrentSt = 0; return ps; } private static CardInstance DefinitionToInstance(CardDefinition def) => new() { InstanceId = Guid.NewGuid().ToString("N")[..8], CardDefinitionId = def.Id, Name = def.Name, CardType = def.CardType.ToString(), Affinity = def.Affinity.ToString(), Rarity = def.Rarity.ToString(), SpCost = def.SpCost, StCost = def.StCost, MaxHealth = def.MaxHealth, CurrentHealth = def.MaxHealth, MaxDefense = def.MaxDefense, CurrentDefense = def.MaxDefense, Damage = def.Damage, CanAttack = def.CanAttack ?? false, CanDefend = def.CanDefend ?? false, }; private static void DrawCards(PlayerState player, int count) { for (int i = 0; i < count && player.Deck.Count > 0; i++) { var card = player.Deck[0]; player.Deck.RemoveAt(0); player.Hand.Add(card); } } private static void ApplyDamage(CardInstance target, int damage) { if (target.CurrentDefense > 0) { var defVal = target.CurrentDefense.GetValueOrDefault(); var overflow = damage - defVal; target.CurrentDefense = Math.Max(0, defVal - damage); if (overflow > 0 && target.CurrentHealth.HasValue) target.CurrentHealth = Math.Max(0, target.CurrentHealth.Value - overflow); } else if (target.CurrentHealth.HasValue) { target.CurrentHealth = Math.Max(0, target.CurrentHealth.Value - damage); } } private static void MoveToDiscard(PlayerState player, FieldCard card) { player.Field.Remove(card); player.Discard.Add(card); } private static FieldCard GetFieldCard(PlayerState player, string instanceId) { var field = player.Field.OfType().FirstOrDefault(c => c.InstanceId == instanceId); if (field != null) return field; if (player.ArchSpirit?.InstanceId == instanceId) return player.ArchSpirit; throw new GameException("CARD_NOT_ON_FIELD"); } private static string GetOpponentId(GameState state, string actorId) => state.Players.Keys.First(k => k != actorId); private static void ValidateActivePlayer(GameState state, string actorId) { if (state.ActivePlayerAccountId != actorId) throw new GameException("NOT_YOUR_TURN"); } private static void ValidatePhase(GameState state, params GamePhase[] allowed) { if (!allowed.Contains(state.Phase)) throw new GameException($"INVALID_PHASE:{state.Phase}"); } private static CardInstanceDto ToCardDto(CardInstance c) => new( InstanceId : c.InstanceId, CardDefinitionId : c.CardDefinitionId, Name : c.Name, CardType : c.CardType, Affinity : c.Affinity, Rarity : c.Rarity, CurrentHealth : c.CurrentHealth, MaxHealth : c.MaxHealth, CurrentDefense : c.CurrentDefense, MaxDefense : c.MaxDefense, Damage : c.Damage, IsExhausted : c.IsExhausted, IsLeader : c is FieldCard fc && fc.IsLeader); } /// Game-rule violation — maps to a client error code. public sealed class GameException : Exception { public string ErrorCode { get; } public GameException(string code) : base(code) => ErrorCode = code; }