Fix gameplay engine rules + add RuleSet/CustomLobby system

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>
This commit is contained in:
dingo
2026-02-26 07:55:32 -05:00
co-authored by Claude Happy
parent 2058a47a92
commit 682a525193
21 changed files with 1399 additions and 96 deletions
+81 -52
View File
@@ -8,8 +8,15 @@ using SOR.Database.Enums;
/// Pure game logic — no database access, no DI. Takes a GameState, mutates it,
/// returns the updated state. Handlers are responsible for loading and saving.
///
/// v1 scope: draw, play, attack, end_turn, concede.
/// No abilities, no ascension, no positional grid.
/// 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
{
@@ -25,34 +32,49 @@ public static class GameEngine
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.
/// Each player's deck is shuffled; both draw 5 opening hand cards.
///
/// 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)
Guid p2AccountId, IEnumerable<(CardDefinition def, int qty)> p2Deck, Guid p2ArchSpiritDefId, CardDefinition p2ArchSpirit,
GameRules? rules = null)
{
rules ??= GameRules.Default;
var state = new GameState
{
SessionId = sessionId,
Phase = GamePhase.Draw,
TurnNumber = 1,
ActivePlayerAccountId = p1AccountId.ToString(),
Rules = rules,
};
state.Players[p1AccountId.ToString()] = BuildPlayerState(p1AccountId, p1Deck, p1ArchSpirit);
state.Players[p2AccountId.ToString()] = BuildPlayerState(p2AccountId, p2Deck, p2ArchSpirit);
// Player 1 draws 5; player 2 draws 4 (goes second — slight advantage compensation).
DrawCards(state.Players[p1AccountId.ToString()], 5);
DrawCards(state.Players[p2AccountId.ToString()], 4);
// Both players draw their opening hand.
DrawCards(state.Players[p1AccountId.ToString()], rules.OpeningHandSize);
DrawCards(state.Players[p2AccountId.ToString()], rules.OpeningHandSize);
state.Phase = GamePhase.Main;
// 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;
}
@@ -84,7 +106,8 @@ public static class GameEngine
/// <summary>
/// Play a card from hand onto the field (non-ArchSpirit cards only).
/// Deducts SP/ST cost; marks IsEntrySick = true.
/// 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)
{
@@ -106,7 +129,7 @@ public static class GameEngine
var field = new FieldCard
{
InstanceId = card.InstanceId,
InstanceId = card.InstanceId,
CardDefinitionId = card.CardDefinitionId,
Name = card.Name,
CardType = card.CardType,
@@ -121,7 +144,6 @@ public static class GameEngine
Damage = card.Damage,
CanAttack = card.CanAttack,
CanDefend = card.CanDefend,
IsEntrySick = true,
IsExhausted = false,
IsLeader = false,
};
@@ -135,9 +157,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).
///
/// Combat: attacker damage hits defender's defense first, overflow hits health.
/// Defender strikes back (damage hits attacker's health directly if no defense).
/// Destroyed units go to graveyard.
/// 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(
@@ -153,9 +175,8 @@ public static class GameEngine
var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
if (attacker.IsEntrySick) throw new GameException("CARD_ENTRY_SICK");
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");
// Attacker hits target.
ApplyDamage(target, attacker.Damage ?? 0);
@@ -167,24 +188,24 @@ public static class GameEngine
attacker.IsExhausted = true;
// Clean up destroyed cards.
bool gameOver = false;
bool gameOver = false;
var activePlayer = state.Players[actorId];
var opponentPlayer = state.Players[opponentId];
if (attacker.CurrentHealth <= 0)
MoveToGraveyard(activePlayer, attacker);
MoveToDiscard(activePlayer, attacker);
if (target.CurrentHealth <= 0)
{
if (target.IsLeader)
{
// ArchSpirit destroyed — game over.
state.Phase = GamePhase.GameOver;
gameOver = true;
state.Phase = GamePhase.GameOver;
gameOver = true;
}
else
{
MoveToGraveyard(opponentPlayer, target);
MoveToDiscard(opponentPlayer, target);
}
}
@@ -192,40 +213,53 @@ public static class GameEngine
}
/// <summary>
/// End the active player's turn. Resets resources and entry sickness; advances turn.
/// 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.
// 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;
card.IsEntrySick = false;
if (card.MaxDefense.HasValue)
card.CurrentDefense = card.MaxDefense;
}
if (active.ArchSpirit != null)
if (active.ArchSpirit is not null)
{
active.ArchSpirit.IsExhausted = false;
active.ArchSpirit.IsEntrySick = false;
if (active.ArchSpirit.MaxDefense.HasValue)
active.ArchSpirit.CurrentDefense = active.ArchSpirit.MaxDefense;
}
// Switch active player.
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
// Next turn: advance counter, restore resources.
var next = state.Players[state.ActivePlayerAccountId];
// Next player's turn: advance counter, accumulate SP.
var next = state.Players[state.ActivePlayerAccountId];
var rules = state.Rules;
state.TurnNumber++;
next.CurrentSp = next.MaxSp;
next.CurrentSt = next.MaxSt;
state.Phase = GamePhase.Draw;
// 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 conceeding player as the loser.</summary>
/// <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;
@@ -236,7 +270,7 @@ public static class GameEngine
/// <summary>
/// Build a client-safe GameStateDto for a specific player's perspective.
/// Opponent's hand is hidden (null); only counts are shown.
/// Opponent's hand is hidden (null); only the count is shown.
/// </summary>
public static GameStateDto ToDto(GameState state, string viewerAccountId)
{
@@ -250,12 +284,10 @@ public static class GameEngine
DeckCount : p.Deck.Count,
Hand : isSelf ? p.Hand.Select(ToCardDto) : null,
Field : p.Field.Select(ToCardDto),
Graveyard : p.Graveyard.Select(ToCardDto),
Discard : p.Discard.Select(ToCardDto),
ArchSpirit : p.ArchSpirit != null ? ToCardDto(p.ArchSpirit) : null,
CurrentSp : p.CurrentSp,
MaxSp : p.MaxSp,
CurrentSt : p.CurrentSt,
MaxSt : p.MaxSt);
CurrentSt : p.CurrentSt);
});
return new GameStateDto(
@@ -274,10 +306,10 @@ public static class GameEngine
/// </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);
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));
}
@@ -290,7 +322,7 @@ public static class GameEngine
{
var ps = new PlayerState { AccountId = accountId.ToString() };
// Build deck pile (expand quantity).
// Build deck pile (expand by quantity).
var pile = new List<CardInstance>();
foreach (var (def, qty) in deckCards)
{
@@ -326,9 +358,9 @@ public static class GameEngine
IsLeader = true,
};
// Starting resources.
ps.CurrentSp = ps.MaxSp;
ps.CurrentSt = ps.MaxSt;
// SP and ST start at 0 for all players.
ps.CurrentSp = 0;
ps.CurrentSt = 0;
return ps;
}
@@ -379,19 +411,17 @@ public static class GameEngine
}
}
private static void MoveToGraveyard(PlayerState player, FieldCard card)
private static void MoveToDiscard(PlayerState player, FieldCard card)
{
player.Field.Remove(card);
player.Graveyard.Add(card);
player.Discard.Add(card);
}
private static FieldCard GetFieldCard(PlayerState player, string instanceId)
{
// Check field first.
var field = player.Field.OfType<FieldCard>().FirstOrDefault(c => c.InstanceId == instanceId);
if (field != null) return field;
// Check ArchSpirit.
if (player.ArchSpirit?.InstanceId == instanceId)
return player.ArchSpirit;
@@ -427,7 +457,6 @@ public static class GameEngine
MaxDefense : c.MaxDefense,
Damage : c.Damage,
IsExhausted : c.IsExhausted,
IsEntrySick : c.IsEntrySick,
IsLeader : c is FieldCard fc && fc.IsLeader);
}