Engine corrections (per gameplay.md + user spec): - Opening draw: both players draw 6 cards at game start - P1 skips Draw phase on turn 1 (already has opening hand); P2 draws once at start of their first turn → 7 cards total - SP: starts at 0, accumulates +3/turn (never resets, no cap by default) - ST: starts at 0, earned only through sacrifice (no per-turn grant) - No entry sickness: units can attack/move/ability the turn they are summoned - Defense restores to MaxDefense at start of each turn (§6.9.3) - Rename Graveyard → Discard throughout (GameState, GameEngine, GameMessages) - Remove IsEntrySick flag from CardInstance and CardInstanceDto GameRuleSet / CustomLobby infrastructure: - GameRuleSet DB entity: admin-configurable rules (IsRankedDefault, IsCustomDefault) - GameRules record (SOR.Game): in-memory config embedded in GameState.Rules - GameSession.RuleSnapshotJson: immutable per-session rule snapshot (jsonb) - MatchmakerService: loads ranked ruleset and snapshots it into each GameSession - GameReadyHandler: deserializes rule snapshot and passes rules to GameEngine.Initialize - CustomLobby DB entity: host+guest, rule overrides, GameSessionId link - CustomLobbyStatus enum: Open / Full / Started / Cancelled Custom game handlers (4): - game.custom.create — host creates lobby with optional rule overrides - game.custom.join — guest joins; when full, creates GameSession + pushes both players - game.custom.leave — host cancels or guest leaves - game.custom.list — paged list of Open lobbies Admin portal: - /game/ranked-rules — edit the ranked play ruleset (auto-seeds default on first visit) - /game/custom-lobbies — read-only view of active and recent custom lobbies - NavMenu: added Ranked Rules + Custom Lobbies links under Game Migration: AddGameRulesAndCustomLobby (game_rule_sets, custom_lobbies, rule_snapshot column on game_sessions) 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>
469 lines
18 KiB
C#
469 lines
18 KiB
C#
namespace SOR.Game;
|
|
|
|
using System.Text.Json;
|
|
using SOR.Database.Entities.Catalog;
|
|
using SOR.Database.Enums;
|
|
|
|
/// <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.
|
|
///
|
|
/// Rules applied (per gameplay.md + user spec):
|
|
/// - Opening hand: all players draw OpeningHandSize cards at game start.
|
|
/// - P1 skips the Draw phase on turn 1 (FirstPlayerSkipsDraw).
|
|
/// P2 draws 1 at the start of their turn → 7 cards total by their first turn.
|
|
/// - SP: starts at 0, accumulates SpAccumulationPerTurn per turn. Never resets.
|
|
/// - ST: starts at 0, earned only through sacrifice — never granted per turn.
|
|
/// - No entry sickness: units can attack/move/ability the turn they are summoned.
|
|
/// - Defense restores to MaxDefense at the start of each turn (§6.9.3).
|
|
/// - Win condition: ArchSpirit destruction.
|
|
/// </summary>
|
|
public static class GameEngine
|
|
{
|
|
private static readonly JsonSerializerOptions _json =
|
|
new(JsonSerializerDefaults.Web) { WriteIndented = false };
|
|
|
|
// ── Serialization ─────────────────────────────────────────────────────────
|
|
|
|
public static GameState Deserialize(string json)
|
|
=> JsonSerializer.Deserialize<GameState>(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<GameRules>(json, _json)
|
|
?? GameRules.Default;
|
|
|
|
// ── 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.
|
|
///
|
|
/// 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).
|
|
/// </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,
|
|
GameRules? rules = null)
|
|
{
|
|
rules ??= GameRules.Default;
|
|
|
|
var state = new GameState
|
|
{
|
|
SessionId = sessionId,
|
|
TurnNumber = 1,
|
|
ActivePlayerAccountId = p1AccountId.ToString(),
|
|
Rules = rules,
|
|
};
|
|
|
|
state.Players[p1AccountId.ToString()] = BuildPlayerState(p1AccountId, p1Deck, p1ArchSpirit);
|
|
state.Players[p2AccountId.ToString()] = BuildPlayerState(p2AccountId, p2Deck, p2ArchSpirit);
|
|
|
|
// Both players draw their opening hand.
|
|
DrawCards(state.Players[p1AccountId.ToString()], rules.OpeningHandSize);
|
|
DrawCards(state.Players[p2AccountId.ToString()], rules.OpeningHandSize);
|
|
|
|
// P1's first turn: skip Draw phase (they drew their opening hand already).
|
|
// P2's first turn will begin at Draw phase — they draw 1 more card there.
|
|
state.Phase = rules.FirstPlayerSkipsDraw ? GamePhase.Main : GamePhase.Draw;
|
|
|
|
return state;
|
|
}
|
|
|
|
// ── Actions ───────────────────────────────────────────────────────────────
|
|
|
|
/// <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).
|
|
/// </summary>
|
|
public static (GameState state, CardInstance? drawn) Draw(GameState state, string actorId)
|
|
{
|
|
ValidateActivePlayer(state, actorId);
|
|
ValidatePhase(state, GamePhase.Draw, GamePhase.Main);
|
|
|
|
var player = state.Players[actorId];
|
|
if (player.Deck.Count == 0)
|
|
return (state, null);
|
|
|
|
var card = player.Deck[0];
|
|
player.Deck.RemoveAt(0);
|
|
player.Hand.Add(card);
|
|
|
|
if (state.Phase == GamePhase.Draw)
|
|
state.Phase = GamePhase.Main;
|
|
|
|
return (state, card);
|
|
}
|
|
|
|
/// <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).
|
|
/// </summary>
|
|
public static GameState PlayCard(GameState state, string actorId, string cardInstanceId)
|
|
{
|
|
ValidateActivePlayer(state, actorId);
|
|
ValidatePhase(state, GamePhase.Main);
|
|
|
|
var player = state.Players[actorId];
|
|
var card = player.Hand.FirstOrDefault(c => c.InstanceId == cardInstanceId)
|
|
?? throw new GameException("CARD_NOT_IN_HAND");
|
|
|
|
if (player.CurrentSp < card.SpCost)
|
|
throw new GameException("INSUFFICIENT_SP");
|
|
if (player.CurrentSt < card.StCost)
|
|
throw new GameException("INSUFFICIENT_ST");
|
|
|
|
player.Hand.Remove(card);
|
|
player.CurrentSp -= card.SpCost;
|
|
player.CurrentSt -= card.StCost;
|
|
|
|
var field = new FieldCard
|
|
{
|
|
InstanceId = card.InstanceId,
|
|
CardDefinitionId = card.CardDefinitionId,
|
|
Name = card.Name,
|
|
CardType = card.CardType,
|
|
Affinity = card.Affinity,
|
|
Rarity = card.Rarity,
|
|
SpCost = card.SpCost,
|
|
StCost = card.StCost,
|
|
MaxHealth = card.MaxHealth,
|
|
CurrentHealth = card.MaxHealth,
|
|
MaxDefense = card.MaxDefense,
|
|
CurrentDefense = card.MaxDefense,
|
|
Damage = card.Damage,
|
|
CanAttack = card.CanAttack,
|
|
CanDefend = card.CanDefend,
|
|
IsExhausted = false,
|
|
IsLeader = false,
|
|
};
|
|
|
|
player.Field.Add(field);
|
|
|
|
return state;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Declare an attack from one of the active player's field cards against an
|
|
/// opponent's field card (or their ArchSpirit).
|
|
///
|
|
/// Combat: attacker damage hits defender's defense first; overflow hits health.
|
|
/// Defender counter-attacks (damage hits attacker's health directly if no defense).
|
|
/// Destroyed units move to the Discard pile.
|
|
/// If the defending ArchSpirit is destroyed the game ends.
|
|
/// </summary>
|
|
public static (GameState state, bool gameOver) Attack(
|
|
GameState state,
|
|
string actorId,
|
|
string attackerInstanceId,
|
|
string targetInstanceId)
|
|
{
|
|
ValidateActivePlayer(state, actorId);
|
|
ValidatePhase(state, GamePhase.Main);
|
|
|
|
var opponentId = GetOpponentId(state, actorId);
|
|
var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
|
|
var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
|
|
|
|
if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
|
|
if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK");
|
|
|
|
// Attacker hits target.
|
|
ApplyDamage(target, attacker.Damage ?? 0);
|
|
|
|
// Target counter-attacks if able (and still alive).
|
|
if (target.CurrentHealth > 0 && target.CanAttack && !target.IsExhausted)
|
|
ApplyDamage(attacker, target.Damage ?? 0);
|
|
|
|
attacker.IsExhausted = true;
|
|
|
|
// Clean up destroyed cards.
|
|
bool gameOver = false;
|
|
var activePlayer = state.Players[actorId];
|
|
var opponentPlayer = state.Players[opponentId];
|
|
|
|
if (attacker.CurrentHealth <= 0)
|
|
MoveToDiscard(activePlayer, attacker);
|
|
|
|
if (target.CurrentHealth <= 0)
|
|
{
|
|
if (target.IsLeader)
|
|
{
|
|
// ArchSpirit destroyed — game over.
|
|
state.Phase = GamePhase.GameOver;
|
|
gameOver = true;
|
|
}
|
|
else
|
|
{
|
|
MoveToDiscard(opponentPlayer, target);
|
|
}
|
|
}
|
|
|
|
return (state, gameOver);
|
|
}
|
|
|
|
/// <summary>
|
|
/// End the active player's turn.
|
|
/// - Resets IsExhausted on all active player field cards.
|
|
/// - Restores CurrentDefense to MaxDefense for all active player field cards (§6.9.3).
|
|
/// - Switches the active player.
|
|
/// - Accumulates SP for the next player (+SpAccumulationPerTurn; never resets).
|
|
/// - Sets phase to Draw for the next player's turn.
|
|
/// </summary>
|
|
public static GameState EndTurn(GameState state, string actorId)
|
|
{
|
|
ValidateActivePlayer(state, actorId);
|
|
ValidatePhase(state, GamePhase.Main);
|
|
|
|
// Refresh active player's field cards at end of their turn.
|
|
var active = state.Players[actorId];
|
|
foreach (var card in active.Field)
|
|
{
|
|
card.IsExhausted = false;
|
|
if (card.MaxDefense.HasValue)
|
|
card.CurrentDefense = card.MaxDefense;
|
|
}
|
|
if (active.ArchSpirit is not null)
|
|
{
|
|
active.ArchSpirit.IsExhausted = false;
|
|
if (active.ArchSpirit.MaxDefense.HasValue)
|
|
active.ArchSpirit.CurrentDefense = active.ArchSpirit.MaxDefense;
|
|
}
|
|
|
|
// Switch active player.
|
|
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
|
|
|
|
// Next player's turn: advance counter, accumulate SP.
|
|
var next = state.Players[state.ActivePlayerAccountId];
|
|
var rules = state.Rules;
|
|
|
|
state.TurnNumber++;
|
|
|
|
// SP accumulates — never resets between turns.
|
|
next.CurrentSp += rules.SpAccumulationPerTurn;
|
|
if (rules.SpHasCap && next.CurrentSp > rules.SpCap)
|
|
next.CurrentSp = rules.SpCap;
|
|
|
|
state.Phase = GamePhase.Draw;
|
|
|
|
return state;
|
|
}
|
|
|
|
/// <summary>Mark the game as over with the conceding player as the loser.</summary>
|
|
public static GameState Concede(GameState state, string actorId)
|
|
{
|
|
state.Phase = GamePhase.GameOver;
|
|
return state;
|
|
}
|
|
|
|
// ── DTO projection ────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Build a client-safe GameStateDto for a specific player's perspective.
|
|
/// Opponent's hand is hidden (null); only the count is shown.
|
|
/// </summary>
|
|
public static GameStateDto ToDto(GameState state, string viewerAccountId)
|
|
{
|
|
var players = state.Players.Values.Select(p =>
|
|
{
|
|
var isSelf = p.AccountId == viewerAccountId;
|
|
|
|
return new PlayerStateDto(
|
|
AccountId : Guid.Parse(p.AccountId),
|
|
HandCount : p.Hand.Count,
|
|
DeckCount : p.Deck.Count,
|
|
Hand : isSelf ? p.Hand.Select(ToCardDto) : null,
|
|
Field : p.Field.Select(ToCardDto),
|
|
Discard : p.Discard.Select(ToCardDto),
|
|
ArchSpirit : p.ArchSpirit != null ? ToCardDto(p.ArchSpirit) : null,
|
|
CurrentSp : p.CurrentSp,
|
|
CurrentSt : p.CurrentSt);
|
|
});
|
|
|
|
return new GameStateDto(
|
|
SessionId : state.SessionId,
|
|
Phase : state.Phase.ToString(),
|
|
ActivePlayerAccountId : state.ActivePlayerAccountId,
|
|
TurnNumber : state.TurnNumber,
|
|
Players : players);
|
|
}
|
|
|
|
// ── ELO ──────────────────────────────────────────────────────────────────
|
|
|
|
/// <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;
|
|
var expected = 1.0 / (1.0 + Math.Pow(10, (loserScore - winnerScore) / 400.0));
|
|
var winnerDelta = (int)Math.Round(K * (1.0 - expected));
|
|
var loserDelta = (int)Math.Round(K * expected);
|
|
return (Math.Max(1, winnerDelta), Math.Max(1, loserDelta));
|
|
}
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
|
|
private static PlayerState BuildPlayerState(
|
|
Guid accountId,
|
|
IEnumerable<(CardDefinition def, int qty)> deckCards,
|
|
CardDefinition archSpiritDef)
|
|
{
|
|
var ps = new PlayerState { AccountId = accountId.ToString() };
|
|
|
|
// Build deck pile (expand by quantity).
|
|
var pile = new List<CardInstance>();
|
|
foreach (var (def, qty) in deckCards)
|
|
{
|
|
for (int i = 0; i < qty; i++)
|
|
pile.Add(DefinitionToInstance(def));
|
|
}
|
|
|
|
// Shuffle.
|
|
var rng = new Random();
|
|
for (int i = pile.Count - 1; i > 0; i--)
|
|
{
|
|
int j = rng.Next(i + 1);
|
|
(pile[i], pile[j]) = (pile[j], pile[i]);
|
|
}
|
|
ps.Deck = pile;
|
|
|
|
// ArchSpirit starts on the field as the leader.
|
|
ps.ArchSpirit = new FieldCard
|
|
{
|
|
InstanceId = $"arch_{accountId:N}"[..8],
|
|
CardDefinitionId = archSpiritDef.Id,
|
|
Name = archSpiritDef.Name,
|
|
CardType = archSpiritDef.CardType.ToString(),
|
|
Affinity = archSpiritDef.Affinity.ToString(),
|
|
Rarity = archSpiritDef.Rarity.ToString(),
|
|
MaxHealth = archSpiritDef.MaxHealth,
|
|
CurrentHealth = archSpiritDef.MaxHealth,
|
|
MaxDefense = archSpiritDef.MaxDefense,
|
|
CurrentDefense = archSpiritDef.MaxDefense,
|
|
Damage = archSpiritDef.Damage,
|
|
CanAttack = archSpiritDef.CanAttack ?? false,
|
|
CanDefend = archSpiritDef.CanDefend ?? false,
|
|
IsLeader = true,
|
|
};
|
|
|
|
// SP and ST start at 0 for all players.
|
|
ps.CurrentSp = 0;
|
|
ps.CurrentSt = 0;
|
|
|
|
return ps;
|
|
}
|
|
|
|
private static CardInstance DefinitionToInstance(CardDefinition def)
|
|
=> new()
|
|
{
|
|
InstanceId = Guid.NewGuid().ToString("N")[..8],
|
|
CardDefinitionId = def.Id,
|
|
Name = def.Name,
|
|
CardType = def.CardType.ToString(),
|
|
Affinity = def.Affinity.ToString(),
|
|
Rarity = def.Rarity.ToString(),
|
|
SpCost = def.SpCost,
|
|
StCost = def.StCost,
|
|
MaxHealth = def.MaxHealth,
|
|
CurrentHealth = def.MaxHealth,
|
|
MaxDefense = def.MaxDefense,
|
|
CurrentDefense = def.MaxDefense,
|
|
Damage = def.Damage,
|
|
CanAttack = def.CanAttack ?? false,
|
|
CanDefend = def.CanDefend ?? false,
|
|
};
|
|
|
|
private static void DrawCards(PlayerState player, int count)
|
|
{
|
|
for (int i = 0; i < count && player.Deck.Count > 0; i++)
|
|
{
|
|
var card = player.Deck[0];
|
|
player.Deck.RemoveAt(0);
|
|
player.Hand.Add(card);
|
|
}
|
|
}
|
|
|
|
private static void ApplyDamage(CardInstance target, int damage)
|
|
{
|
|
if (target.CurrentDefense > 0)
|
|
{
|
|
var defVal = target.CurrentDefense.GetValueOrDefault();
|
|
var overflow = damage - defVal;
|
|
target.CurrentDefense = Math.Max(0, defVal - damage);
|
|
if (overflow > 0 && target.CurrentHealth.HasValue)
|
|
target.CurrentHealth = Math.Max(0, target.CurrentHealth.Value - overflow);
|
|
}
|
|
else if (target.CurrentHealth.HasValue)
|
|
{
|
|
target.CurrentHealth = Math.Max(0, target.CurrentHealth.Value - damage);
|
|
}
|
|
}
|
|
|
|
private static void MoveToDiscard(PlayerState player, FieldCard card)
|
|
{
|
|
player.Field.Remove(card);
|
|
player.Discard.Add(card);
|
|
}
|
|
|
|
private static FieldCard GetFieldCard(PlayerState player, string instanceId)
|
|
{
|
|
var field = player.Field.OfType<FieldCard>().FirstOrDefault(c => c.InstanceId == instanceId);
|
|
if (field != null) return field;
|
|
|
|
if (player.ArchSpirit?.InstanceId == instanceId)
|
|
return player.ArchSpirit;
|
|
|
|
throw new GameException("CARD_NOT_ON_FIELD");
|
|
}
|
|
|
|
private static string GetOpponentId(GameState state, string actorId)
|
|
=> state.Players.Keys.First(k => k != actorId);
|
|
|
|
private static void ValidateActivePlayer(GameState state, string actorId)
|
|
{
|
|
if (state.ActivePlayerAccountId != actorId)
|
|
throw new GameException("NOT_YOUR_TURN");
|
|
}
|
|
|
|
private static void ValidatePhase(GameState state, params GamePhase[] allowed)
|
|
{
|
|
if (!allowed.Contains(state.Phase))
|
|
throw new GameException($"INVALID_PHASE:{state.Phase}");
|
|
}
|
|
|
|
private static CardInstanceDto ToCardDto(CardInstance c)
|
|
=> new(
|
|
InstanceId : c.InstanceId,
|
|
CardDefinitionId : c.CardDefinitionId,
|
|
Name : c.Name,
|
|
CardType : c.CardType,
|
|
Affinity : c.Affinity,
|
|
Rarity : c.Rarity,
|
|
CurrentHealth : c.CurrentHealth,
|
|
MaxHealth : c.MaxHealth,
|
|
CurrentDefense : c.CurrentDefense,
|
|
MaxDefense : c.MaxDefense,
|
|
Damage : c.Damage,
|
|
IsExhausted : c.IsExhausted,
|
|
IsLeader : c is FieldCard fc && fc.IsLeader);
|
|
}
|
|
|
|
/// <summary>Game-rule violation — maps to a client error code.</summary>
|
|
public sealed class GameException : Exception
|
|
{
|
|
public string ErrorCode { get; }
|
|
public GameException(string code) : base(code) => ErrorCode = code;
|
|
}
|