namespace SOR.Game;
using System.Text.Json;
using System.Text.Json.Serialization;
using SOR.Database.Entities.Catalog;
using SOR.Database.Enums;
using SOR.Game.Abilities;
using SOR.Game.Combat;
using SOR.Game.Grid;
///
/// Pure game logic — no database access, no DI. Takes a GameState, mutates it,
/// returns the updated state. Handlers are responsible for loading and saving.
///
/// Turn flow:
/// 1. game.ready (both players) → Placement phase, board created.
/// 2. game.place_arch_spirit (both players) → affinities pushed, opening draw, turn 1 begins.
/// 3. Draw → Main → EndTurn → (repeat).
///
/// Rules applied (per gameplay.md + user spec):
/// - Opening hand: both players draw OpeningHandSize cards after placement.
/// - P1 skips the Draw phase on turn 1 (FirstPlayerSkipsDraw).
/// - 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/sacrifice the turn they are channeled.
/// - Defense restores to MaxDefense at the start of each player's turn (§6.9.3).
/// - MP restores to MaxMp at the start of each player's turn (§6.0).
/// - Win condition: ArchSpirit destruction.
///
public static class GameEngine
{
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web)
{
WriteIndented = false,
Converters = { new JsonStringEnumConverter() },
};
// ── 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.
///
/// The game starts in the Placement phase — both players must call PlaceArchSpirit
/// before the opening draw happens and turn 1 begins.
///
/// Decks are shuffled. ArchSpirits are created but NOT yet placed on the board
/// (Position = null until PlaceArchSpirit is called).
///
public static GameState Initialize(
Guid sessionId,
Guid p1AccountId, IEnumerable<(CardDefinition def, int qty)> p1Deck, CardDefinition p1ArchSpirit,
Guid p2AccountId, IEnumerable<(CardDefinition def, int qty)> p2Deck, CardDefinition p2ArchSpirit,
GameRules? rules = null)
{
rules ??= GameRules.Default;
var state = new GameState
{
SessionId = sessionId,
TurnNumber = 1,
ActivePlayerAccountId = p1AccountId.ToString(),
PlayerOneAccountId = p1AccountId.ToString(),
Rules = rules,
Phase = GamePhase.Placement,
Board = Board.Create(rules.BoardWidth, rules.BoardHeight),
};
state.Players[p1AccountId.ToString()] = BuildPlayerState(p1AccountId, p1Deck, p1ArchSpirit);
state.Players[p2AccountId.ToString()] = BuildPlayerState(p2AccountId, p2Deck, p2ArchSpirit);
return state;
}
// ── Actions ────────────────────────────────────────────────────────────────
///
/// Place the player's ArchSpirit on their starting row (Placement phase).
///
/// P1 must place in row y=0; P2 must place in row y=Height-1.
/// Affinity is pushed to the placement tile and all in-bounds orthogonal neighbors.
///
/// When both players have placed, the opening draw is performed and turn 1 begins.
/// Returns whether both players are now placed (game can advance).
///
public static (GameState state, bool bothPlaced) PlaceArchSpirit(
GameState state, string actorId, Coord coord)
{
ValidatePhase(state, GamePhase.Placement);
var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
var player = state.Players[actorId];
var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
if (archSpirit.Position.HasValue) throw new GameException("ARCH_SPIRIT_ALREADY_PLACED");
// Validate placement row.
bool isP1 = actorId == state.PlayerOneAccountId;
int expectedRow = isP1 ? 0 : board.Height - 1;
if (coord.Y != expectedRow) throw new GameException("INVALID_PLACEMENT_ROW");
// Validate tile.
var tile = board.GetTile(coord) ?? throw new GameException("TILE_OUT_OF_BOUNDS");
if (!tile.IsEmpty) throw new GameException("TILE_OCCUPIED");
// Place ArchSpirit.
archSpirit.Position = coord;
archSpirit.CurrentMp = archSpirit.MaxMp ?? 0;
board.PlaceUnit(coord, archSpirit.InstanceId, actorId);
// Push placement affinity.
if (Enum.TryParse(archSpirit.Affinity, out var affinity))
AffinitySystem.ApplyPlacementAffinity(board, coord, affinity);
// Check if both players have placed.
bool bothPlaced = state.Players.Values.All(p => p.ArchSpirit?.Position.HasValue == true);
if (bothPlaced)
{
var rules = state.Rules;
// Opening draw for both players.
foreach (var p in state.Players.Values)
DrawCards(p, rules.OpeningHandSize);
// P1 gets first-turn SP accumulation.
var p1 = state.Players[state.PlayerOneAccountId];
p1.CurrentSp += rules.SpAccumulationPerTurn;
if (rules.SpHasCap && p1.CurrentSp > rules.SpCap)
p1.CurrentSp = rules.SpCap;
// Advance to first turn phase.
state.Phase = rules.FirstPlayerSkipsDraw ? GamePhase.Main : GamePhase.Draw;
}
return (state, bothPlaced);
}
///
/// Draw cards from the active player's deck into hand.
/// Draws Rules.DrawPerTurn + player.DrawPerTurnBonus cards in one call.
/// Respects HandSizeCap: if DiscardOnMaxHand, excess cards are auto-discarded;
/// otherwise drawing stops when the cap is reached.
///
public static (GameState state, IReadOnlyList drawn) Draw(GameState state, string actorId)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Draw, GamePhase.Main);
var player = state.Players[actorId];
var rules = state.Rules;
int count = Math.Max(1, rules.DrawPerTurn + player.DrawPerTurnBonus);
var drawn = new List(count);
for (int i = 0; i < count && player.Deck.Count > 0; i++)
{
// If capped and not auto-discarding, stop drawing once at cap.
if (rules.HandSizeCap > 0 && !rules.DiscardOnMaxHand && player.Hand.Count >= rules.HandSizeCap)
break;
var card = player.Deck[0];
player.Deck.RemoveAt(0);
player.Hand.Add(card);
drawn.Add(card);
}
// Auto-discard excess from the newest-drawn cards when DiscardOnMaxHand is active.
if (rules.HandSizeCap > 0 && rules.DiscardOnMaxHand)
{
while (player.Hand.Count > rules.HandSizeCap)
{
var last = player.Hand[^1];
player.Hand.RemoveAt(player.Hand.Count - 1);
player.Discard.Add(last);
drawn.Remove(last);
}
}
if (state.Phase == GamePhase.Draw)
state.Phase = GamePhase.Main;
return (state, drawn);
}
///
/// Channel (play) a card from hand.
///
/// Spirit: targetTiles must have exactly 1 entry — a tile within the ArchSpirit's
/// channeling range with valid affinity. The Spirit is placed there.
///
/// Terramorpha: targetTiles must have N entries matching TerramorphaMode (Mono=1, Di=2,
/// Tri=3). Each subsequent tile must be orthogonally adjacent to the previous.
/// The card's affinity is pushed to each tile; the card then goes to Discard.
///
/// Ruin: placed on a random tile matching the card's affinity (ignores occupancy).
/// Abilities fire at TurnStart if a Spirit/ArchSpirit occupies the tile.
///
/// Repentance / Instinct: pass ability targets via cardTargets for unit/tile inputs.
///
public static GameState ChannelCard(
GameState state, string actorId, string cardInstanceId, IReadOnlyList? targetTiles,
IReadOnlyList? cardTargets = null)
{
var player = state.Players[actorId];
var card = player.Hand.FirstOrDefault(c => c.InstanceId == cardInstanceId)
?? throw new GameException("CARD_NOT_IN_HAND");
// Instinct is quick-play: it may be channeled on any turn (including opponent turn),
// but never during Setup/Placement/GameOver.
if (card.CardType == "Instinct")
{
if (state.Phase is GamePhase.Setup or GamePhase.Placement or GamePhase.GameOver)
throw new GameException($"INVALID_PHASE:{state.Phase}");
}
else
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
}
if (player.CurrentSp < card.SpCost) throw new GameException("INSUFFICIENT_SP");
if (player.CurrentSt < card.StCost) throw new GameException("INSUFFICIENT_ST");
// Ability lock-out checks.
if (card.CardType == "Spirit" && !player.CanChannelSpirit)
throw new GameException("CANNOT_CHANNEL_SPIRIT");
if (card.CardType == "Repentance" && !player.CanChannelRepentance)
throw new GameException("CANNOT_CHANNEL_REPENTANCE");
if (card.CardType == "Instinct" && !player.CanChannelInstinct)
throw new GameException("CANNOT_CHANNEL_INSTINCT");
if (card.CardType == "Ruin" && !player.CanChannelRuin)
throw new GameException("CANNOT_CHANNEL_RUIN");
if (card.CardType == "Terramorpha")
{
var allowed = card.TerramorphaMode switch
{
TerramorphaMode.Mono => player.CanChannelTerramorphaMono,
TerramorphaMode.Di => player.CanChannelTerramorphaDi,
TerramorphaMode.Tri => player.CanChannelTerramorphaTri,
_ => true,
};
if (!allowed) throw new GameException("CANNOT_CHANNEL_TERRAMORPHA");
}
var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
if (card.CardType == "Spirit")
{
if (targetTiles is null || targetTiles.Count == 0)
throw new GameException("TARGET_TILE_REQUIRED");
var coord = targetTiles[0];
var tile = board.GetTile(coord) ?? throw new GameException("TILE_OUT_OF_BOUNDS");
if (!tile.IsEmpty) throw new GameException("TILE_OCCUPIED");
// Validate channeling range from ArchSpirit.
var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
if (archSpirit.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED");
var minRange = card.MinChannelRange ?? 1;
var maxRange = card.MaxChannelRange ?? 1;
var dist = archSpirit.Position.Value.ManhattanDistance(coord);
if (dist < minRange || dist > maxRange)
throw new GameException("OUT_OF_CHANNEL_RANGE");
// Validate affinity.
if (Enum.TryParse(card.Affinity, out var cardAffinity))
{
if (!AffinitySystem.IsAffinityValid(tile, cardAffinity))
throw new GameException("INVALID_AFFINITY");
}
player.Hand.Remove(card);
player.CurrentSp -= card.SpCost;
player.CurrentSt -= card.StCost;
var field = ToFieldCard(card, coord);
player.Field.Add(field);
board.PlaceUnit(coord, field.InstanceId, actorId);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Channeled,
ActorId = actorId,
CardType = "Spirit",
Data = new TriggerEventData { SourceId = field.InstanceId },
});
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitEnterBattlefield,
ActorId = actorId,
UnitType = "Spirit",
Data = new TriggerEventData { SourceId = field.InstanceId },
});
AbilitySystem.EvaluateAurasOnEnter(state, field.InstanceId);
AbilitySystem.ApplyPassivesForSource(state, field.InstanceId, actorId);
AbilitySystem.ApplyPassivesToNewTarget(state, field.InstanceId);
}
else if (card.CardType == "Terramorpha")
{
int expectedCount = card.TerramorphaMode switch
{
TerramorphaMode.Mono => 1,
TerramorphaMode.Di => 2,
TerramorphaMode.Tri => 3,
_ => throw new GameException("UNKNOWN_TERRAMORPHA_MODE"),
};
if (targetTiles is null || targetTiles.Count != expectedCount)
throw new GameException("INVALID_TILE_COUNT");
// Validate all tiles are in bounds.
foreach (var t in targetTiles)
if (board.GetTile(t) is null)
throw new GameException("TILE_OUT_OF_BOUNDS");
// Di/Tri: each subsequent tile must be orthogonally adjacent to the previous.
for (int i = 1; i < targetTiles.Count; i++)
if (!targetTiles[i].IsOrthogonallyAdjacentTo(targetTiles[i - 1]))
throw new GameException("TILES_NOT_ADJACENT");
player.Hand.Remove(card);
player.CurrentSp -= card.SpCost;
player.CurrentSt -= card.StCost;
// Push card affinity to each targeted tile.
if (Enum.TryParse(card.Affinity, out var affinity))
foreach (var t in targetTiles)
AffinitySystem.PushAffinity(board.GetTile(t)!, affinity);
player.Discard.Add(card);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Channeled,
ActorId = actorId,
CardType = "Terramorpha",
});
// Tile affinities changed — re-evaluate conditional passives for all units.
AbilitySystem.ReEvaluateConditionalPassives(state);
}
else if (card.CardType == "Ruin")
{
// Place on a random tile matching the Ruin's affinity (may already be occupied).
var hasAffinity = Enum.TryParse(card.Affinity, out var ruinAffinity);
var validTiles = board.Tiles.Values
.Where(t => !hasAffinity || AffinitySystem.IsAffinityValid(t, ruinAffinity))
.ToList();
if (validTiles.Count == 0) throw new GameException("NO_VALID_TILE");
var ruinCoord = validTiles[Random.Shared.Next(validTiles.Count)].Coord;
player.Hand.Remove(card);
player.CurrentSp -= card.SpCost;
player.CurrentSt -= card.StCost;
var ruinField = ToFieldCard(card, ruinCoord);
player.Field.Add(ruinField);
board.PlaceRuin(ruinCoord, ruinField.InstanceId, actorId);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Channeled,
ActorId = actorId,
CardType = "Ruin",
Data = new TriggerEventData { SourceId = ruinField.InstanceId },
});
}
else
{
// Repentance, Instinct — pay cost, fire EffectsJson actions, then discard.
player.Hand.Remove(card);
player.CurrentSp -= card.SpCost;
player.CurrentSt -= card.StCost;
// Fire inline effects if the card has an EffectsJson action list.
AbilitySystem.FireCardEffects(state, actorId, card, cardTargets);
player.Discard.Add(card);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Channeled,
ActorId = actorId,
CardType = card.CardType,
});
}
return state;
}
///
/// Ascend the active player's ArchSpirit to the next tier (§6.7.2).
///
/// The incoming ArchSpirit must be exactly one tier above the current and must link
/// back to it via PreviousTierId. It may reside in any zone (hand, deck, or discard).
/// Cost is the incoming ArchSpirit's SP/ST cost.
/// The new ArchSpirit enters at the current position with full HP, Defense, and MP.
///
public static GameState Ascend(GameState state, string actorId, string incomingCardInstanceId)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
var player = state.Players[actorId];
var current = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
if (current.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED");
// Find the incoming ArchSpirit in any zone (hand → deck → discard).
var incoming = FindInAnyZone(player, incomingCardInstanceId)
?? throw new GameException("CARD_NOT_FOUND");
if (incoming.CardType != "ArchSpirit")
throw new GameException("NOT_AN_ARCH_SPIRIT");
// Tier chain: incoming must be exactly current.Tier + 1.
int currentTier = current.Tier ?? 1;
if (incoming.Tier != currentTier + 1)
throw new GameException("INVALID_ASCEND_TIER");
// Lineage: incoming.PreviousTierId must reference current's CardDefinitionId.
if (incoming.PreviousTierId != current.CardDefinitionId)
throw new GameException("INVALID_ASCEND_LINEAGE");
// Pay the incoming ArchSpirit's cost.
if (player.CurrentSp < incoming.SpCost) throw new GameException("INSUFFICIENT_SP");
if (player.CurrentSt < incoming.StCost) throw new GameException("INSUFFICIENT_ST");
player.CurrentSp -= incoming.SpCost;
player.CurrentSt -= incoming.StCost;
// Remove incoming from its zone.
RemoveFromAnyZone(player, incoming);
// Build the new FieldCard at the current position.
var coord = current.Position.Value;
var newArchSpirit = ToFieldCard(incoming, coord, isLeader: true);
// Remove current from board; move to discard.
board.RemoveUnit(current.InstanceId);
player.Discard.Add(current);
// Seat the new ArchSpirit.
player.ArchSpirit = newArchSpirit;
board.PlaceUnit(coord, newArchSpirit.InstanceId, actorId);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Ascend,
ActorId = actorId,
Data = new TriggerEventData { SourceId = newArchSpirit.InstanceId },
});
return state;
}
///
/// Transition the active player's ArchSpirit with a Tier 1 ArchSpirit from hand (§6.7.1).
///
/// The incoming must be Tier 1 and must come from hand.
/// Cost is the incoming ArchSpirit's SP/ST cost.
/// The new ArchSpirit enters at the current position with full HP, Defense, and MP.
///
public static GameState Transition(GameState state, string actorId, string incomingCardInstanceId)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
var player = state.Players[actorId];
var current = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
if (current.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED");
// Incoming must be in hand (§6.7.1).
var incoming = player.Hand.FirstOrDefault(c => c.InstanceId == incomingCardInstanceId)
?? throw new GameException("CARD_NOT_IN_HAND");
if (incoming.CardType != "ArchSpirit")
throw new GameException("NOT_AN_ARCH_SPIRIT");
// Must be Tier 1.
if ((incoming.Tier ?? 1) != 1)
throw new GameException("NOT_TIER_1");
if (!player.CanTransitionArchSpirit)
throw new GameException("CANNOT_TRANSITION");
// Pay the incoming ArchSpirit's cost.
if (player.CurrentSp < incoming.SpCost) throw new GameException("INSUFFICIENT_SP");
if (player.CurrentSt < incoming.StCost) throw new GameException("INSUFFICIENT_ST");
player.CurrentSp -= incoming.SpCost;
player.CurrentSt -= incoming.StCost;
player.Hand.Remove(incoming);
// Build the new FieldCard at the current position.
var coord = current.Position.Value;
var newArchSpirit = ToFieldCard(incoming, coord, isLeader: true);
// Remove current from board; fire aura leave before removal.
AbilitySystem.EvaluateAurasOnLeave(state, current.InstanceId);
AbilitySystem.RevokePassivesForSource(state, current.InstanceId);
board.RemoveUnit(current.InstanceId);
player.Discard.Add(current);
// Seat the new ArchSpirit; fire aura enter after placement.
player.ArchSpirit = newArchSpirit;
board.PlaceUnit(coord, newArchSpirit.InstanceId, actorId);
AbilitySystem.EvaluateAurasOnEnter(state, newArchSpirit.InstanceId);
AbilitySystem.ApplyPassivesForSource(state, newArchSpirit.InstanceId, actorId);
AbilitySystem.ApplyPassivesToNewTarget(state, newArchSpirit.InstanceId);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.Transition,
ActorId = actorId,
Data = new TriggerEventData { SourceId = newArchSpirit.InstanceId },
});
return state;
}
///
/// Move a unit on the board.
///
/// Walk/Flight: BFS pathfinding within the unit's remaining MP.
/// Walk: all occupied tiles block pathing.
/// Flight: only tiles occupied by other Flight units block pathing.
///
/// Jump: can land on any empty in-bounds tile; costs 1 MP per landing.
/// Teleport: same as Jump but requires line-of-sight to the destination; costs 1 MP.
///
public static GameState MoveUnit(
GameState state, string actorId, string unitInstanceId, Coord targetPos)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
var player = state.Players[actorId];
var unit = GetFieldCard(player, unitInstanceId);
if (unit.Position is null) throw new GameException("UNIT_NOT_ON_BOARD");
if (unit.CurrentMp <= 0) throw new GameException("NO_MP");
var from = unit.Position.Value;
var targetTile = board.GetTile(targetPos) ?? throw new GameException("TILE_OUT_OF_BOUNDS");
if (!targetTile.IsEmpty) throw new GameException("TILE_OCCUPIED");
if (from == targetPos) throw new GameException("ALREADY_AT_TARGET");
var movType = unit.MovementType;
if (movType == MovementType.Walk || movType == MovementType.Flight)
{
var blocked = BuildBlockedSet(state, unitInstanceId, movType);
var reachable = Pathfinding.GetReachableWithCost(board, from, unit.CurrentMp, blocked);
if (!reachable.TryGetValue(targetPos, out var cost))
throw new GameException("TILE_UNREACHABLE");
unit.CurrentMp -= cost;
}
else if (movType == MovementType.Jump)
{
unit.CurrentMp -= 1;
}
else if (movType == MovementType.Teleport)
{
var occupancy = board.BuildOccupancyMap();
occupancy.Remove(from); // exclude self from LOS check
if (!LineOfSight.HasLos(board, from, targetPos, occupancy))
throw new GameException("NO_LINE_OF_SIGHT");
unit.CurrentMp -= 1;
}
else
{
throw new GameException("UNIT_CANNOT_MOVE");
}
unit.Position = targetPos;
board.MoveUnit(unitInstanceId, targetPos);
AbilitySystem.EvaluateAuraTransitions(state, unitInstanceId, from, targetPos);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitMove,
ActorId = actorId,
UnitType = unit.CardType,
Data = new TriggerEventData { SourceId = unitInstanceId },
});
// Fire UnitOccupyRuin if the destination tile has a Ruin.
var destTileAfterMove = board.GetTile(targetPos);
if (destTileAfterMove?.RuinId is not null)
{
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitOccupyRuin,
ActorId = actorId,
Data = new TriggerEventData { SourceId = unitInstanceId, TargetId = destTileAfterMove.RuinId },
});
}
// A unit changed tiles — re-evaluate tile-affinity (and other) conditional passives.
AbilitySystem.ReEvaluateConditionalPassives(state);
return state;
}
///
/// Declare an attack from one of the active player's field cards against an
/// opponent's field card (or their ArchSpirit).
///
/// Range and LOS are validated against the board when present.
/// Combat: attacker damage hits defender's defense first; overflow hits health.
/// Defender counter-attacks (damage hits attacker's health directly if no defense).
/// 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");
if (!target.CanBeAttacked) throw new GameException("TARGET_CANNOT_BE_ATTACKED");
// Range + LOS validation when board is active.
if (state.Board is not null && attacker.Position.HasValue && target.Position.HasValue)
{
var occupancy = state.Board.BuildOccupancyMap();
var minRange = attacker.MinAttackRange ?? 1;
var maxRange = attacker.MaxAttackRange ?? 1;
if (!AttackSystem.CanAttack(
attacker.Position.Value, target.Position.Value,
minRange, maxRange, attacker.RequiresLos,
state.Board, occupancy))
throw new GameException("TARGET_OUT_OF_RANGE");
}
// 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);
// Consume extra attack or exhaust normally.
if (attacker.ExtraAttacksRemaining > 0)
attacker.ExtraAttacksRemaining--;
else
attacker.IsExhausted = true;
bool gameOver = false;
var activePlayer = state.Players[actorId];
var opponentPlayer = state.Players[opponentId];
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitAttack,
ActorId = actorId,
UnitType = attacker.CardType,
Data = new TriggerEventData
{
SourceId = attackerInstanceId,
TargetId = targetInstanceId,
},
});
if (attacker.CurrentHealth <= 0)
{
AbilitySystem.EvaluateAurasOnLeave(state, attacker.InstanceId);
AbilitySystem.RevokePassivesForSource(state, attacker.InstanceId);
if (state.Board is not null) state.Board.RemoveUnit(attacker.InstanceId);
MoveToDiscard(activePlayer, attacker);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitDeath,
ActorId = actorId,
UnitType = attacker.CardType,
Data = new TriggerEventData { TargetId = attacker.InstanceId },
});
}
if (target.CurrentHealth <= 0)
{
if (target.IsLeader)
{
state.Phase = GamePhase.GameOver;
gameOver = true;
}
else
{
AbilitySystem.EvaluateAurasOnLeave(state, target.InstanceId);
AbilitySystem.RevokePassivesForSource(state, target.InstanceId);
if (state.Board is not null) state.Board.RemoveUnit(target.InstanceId);
MoveToDiscard(opponentPlayer, target);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitDeath,
ActorId = opponentId,
UnitType = target.CardType,
Data = new TriggerEventData { TargetId = target.InstanceId },
});
}
}
return (state, gameOver);
}
///
/// Sacrifice a Spirit adjacent to the player's ArchSpirit (§6.15).
/// Sacrifice is a free action — does not exhaust the Spirit and does not consume
/// attack or ability uses.
///
public static GameState Sacrifice(GameState state, string actorId, string unitInstanceId)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
var player = state.Players[actorId];
var unit = player.Field.OfType()
.FirstOrDefault(c => c.InstanceId == unitInstanceId)
?? throw new GameException("UNIT_NOT_ON_FIELD");
if (unit.IsLeader) throw new GameException("CANNOT_SACRIFICE_ARCH_SPIRIT");
if (!unit.CanBeSacrificed) throw new GameException("UNIT_CANNOT_BE_SACRIFICED");
var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
if (archSpirit.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED");
if (unit.Position is null) throw new GameException("UNIT_NOT_ON_BOARD");
if (!unit.Position.Value.IsOrthogonallyAdjacentTo(archSpirit.Position.Value))
throw new GameException("UNIT_NOT_ADJACENT_TO_ARCH_SPIRIT");
int stReturn;
if (unit.FixedSacrificeReturn.HasValue && unit.FixedSacrificeReturn.Value >= 0)
stReturn = unit.FixedSacrificeReturn.Value;
else
{
var sacValue = SacrificeSystem.GetSacrificeValue(unit.StCost, unit.SpCost);
stReturn = SacrificeSystem.GetSTReturn(player.CurrentSt, sacValue);
}
player.CurrentSt += stReturn;
AbilitySystem.EvaluateAurasOnLeave(state, unitInstanceId);
AbilitySystem.RevokePassivesForSource(state, unitInstanceId);
if (state.Board is not null) state.Board.RemoveUnit(unitInstanceId);
player.Field.Remove(unit);
player.Discard.Add(unit);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.SpiritSacrificed,
ActorId = actorId,
UnitType = unit.CardType,
Data = new TriggerEventData { SourceId = actorId, TargetId = unitInstanceId },
});
return state;
}
///
/// End the active player's turn.
///
/// Per §6.0 (applied at start of next player's turn):
/// 1. MP restoration for all friendly units.
/// 2. Defense restoration for all friendly units.
/// 3. SP accumulation.
/// 4. Advance to Draw phase.
///
/// IsExhausted resets for the ENDING player's units (they finished acting).
/// MP + Defense restore for the STARTING player (at the top of their turn).
///
///
/// Returns gameOver = true when TurnLimit is exceeded; winner is the player with more
/// ArchSpirit HP (P1 wins on tie). Caller must invoke FinalizeGameAsync in that case.
///
public static (GameState state, bool gameOver) EndTurn(GameState state, string actorId)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
// Reset exhausted and ability uses for the player ending their turn.
var active = state.Players[actorId];
foreach (var card in active.Field.OfType())
{
card.IsExhausted = false;
card.AbilityUsesThisTurn = null;
card.ExtraAttacksRemaining = 0;
}
if (active.ArchSpirit is not null)
{
active.ArchSpirit.IsExhausted = false;
active.ArchSpirit.AbilityUsesThisTurn = null;
active.ArchSpirit.ExtraAttacksRemaining = 0;
}
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.TurnEnd,
ActorId = actorId,
});
// Tick DOT/HOT effects, then expire UntilEndOfTurn and ForNTurns effects.
AbilitySystem.TickActiveEffects(state, actorId);
AbilitySystem.ExpireActiveEffects(state, actorId, isEndOfTurn: true);
// Switch active player and increment turn counter.
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
state.TurnNumber++;
// Check turn limit BEFORE setting up the new turn.
var rules = state.Rules;
if (rules.TurnLimit > 0 && state.TurnNumber > rules.TurnLimit)
{
state.Phase = GamePhase.GameOver;
return (state, true);
}
// Start of next player's turn: restore MP (+ MpBuff), defense, accumulate SP.
var next = state.Players[state.ActivePlayerAccountId];
foreach (var card in next.Field.OfType())
{
if (card.MaxMp.HasValue) card.CurrentMp = card.MaxMp.Value + rules.MpBuff;
if (card.MaxDefense.HasValue) card.CurrentDefense = card.MaxDefense;
}
if (next.ArchSpirit is not null)
{
if (next.ArchSpirit.MaxMp.HasValue) next.ArchSpirit.CurrentMp = next.ArchSpirit.MaxMp.Value + rules.MpBuff;
if (next.ArchSpirit.MaxDefense.HasValue) next.ArchSpirit.CurrentDefense = next.ArchSpirit.MaxDefense;
}
next.CurrentSp += rules.SpAccumulationPerTurn + next.SpAccumulationBonus;
if (rules.SpHasCap && next.CurrentSp > rules.SpCap)
next.CurrentSp = rules.SpCap;
state.Phase = GamePhase.Draw;
// Expire UntilStartOfOwnerTurn effects now that the new active player is set.
AbilitySystem.ExpireActiveEffects(state, state.ActivePlayerAccountId, isEndOfTurn: false);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.TurnStart,
ActorId = state.ActivePlayerAccountId,
});
AbilitySystem.FireRuinAbilities(state);
return (state, false);
}
///
/// Helper to determine the turn-limit winner: player with more ArchSpirit HP.
/// P1 wins on tie. Returns (winnerId, loserId).
///
public static (Guid winnerId, Guid loserId) GetTurnLimitWinner(GameState state)
{
var p1Id = Guid.Parse(state.PlayerOneAccountId);
var p2Id = Guid.Parse(GetOpponentId(state, state.PlayerOneAccountId));
var p1Hp = state.Players[state.PlayerOneAccountId].ArchSpirit?.CurrentHealth ?? 0;
var p2Hp = state.Players[state.Players.Keys.First(k => k != state.PlayerOneAccountId)].ArchSpirit?.CurrentHealth ?? 0;
return p1Hp >= p2Hp ? (p1Id, p2Id) : (p2Id, p1Id);
}
/// 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;
}
///
/// Activate an Active ability on a field unit owned by the active player.
/// Validates turn / phase, delegates cost + effect resolution to AbilitySystem.
///
public static GameState ActivateAbility(
GameState state,
string actorId,
string sourceInstanceId,
int abilityIndex,
IReadOnlyList? targets)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
state = AbilitySystem.ActivateAbility(state, actorId, sourceInstanceId, abilityIndex, targets);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitAbilityActivated,
ActorId = actorId,
Data = new TriggerEventData { SourceId = sourceInstanceId },
});
AbilitySystem.ReEvaluateConditionalPassives(state);
return state;
}
// ── DTO projection ────────────────────────────────────────────────────────
///
/// Build a spectator-safe GameStateDto — both players' hands are hidden (null).
///
public static GameStateDto ToDtoSpectator(GameState state)
=> ToDto(state, string.Empty); // Empty string matches neither player → both hands hidden.
///
/// 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);
});
var boardDto = state.Board is not null ? ToBoardDto(state.Board) : null;
return new GameStateDto(
SessionId : state.SessionId,
Phase : state.Phase.ToString(),
ActivePlayerAccountId : state.ActivePlayerAccountId,
PlayerOneAccountId : state.PlayerOneAccountId,
TurnNumber : state.TurnNumber,
StateVersion : state.NextActionSequence,
Players : players,
Board : boardDto);
}
// ── Deck validation ───────────────────────────────────────────────────────
///
/// Validate a deck against custom lobby rules.
/// Returns a list of error codes (empty = valid). Only checks rules with non-zero limits.
/// Does not check the arch spirit (it is validated separately at card-edit time).
///
public static IReadOnlyList ValidateDeck(
IEnumerable<(CardDefinition def, int qty)> deck,
GameRules rules)
{
var errors = new List();
var deckList = deck.ToList();
int totalCards = deckList.Sum(d => d.qty);
if (rules.MinDeckSize > 0 && totalCards < rules.MinDeckSize)
errors.Add($"DECK_TOO_SMALL:{totalCards}<{rules.MinDeckSize}");
if (rules.MaxDeckSize > 0 && totalCards > rules.MaxDeckSize)
errors.Add($"DECK_TOO_LARGE:{totalCards}>{rules.MaxDeckSize}");
if (rules.MaxArchTier1 > 0)
{
var tier1Count = deckList
.Where(d => d.def.CardType == CardType.ArchSpirit && (d.def.Tier ?? 1) == 1)
.Sum(d => d.qty);
if (tier1Count > rules.MaxArchTier1)
errors.Add($"TOO_MANY_ARCH_TIER1:{tier1Count}>{rules.MaxArchTier1}");
}
return errors;
}
// ── ELO ───────────────────────────────────────────────────────────────────
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() };
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: created but not yet placed (Position = null, CurrentMp = 0 until placed).
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,
CanMove = archSpiritDef.CanMove ?? false,
MovementType = archSpiritDef.MovementType,
MaxMp = archSpiritDef.MovementPoints,
CurrentMp = 0, // set when placed during Placement phase
MinAttackRange = archSpiritDef.MinAttackRange,
MaxAttackRange = archSpiritDef.MaxAttackRange,
RequiresLos = archSpiritDef.RequiresLos ?? false,
MinChannelRange = archSpiritDef.MinChannelRange,
MaxChannelRange = archSpiritDef.MaxChannelRange,
IsLeader = true,
IsExhausted = false,
Position = null,
Tier = archSpiritDef.Tier,
PreviousTierId = archSpiritDef.PreviousTierId,
AbilitiesJson = archSpiritDef.AbilitiesJson,
EffectsJson = archSpiritDef.EffectsJson,
};
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,
CanMove = def.CanMove ?? false,
MovementType = def.MovementType,
MaxMp = def.MovementPoints,
MinAttackRange = def.MinAttackRange,
MaxAttackRange = def.MaxAttackRange,
RequiresLos = def.RequiresLos ?? false,
MinChannelRange = def.MinChannelRange,
MaxChannelRange = def.MaxChannelRange,
Tier = def.Tier,
PreviousTierId = def.PreviousTierId,
TerramorphaMode = def.TerramorphaMode,
AbilitiesJson = def.AbilitiesJson,
EffectsJson = def.EffectsJson,
Genus = def.Genus?.ToList(),
};
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 HashSet BuildBlockedSet(
GameState state, string movingUnitId, MovementType? movType)
{
var blocked = new HashSet();
foreach (var player in state.Players.Values)
{
foreach (var card in player.Field.OfType())
{
if (card.InstanceId == movingUnitId) continue;
if (!card.Position.HasValue) continue;
// Flight is blocked only by other Flight units; Walk is blocked by all.
if (movType == MovementType.Flight && card.MovementType != MovementType.Flight) continue;
blocked.Add(card.Position.Value);
}
var arch = player.ArchSpirit;
if (arch is not null && arch.InstanceId != movingUnitId && arch.Position.HasValue)
{
if (movType != MovementType.Flight || arch.MovementType == MovementType.Flight)
blocked.Add(arch.Position.Value);
}
}
return blocked;
}
///
/// Create a FieldCard from an existing CardInstance, placing it at the given position
/// with full HP, Defense, and MP restored. isLeader=true for ArchSpirits.
///
private static FieldCard ToFieldCard(CardInstance source, Coord position, bool isLeader = false)
=> new()
{
InstanceId = source.InstanceId,
CardDefinitionId = source.CardDefinitionId,
Name = source.Name,
CardType = source.CardType,
Affinity = source.Affinity,
Rarity = source.Rarity,
SpCost = source.SpCost,
StCost = source.StCost,
MaxHealth = source.MaxHealth,
CurrentHealth = source.MaxHealth,
MaxDefense = source.MaxDefense,
CurrentDefense = source.MaxDefense,
Damage = source.Damage,
CanAttack = source.CanAttack,
CanDefend = source.CanDefend,
CanMove = source.CanMove,
MovementType = source.MovementType,
MaxMp = source.MaxMp,
CurrentMp = source.MaxMp ?? 0,
MinAttackRange = source.MinAttackRange,
MaxAttackRange = source.MaxAttackRange,
RequiresLos = source.RequiresLos,
MinChannelRange = source.MinChannelRange,
MaxChannelRange = source.MaxChannelRange,
IsLeader = isLeader,
IsExhausted = false,
Tier = source.Tier,
PreviousTierId = source.PreviousTierId,
TerramorphaMode = source.TerramorphaMode,
AbilitiesJson = source.AbilitiesJson,
EffectsJson = source.EffectsJson,
Genus = source.Genus?.ToList(),
Position = position,
};
/// Search hand → deck → discard for a card by instance ID.
private static CardInstance? FindInAnyZone(PlayerState player, string instanceId)
=> player.Hand.FirstOrDefault(c => c.InstanceId == instanceId)
?? player.Deck.FirstOrDefault(c => c.InstanceId == instanceId)
?? (CardInstance?)player.Discard.FirstOrDefault(c => c.InstanceId == instanceId);
/// Remove a card from whichever zone holds it (hand, deck, or discard).
private static void RemoveFromAnyZone(PlayerState player, CardInstance card)
{
if (!player.Hand.Remove(card))
if (!player.Deck.Remove(card))
player.Discard.Remove(card);
}
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)
{
var fc = c as FieldCard;
return 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.IsLeader,
Position : fc?.Position.HasValue == true
? new CoordDto(fc.Position.Value.X, fc.Position.Value.Y) : null,
CurrentMp : fc?.CurrentMp,
MaxMp : c.MaxMp,
MovementType : c.MovementType?.ToString(),
Tier : c.Tier,
TerramorphaMode : c.TerramorphaMode?.ToString(),
SpCost : c.SpCost,
StCost : c.StCost,
Genus : c.Genus,
MinChannelRange : c.MinChannelRange,
MaxChannelRange : c.MaxChannelRange,
MinAttackRange : c.MinAttackRange,
MaxAttackRange : c.MaxAttackRange,
CanMove : c.CanMove,
CanAttack : c.CanAttack,
ExtraAttacksRemaining : c.ExtraAttacksRemaining,
CanBeAttacked : c.CanBeAttacked,
AbilitiesJson : c.AbilitiesJson,
EffectsJson : c.EffectsJson);
}
private static BoardDto ToBoardDto(Board board)
{
var tiles = board.Tiles.Values.Select(t => new TileDto(
Coord : new CoordDto(t.Coord.X, t.Coord.Y),
Base1 : t.Base1.ToString(),
Base2 : t.Base2.ToString(),
ResolvedAffinity : AffinitySystem.Resolve(t.Base1, t.Base2).ToString(),
OccupantId : t.OccupantId,
OccupantOwner : t.OccupantOwner,
RuinId : t.RuinId,
RuinOwner : t.RuinOwner));
return new BoardDto(board.Width, board.Height, tiles);
}
}
/// 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;
}