From b46f4e9157e44d578dd2a9ca0fde306a5ca7d5ad Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 26 Feb 2026 12:45:23 -0500 Subject: [PATCH] Add Ascend, Transition, and Terramorpha implementations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CardInstance: add Tier, PreviousTierId (ascension chain), TerramorphaMode - GameEngine.Ascend (§6.7.2): any-zone search, tier+lineage validation, full HP/Def/MP on entry - GameEngine.Transition (§6.7.1): hand-only, Tier 1 guard, full HP/Def/MP on entry - GameEngine.ChannelCard: Terramorpha path (Mono/Di/Tri tile count + adjacency + affinity push); non-Spirit, non-Terramorpha cards now correctly go to Discard instead of Field - GamePlayCardRequest: add TargetTiles for multi-tile Terramorpha; handler routes accordingly - CardInstanceDto: expose Tier and TerramorphaMode to clients - New handlers: game.ascend, game.transition Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Server/src/SOR.Game/GameEngine.cs | 277 +++++++++++++++--- Server/src/SOR.Game/GameMessages.cs | 39 ++- Server/src/SOR.Game/GameState.cs | 22 ++ .../SOR.Game/Handlers/GameAscendHandler.cs | 56 ++++ .../SOR.Game/Handlers/GamePlayCardHandler.cs | 18 +- .../Handlers/GameTransitionHandler.cs | 56 ++++ Server/src/SOR.Game/ServiceRegistration.cs | 2 + 7 files changed, 412 insertions(+), 58 deletions(-) create mode 100644 Server/src/SOR.Game/Handlers/GameAscendHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameTransitionHandler.cs diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index fed3ed7..ae05856 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -172,14 +172,18 @@ public static class GameEngine /// /// Channel (play) a card from hand. /// - /// Spirit cards require a TargetTile within the ArchSpirit's channeling range - /// and valid affinity on the target tile. They are placed on the board at that tile. + /// Spirit: targetTiles must have exactly 1 entry — a tile within the ArchSpirit's + /// channeling range with valid affinity. The Spirit is placed there. /// - /// Other card types (Repentance, Instinct, Ruin, Terramorpha) do not require a tile - /// in this initial implementation — effect resolution is handled by AbilitySystem (future). + /// 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. + /// + /// Repentance / Instinct / Ruin: targetTiles may be null. The card goes to Discard after + /// cost payment — full effect resolution is deferred to AbilitySystem (future). /// public static GameState ChannelCard( - GameState state, string actorId, string cardInstanceId, Coord? targetTile) + GameState state, string actorId, string cardInstanceId, IReadOnlyList? targetTiles) { ValidateActivePlayer(state, actorId); ValidatePhase(state, GamePhase.Main); @@ -195,10 +199,11 @@ public static class GameEngine if (card.CardType == "Spirit") { - if (!targetTile.HasValue) throw new GameException("TARGET_TILE_REQUIRED"); + if (targetTiles is null || targetTiles.Count == 0) + throw new GameException("TARGET_TILE_REQUIRED"); - var tile = board.GetTile(targetTile.Value) - ?? throw new GameException("TILE_OUT_OF_BOUNDS"); + 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. @@ -207,7 +212,7 @@ public static class GameEngine var minRange = card.MinChannelRange ?? 1; var maxRange = card.MaxChannelRange ?? 1; - var dist = archSpirit.Position.Value.ManhattanDistance(targetTile.Value); + var dist = archSpirit.Position.Value.ManhattanDistance(coord); if (dist < minRange || dist > maxRange) throw new GameException("OUT_OF_CHANNEL_RANGE"); @@ -217,47 +222,167 @@ public static class GameEngine 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); + } + 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); + } + else + { + // Repentance, Instinct, Ruin — pay cost and discard. + // Full effect resolution deferred to AbilitySystem (future). + player.Hand.Remove(card); + player.CurrentSp -= card.SpCost; + player.CurrentSt -= card.StCost; + player.Discard.Add(card); } - player.Hand.Remove(card); - player.CurrentSp -= card.SpCost; - player.CurrentSt -= card.StCost; + return state; + } - 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, - CanMove = card.CanMove, - MovementType = card.MovementType, - MaxMp = card.MaxMp, - CurrentMp = card.MaxMp ?? 0, - MinAttackRange = card.MinAttackRange, - MaxAttackRange = card.MaxAttackRange, - RequiresLos = card.RequiresLos, - MinChannelRange = card.MinChannelRange, - MaxChannelRange = card.MaxChannelRange, - IsLeader = false, - IsExhausted = false, - Position = targetTile, - }; + /// + /// 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); - player.Field.Add(field); + 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"); - if (targetTile.HasValue) - board.PlaceUnit(targetTile.Value, field.InstanceId, actorId); + // 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); + + 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"); + + // 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; move to discard. + board.RemoveUnit(current.InstanceId); + player.Discard.Add(current); + + // Seat the new ArchSpirit. + player.ArchSpirit = newArchSpirit; + board.PlaceUnit(coord, newArchSpirit.InstanceId, actorId); return state; } @@ -596,6 +721,8 @@ public static class GameEngine IsLeader = true, IsExhausted = false, Position = null, + Tier = archSpiritDef.Tier, + PreviousTierId = archSpiritDef.PreviousTierId, }; ps.CurrentSp = 0; @@ -630,6 +757,9 @@ public static class GameEngine RequiresLos = def.RequiresLos ?? false, MinChannelRange = def.MinChannelRange, MaxChannelRange = def.MaxChannelRange, + Tier = def.Tier, + PreviousTierId = def.PreviousTierId, + TerramorphaMode = def.TerramorphaMode, }; private static void DrawCards(PlayerState player, int count) @@ -702,6 +832,59 @@ public static class GameEngine 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, + 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) @@ -735,7 +918,9 @@ public static class GameEngine ? new CoordDto(fc.Position.Value.X, fc.Position.Value.Y) : null, CurrentMp : fc?.CurrentMp, MaxMp : c.MaxMp, - MovementType : c.MovementType?.ToString()); + MovementType : c.MovementType?.ToString(), + Tier : c.Tier, + TerramorphaMode : c.TerramorphaMode?.ToString()); } private static BoardDto ToBoardDto(Board board) diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index ef13753..566d22c 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -18,10 +18,17 @@ public sealed record GameDrawRequest(Guid SessionId); public sealed record GamePlaceArchSpiritRequest(Guid SessionId, CoordDto Position); /// -/// Channel (play) a card from hand. Spirit cards require a TargetTile within -/// the ArchSpirit's channeling range; other card types may omit it. +/// Channel (play) a card from hand. +/// Spirit cards require TargetTile (single tile within ArchSpirit's channeling range). +/// Terramorpha cards require TargetTiles (1 tile for Mono, 2 for Di, 3 for Tri — each +/// subsequent tile must be orthogonally adjacent to the previous). +/// Other card types (Repentance, Instinct, Ruin) may omit both. /// -public sealed record GamePlayCardRequest(Guid SessionId, string CardInstanceId, CoordDto? TargetTile = null); +public sealed record GamePlayCardRequest( + Guid SessionId, + string CardInstanceId, + CoordDto? TargetTile = null, + IReadOnlyList? TargetTiles = null); /// Move a unit on the board to a new tile. public sealed record GameMoveUnitRequest(Guid SessionId, string UnitInstanceId, CoordDto TargetPosition); @@ -44,6 +51,22 @@ public sealed record GameEndTurnRequest(Guid SessionId); /// Concede the game (forfeit). public sealed record GameConcedeRequest(Guid SessionId); +/// +/// Ascend the active player's ArchSpirit to the next tier (§6.7.2). +/// IncomingCardInstanceId is the instance ID of the higher-tier ArchSpirit — it may +/// reside in any zone (hand, deck, discard, or even field in edge cases). +/// The incoming ArchSpirit must be exactly one tier above the current and must link +/// back to it via PreviousTierId. Cost is the incoming ArchSpirit's SP/ST cost. +/// +public sealed record GameAscendRequest(Guid SessionId, string IncomingCardInstanceId); + +/// +/// Transition the active player's ArchSpirit with a Tier 1 ArchSpirit from hand (§6.7.1). +/// The current ArchSpirit goes to discard; the incoming enters with full HP/Defense/MP. +/// Cost is the incoming ArchSpirit's SP/ST cost. +/// +public sealed record GameTransitionRequest(Guid SessionId, string IncomingCardInstanceId); + // ── Custom lobby requests ───────────────────────────────────────────────────── /// Create a new custom lobby. Host provides their deck and optional rule overrides. @@ -98,6 +121,10 @@ public sealed record GameEndTurnResponse(GameStateDto State); public sealed record GameConcedeResponse(GameStateDto State); +public sealed record GameAscendResponse(GameStateDto State); + +public sealed record GameTransitionResponse(GameStateDto State); + // ── Custom lobby responses ───────────────────────────────────────────────────── public sealed record CreateCustomLobbyResponse( @@ -188,10 +215,12 @@ public sealed record CardInstanceDto( int? Damage, bool IsExhausted, bool IsLeader, - CoordDto? Position, // null when not on field or not yet placed + CoordDto? Position, // null when not on field or not yet placed int? CurrentMp, int? MaxMp, - string? MovementType); // enum as string, null for non-unit cards + string? MovementType, // enum as string, null for non-unit cards + int? Tier, // ArchSpirit only; 1 = base form + string? TerramorphaMode); // Terramorpha only: "Mono" | "Di" | "Tri" public sealed record BoardDto( int Width, diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 02a1739..2932ae8 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -129,6 +129,28 @@ public class CardInstance public bool CanAttack { get; set; } public bool CanDefend { get; set; } + + // ── Ascend / Transition ─────────────────────────────────────────────────── + + /// + /// For ArchSpirit cards: tier number (1 = base). Mirrored from CardDefinition + /// to enable ascension chain validation in the engine without a DB round-trip. + /// + public int? Tier { get; set; } + + /// + /// For Tier 2+ ArchSpirits: the CardDefinitionId of the Tier (N-1) predecessor. + /// Null for Tier 1 and all non-ArchSpirit cards. + /// + public Guid? PreviousTierId { get; set; } + + // ── Terramorpha ──────────────────────────────────────────────────────────── + + /// + /// For Terramorpha cards only: how many tiles (and adjacency chain) this card + /// requires when channeled. Mirrored from CardDefinition. + /// + public TerramorphaMode? TerramorphaMode { get; set; } } /// diff --git a/Server/src/SOR.Game/Handlers/GameAscendHandler.cs b/Server/src/SOR.Game/Handlers/GameAscendHandler.cs new file mode 100644 index 0000000..14f60b6 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameAscendHandler.cs @@ -0,0 +1,56 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.ascend — active player upgrades their ArchSpirit by exactly one tier (§6.7.2). +/// +/// The incoming higher-tier ArchSpirit must be the direct next tier in the ascension chain +/// (Tier+1, PreviousTierId == current ArchSpirit's CardDefinitionId). It may come from +/// 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. +/// +internal sealed class GameAscendHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameAscendHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.ascend"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var state = GameEngine.Deserialize(session.StateJson!); + var newState = GameEngine.Ascend(state, actorId, req.IncomingCardInstanceId); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.ascend", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct); + + return ServerMessage.Reply("game.ascend.ack", message.Seq, + new GameAscendResponse(GameEngine.ToDto(newState, actorId))); + } +} diff --git a/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs b/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs index f000c2f..5d69498 100644 --- a/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs +++ b/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs @@ -11,9 +11,9 @@ using SOR.Shared.Networking; /// /// game.play_card — active player channels a card from their hand. /// -/// Spirit cards require a TargetTile within the ArchSpirit's channeling range with -/// valid affinity. Other card types (Repentance, Instinct, Ruin, Terramorpha) may -/// omit TargetTile — full effect resolution is handled by AbilitySystem (future). +/// Spirit: TargetTile required (within ArchSpirit's channeling range, valid affinity). +/// Terramorpha: TargetTiles required (Mono=1, Di=2, Tri=3 tiles; each adjacent to the prior). +/// Repentance / Instinct / Ruin: no tile required; effects deferred to AbilitySystem (future). /// internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler { @@ -41,11 +41,15 @@ internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); var state = GameEngine.Deserialize(session.StateJson!); - Coord? target = req.TargetTile is not null - ? new Coord(req.TargetTile.X, req.TargetTile.Y) - : null; + // Build the coordinate list for the engine. + // TargetTiles (multi-tile) takes priority; fall back to TargetTile (single-tile). + IReadOnlyList? targets = null; + if (req.TargetTiles is { Count: > 0 }) + targets = req.TargetTiles.Select(t => new Coord(t.X, t.Y)).ToList(); + else if (req.TargetTile is not null) + targets = new[] { new Coord(req.TargetTile.X, req.TargetTile.Y) }; - var newState = GameEngine.ChannelCard(state, actorId, req.CardInstanceId, target); + var newState = GameEngine.ChannelCard(state, actorId, req.CardInstanceId, targets); await SaveStateAsync(_gameDb, session, newState, actorId, "game.play_card", JsonSerializer.Serialize(req), ct); diff --git a/Server/src/SOR.Game/Handlers/GameTransitionHandler.cs b/Server/src/SOR.Game/Handlers/GameTransitionHandler.cs new file mode 100644 index 0000000..446d343 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameTransitionHandler.cs @@ -0,0 +1,56 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.transition — active player swaps their ArchSpirit with a Tier 1 ArchSpirit +/// from hand (§6.7.1). +/// +/// The outgoing ArchSpirit goes to discard; the incoming enters at the same board +/// position with full HP, Defense, and MP. Cost is the incoming ArchSpirit's SP/ST cost. +/// The incoming ArchSpirit may move, attack, and use abilities the turn it enters. +/// +internal sealed class GameTransitionHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameTransitionHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.transition"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var state = GameEngine.Deserialize(session.StateJson!); + var newState = GameEngine.Transition(state, actorId, req.IncomingCardInstanceId); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.transition", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct); + + return ServerMessage.Reply("game.transition.ack", message.Seq, + new GameTransitionResponse(GameEngine.ToDto(newState, actorId))); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 61a2411..e2af6dd 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -29,6 +29,8 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient();