Add square grid system, positional combat, sacrifice, and Placement phase
Grid infrastructure (SOR.Game/Grid/): - Coord — immutable (X,Y) struct with Manhattan distance, adjacency, BFS helpers - Tile — mutable affinity slots (Base1/Base2) + occupancy tracking - Board — 8×8 (configurable) grid, PlaceUnit/RemoveUnit/MoveUnit/BuildOccupancyMap - Pathfinding — Walk/Flight BFS (GetReachableWithCost), Jump/Teleport range (GetJumpRange) - LineOfSight — supercover DDA; occupied intermediate tiles block LOS - AffinitySystem — full Resolve table for all 20+ affinities per affinity.md, PushAffinity, ApplyPlacementAffinity, IsAffinityValid (basic vs non-basic rules) Combat (SOR.Game/Combat/): - AttackSystem — Manhattan range + optional LOS validation (§6.10) - SacrificeSystem — exact ST return formula from gameplay.md §6.15 Abilities (SOR.Game/Abilities/): - AbilitySystem stub — future pass per abilities.md Game engine / state changes: - GamePhase: added Placement phase (before Draw) - GameRuleSet + GameRules: added BoardWidth/BoardHeight (default 8×8) - GameState: added Board, PlayerOneAccountId; CardInstance gains MovementType, MaxMp, MinAttackRange, MaxAttackRange, RequiresLos, MinChannelRange, MaxChannelRange, IsLeader (moved from FieldCard); FieldCard adds Position + CurrentMp - [JsonPolymorphic] on CardInstance so FieldCard survives JSONB round-trip - JsonStringEnumConverter added to GameEngine serializer options - GameEngine.Initialize: creates Board + sets Placement phase; no opening draw yet - GameEngine.PlaceArchSpirit: validates row, pushes affinity, triggers opening draw and SP gain when both players placed - GameEngine.ChannelCard (was PlayCard): validates channeling range + affinity for Spirits - GameEngine.MoveUnit: Walk/Flight BFS, Jump (1 MP/landing), Teleport (LOS + 1 MP) - GameEngine.Attack: adds range+LOS validation via AttackSystem - GameEngine.Sacrifice: adjacency + SacrificeSystem ST formula - GameEngine.EndTurn: now also restores MP (§6.0 step 1) for next player - ToDto: includes Board tiles with resolved affinities; CardInstanceDto gets Position, CurrentMp, MaxMp, MovementType New handlers: game.place_arch_spirit, game.move_unit, game.sacrifice Updated handlers: game.play_card (target tile), GameReadyHandler (new Initialize sig) Migration: AddBoardDimensions (board_width/board_height on game_rule_sets) Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -1,29 +1,40 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using SOR.Database.Entities.Catalog;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Game.Combat;
|
||||
using SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// 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: all players draw OpeningHandSize cards at game start.
|
||||
/// - Opening hand: both players draw OpeningHandSize cards after placement.
|
||||
/// - 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).
|
||||
/// - 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.
|
||||
/// </summary>
|
||||
public static class GameEngine
|
||||
{
|
||||
private static readonly JsonSerializerOptions _json =
|
||||
new(JsonSerializerDefaults.Web) { WriteIndented = false };
|
||||
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = false,
|
||||
Converters = { new JsonStringEnumConverter() },
|
||||
};
|
||||
|
||||
// ── Serialization ─────────────────────────────────────────────────────────
|
||||
// ── Serialization ──────────────────────────────────────────────────────────
|
||||
|
||||
public static GameState Deserialize(string json)
|
||||
=> JsonSerializer.Deserialize<GameState>(json, _json)
|
||||
@@ -36,23 +47,21 @@ public static class GameEngine
|
||||
=> JsonSerializer.Deserialize<GameRules>(json, _json)
|
||||
?? GameRules.Default;
|
||||
|
||||
// ── Initialization ────────────────────────────────────────────────────────
|
||||
// ── Initialization ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// The game starts in the Placement phase — both players must call PlaceArchSpirit
|
||||
/// before the opening draw happens and turn 1 begins.
|
||||
///
|
||||
/// 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).
|
||||
/// Decks are shuffled. ArchSpirits are created but NOT yet placed on the board
|
||||
/// (Position = null until PlaceArchSpirit is called).
|
||||
/// </summary>
|
||||
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,
|
||||
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;
|
||||
@@ -62,28 +71,84 @@ public static class GameEngine
|
||||
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);
|
||||
|
||||
// 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 ───────────────────────────────────────────────────────────────
|
||||
// ── Actions ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<Affinity>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draw the top card from the active player's deck into hand.
|
||||
/// Returns null if the deck is empty (no mill — just no draw).
|
||||
/// Returns null if the deck is empty (no mill).
|
||||
/// </summary>
|
||||
public static (GameState state, CardInstance? drawn) Draw(GameState state, string actorId)
|
||||
{
|
||||
@@ -105,11 +170,16 @@ public static class GameEngine
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// 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.
|
||||
///
|
||||
/// Other card types (Repentance, Instinct, Ruin, Terramorpha) do not require a tile
|
||||
/// in this initial implementation — effect resolution is handled by AbilitySystem (future).
|
||||
/// </summary>
|
||||
public static GameState PlayCard(GameState state, string actorId, string cardInstanceId)
|
||||
public static GameState ChannelCard(
|
||||
GameState state, string actorId, string cardInstanceId, Coord? targetTile)
|
||||
{
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
@@ -118,10 +188,36 @@ public static class GameEngine
|
||||
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");
|
||||
if (player.CurrentSp < card.SpCost) throw new GameException("INSUFFICIENT_SP");
|
||||
if (player.CurrentSt < card.StCost) throw new GameException("INSUFFICIENT_ST");
|
||||
|
||||
var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
|
||||
|
||||
if (card.CardType == "Spirit")
|
||||
{
|
||||
if (!targetTile.HasValue) throw new GameException("TARGET_TILE_REQUIRED");
|
||||
|
||||
var tile = board.GetTile(targetTile.Value)
|
||||
?? 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(targetTile.Value);
|
||||
if (dist < minRange || dist > maxRange)
|
||||
throw new GameException("OUT_OF_CHANNEL_RANGE");
|
||||
|
||||
// Validate affinity.
|
||||
if (Enum.TryParse<Affinity>(card.Affinity, out var cardAffinity))
|
||||
{
|
||||
if (!AffinitySystem.IsAffinityValid(tile, cardAffinity))
|
||||
throw new GameException("INVALID_AFFINITY");
|
||||
}
|
||||
}
|
||||
|
||||
player.Hand.Remove(card);
|
||||
player.CurrentSp -= card.SpCost;
|
||||
@@ -144,12 +240,90 @@ public static class GameEngine
|
||||
Damage = card.Damage,
|
||||
CanAttack = card.CanAttack,
|
||||
CanDefend = card.CanDefend,
|
||||
IsExhausted = false,
|
||||
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,
|
||||
};
|
||||
|
||||
player.Field.Add(field);
|
||||
|
||||
if (targetTile.HasValue)
|
||||
board.PlaceUnit(targetTile.Value, field.InstanceId, actorId);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -157,9 +331,9 @@ public static class GameEngine
|
||||
/// 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).
|
||||
/// Destroyed units move to the Discard pile.
|
||||
/// If the defending ArchSpirit is destroyed the game ends.
|
||||
/// </summary>
|
||||
public static (GameState state, bool gameOver) Attack(
|
||||
@@ -172,39 +346,55 @@ public static class GameEngine
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
|
||||
var opponentId = GetOpponentId(state, actorId);
|
||||
var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
|
||||
var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
|
||||
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 (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
|
||||
if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK");
|
||||
|
||||
// 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).
|
||||
// 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)
|
||||
{
|
||||
if (state.Board is not null) state.Board.RemoveUnit(attacker.InstanceId);
|
||||
MoveToDiscard(activePlayer, attacker);
|
||||
}
|
||||
|
||||
if (target.CurrentHealth <= 0)
|
||||
{
|
||||
if (target.IsLeader)
|
||||
{
|
||||
// ArchSpirit destroyed — game over.
|
||||
state.Phase = GamePhase.GameOver;
|
||||
gameOver = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (state.Board is not null) state.Board.RemoveUnit(target.InstanceId);
|
||||
MoveToDiscard(opponentPlayer, target);
|
||||
}
|
||||
}
|
||||
@@ -212,52 +402,84 @@ public static class GameEngine
|
||||
return (state, gameOver);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<FieldCard>()
|
||||
.FirstOrDefault(c => c.InstanceId == unitInstanceId)
|
||||
?? throw new GameException("UNIT_NOT_ON_FIELD");
|
||||
|
||||
if (unit.IsLeader) throw new GameException("CANNOT_SACRIFICE_ARCH_SPIRIT");
|
||||
|
||||
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");
|
||||
|
||||
var sacValue = SacrificeSystem.GetSacrificeValue(unit.StCost, unit.SpCost);
|
||||
var stReturn = SacrificeSystem.GetSTReturn(player.CurrentSt, sacValue);
|
||||
player.CurrentSt += stReturn;
|
||||
|
||||
if (state.Board is not null) state.Board.RemoveUnit(unitInstanceId);
|
||||
player.Field.Remove(unit);
|
||||
player.Discard.Add(unit);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// End the active player's turn.
|
||||
///
|
||||
/// Per §6.0 (start-of-turn order):
|
||||
/// 1. MP restore (not yet implemented — no positional grid in v1)
|
||||
/// 2. Defense restoration for the NEXT player's units (§6.9.3)
|
||||
/// 3. SP gain for the next player
|
||||
/// 4. Draw phase
|
||||
/// 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.
|
||||
///
|
||||
/// Note: IsExhausted resets for the ENDING player's units (they finished acting).
|
||||
/// Defense restores for the STARTING player's units (at the top of their turn).
|
||||
/// These apply to different players — restoring defense for the wrong player
|
||||
/// would let the opponent attack into fully-restored defense every single turn.
|
||||
/// IsExhausted resets for the ENDING player's units (they finished acting).
|
||||
/// MP + Defense restore for the STARTING player (at the top of their turn).
|
||||
/// </summary>
|
||||
public static GameState EndTurn(GameState state, string actorId)
|
||||
{
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
|
||||
// End of active player's turn: reset exhausted status only.
|
||||
// Defense does NOT restore here — it restores at start of that player's NEXT turn.
|
||||
// Reset exhausted for the player ending their turn.
|
||||
var active = state.Players[actorId];
|
||||
foreach (var card in active.Field)
|
||||
foreach (var card in active.Field.OfType<FieldCard>())
|
||||
card.IsExhausted = false;
|
||||
if (active.ArchSpirit is not null)
|
||||
active.ArchSpirit.IsExhausted = false;
|
||||
|
||||
// Switch active player.
|
||||
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
|
||||
state.TurnNumber++;
|
||||
|
||||
// Start of next player's turn: restore their defense (§6.9.3), accumulate SP.
|
||||
// Start of next player's turn: restore MP, defense, accumulate SP.
|
||||
var next = state.Players[state.ActivePlayerAccountId];
|
||||
var rules = state.Rules;
|
||||
|
||||
state.TurnNumber++;
|
||||
|
||||
// Defense restores for the player whose turn is starting.
|
||||
foreach (var card in next.Field)
|
||||
foreach (var card in next.Field.OfType<FieldCard>())
|
||||
{
|
||||
if (card.MaxDefense.HasValue)
|
||||
card.CurrentDefense = card.MaxDefense;
|
||||
if (card.MaxMp.HasValue) card.CurrentMp = card.MaxMp.Value;
|
||||
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;
|
||||
if (next.ArchSpirit.MaxDefense.HasValue) next.ArchSpirit.CurrentDefense = next.ArchSpirit.MaxDefense;
|
||||
}
|
||||
if (next.ArchSpirit is not null && next.ArchSpirit.MaxDefense.HasValue)
|
||||
next.ArchSpirit.CurrentDefense = next.ArchSpirit.MaxDefense;
|
||||
|
||||
// SP accumulates — never resets between turns.
|
||||
next.CurrentSp += rules.SpAccumulationPerTurn;
|
||||
if (rules.SpHasCap && next.CurrentSp > rules.SpCap)
|
||||
next.CurrentSp = rules.SpCap;
|
||||
@@ -298,21 +520,20 @@ public static class GameEngine
|
||||
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,
|
||||
TurnNumber : state.TurnNumber,
|
||||
StateVersion : state.NextActionSequence,
|
||||
Players : players);
|
||||
Players : players,
|
||||
Board : boardDto);
|
||||
}
|
||||
|
||||
// ── ELO ──────────────────────────────────────────────────────────────────
|
||||
// ── ELO ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Compute ELO rank score deltas after a game.
|
||||
/// Returns (winnerDelta, loserDelta) — both are positive values indicating change magnitude.
|
||||
/// </summary>
|
||||
public static (int winnerDelta, int loserDelta) ComputeEloDelta(int winnerScore, int loserScore)
|
||||
{
|
||||
const double K = 32.0;
|
||||
@@ -331,7 +552,6 @@ public static class GameEngine
|
||||
{
|
||||
var ps = new PlayerState { AccountId = accountId.ToString() };
|
||||
|
||||
// Build deck pile (expand by quantity).
|
||||
var pile = new List<CardInstance>();
|
||||
foreach (var (def, qty) in deckCards)
|
||||
{
|
||||
@@ -348,7 +568,7 @@ public static class GameEngine
|
||||
}
|
||||
ps.Deck = pile;
|
||||
|
||||
// ArchSpirit starts on the field as the leader.
|
||||
// ArchSpirit: created but not yet placed (Position = null, CurrentMp = 0 until placed).
|
||||
ps.ArchSpirit = new FieldCard
|
||||
{
|
||||
InstanceId = $"arch_{accountId:N}"[..8],
|
||||
@@ -362,12 +582,22 @@ public static class GameEngine
|
||||
MaxDefense = archSpiritDef.MaxDefense,
|
||||
CurrentDefense = archSpiritDef.MaxDefense,
|
||||
Damage = archSpiritDef.Damage,
|
||||
CanAttack = archSpiritDef.CanAttack ?? false,
|
||||
CanDefend = archSpiritDef.CanDefend ?? false,
|
||||
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,
|
||||
};
|
||||
|
||||
// SP and ST start at 0 for all players.
|
||||
ps.CurrentSp = 0;
|
||||
ps.CurrentSt = 0;
|
||||
|
||||
@@ -390,8 +620,16 @@ public static class GameEngine
|
||||
MaxDefense = def.MaxDefense,
|
||||
CurrentDefense = def.MaxDefense,
|
||||
Damage = def.Damage,
|
||||
CanAttack = def.CanAttack ?? false,
|
||||
CanDefend = def.CanDefend ?? false,
|
||||
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,
|
||||
};
|
||||
|
||||
private static void DrawCards(PlayerState player, int count)
|
||||
@@ -440,6 +678,30 @@ public static class GameEngine
|
||||
private static string GetOpponentId(GameState state, string actorId)
|
||||
=> state.Players.Keys.First(k => k != actorId);
|
||||
|
||||
private static HashSet<Coord> BuildBlockedSet(
|
||||
GameState state, string movingUnitId, MovementType? movType)
|
||||
{
|
||||
var blocked = new HashSet<Coord>();
|
||||
foreach (var player in state.Players.Values)
|
||||
{
|
||||
foreach (var card in player.Field.OfType<FieldCard>())
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
private static void ValidateActivePlayer(GameState state, string actorId)
|
||||
{
|
||||
if (state.ActivePlayerAccountId != actorId)
|
||||
@@ -453,7 +715,9 @@ public static class GameEngine
|
||||
}
|
||||
|
||||
private static CardInstanceDto ToCardDto(CardInstance c)
|
||||
=> new(
|
||||
{
|
||||
var fc = c as FieldCard;
|
||||
return new(
|
||||
InstanceId : c.InstanceId,
|
||||
CardDefinitionId : c.CardDefinitionId,
|
||||
Name : c.Name,
|
||||
@@ -466,7 +730,26 @@ public static class GameEngine
|
||||
MaxDefense : c.MaxDefense,
|
||||
Damage : c.Damage,
|
||||
IsExhausted : c.IsExhausted,
|
||||
IsLeader : c is FieldCard fc && fc.IsLeader);
|
||||
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());
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
return new BoardDto(board.Width, board.Height, tiles);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game-rule violation — maps to a client error code.</summary>
|
||||
|
||||
Reference in New Issue
Block a user