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
@@ -6,13 +6,13 @@ using SOR.Database.Enums;
/// <summary>
/// EF Core DbContext for the game schema: matchmaking queue entries, game sessions,
/// and the per-session action log.
/// the per-session action log, configurable rule sets, and custom lobbies.
///
/// StateJson (on GameSession) is stored as JSONB.
/// StateJson (on GameSession) and RuleSnapshotJson are stored as JSONB.
/// Cross-schema IDs (AccountId, DeckId) are bare Guids — no EF foreign keys.
///
/// Schema: "game"
/// Run migrations: dotnet ef migrations add InitialCreate
/// Run migrations: dotnet ef migrations add <Name>
/// --context GameDbContext
/// --project src/SOR.Database
/// --startup-project src/SOR.Admin
@@ -26,6 +26,8 @@ public sealed class GameDbContext : DbContext
public DbSet<MatchmakingEntry> MatchmakingEntries => Set<MatchmakingEntry>();
public DbSet<GameSession> GameSessions => Set<GameSession>();
public DbSet<GameActionLog> ActionLogs => Set<GameActionLog>();
public DbSet<GameRuleSet> GameRuleSets => Set<GameRuleSet>();
public DbSet<CustomLobby> CustomLobbies => Set<CustomLobby>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -36,9 +38,7 @@ public sealed class GameDbContext : DbContext
e.ToTable("matchmaking_entries");
e.HasKey(m => m.Id);
e.Property(m => m.Status).HasConversion<string>();
// Primary query: find all Searching entries within a rank range.
e.HasIndex(m => new { m.Status, m.RankScore });
// Used to check if a player is already in the queue.
e.HasIndex(m => new { m.AccountId, m.Status });
});
@@ -48,7 +48,7 @@ public sealed class GameDbContext : DbContext
e.HasKey(s => s.Id);
e.Property(s => s.Status).HasConversion<string>();
e.Property(s => s.StateJson).HasColumnType("jsonb").HasColumnName("state");
// Look up active game for a player.
e.Property(s => s.RuleSnapshotJson).HasColumnType("jsonb").HasColumnName("rule_snapshot");
e.HasIndex(s => s.PlayerOneAccountId);
e.HasIndex(s => s.PlayerTwoAccountId);
e.HasIndex(s => new { s.Status, s.CreatedAt });
@@ -66,5 +66,24 @@ public sealed class GameDbContext : DbContext
e.HasIndex(a => new { a.GameSessionId, a.SequenceNumber }).IsUnique();
e.HasIndex(a => a.ActorAccountId);
});
builder.Entity<GameRuleSet>(e =>
{
e.ToTable("game_rule_sets");
e.HasKey(r => r.Id);
// Enforce only one ranked default and one custom default in application logic;
// filtered indexes here would require PostgreSQL-specific syntax.
e.HasIndex(r => r.IsRankedDefault);
e.HasIndex(r => r.IsCustomDefault);
});
builder.Entity<CustomLobby>(e =>
{
e.ToTable("custom_lobbies");
e.HasKey(l => l.Id);
e.Property(l => l.Status).HasConversion<string>();
e.HasIndex(l => new { l.Status, l.CreatedAt });
e.HasIndex(l => l.HostAccountId);
});
}
}
@@ -0,0 +1,48 @@
namespace SOR.Database.Entities.Game;
using SOR.Database.Enums;
/// <summary>
/// A custom (non-matchmade) game lobby created by a player.
///
/// The host creates the lobby and invites one other player. Once both are present,
/// a GameSession is created using the custom rules. Rule fields that are null inherit
/// from the active custom-default GameRuleSet.
///
/// Cross-schema: all account and deck IDs are bare Guids — no EF foreign keys.
/// </summary>
public sealed class CustomLobby
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public CustomLobbyStatus Status { get; set; } = CustomLobbyStatus.Open;
// ── Host ─────────────────────────────────────────────────────────────────
public Guid HostAccountId { get; set; }
public Guid HostDeckId { get; set; }
// ── Guest ────────────────────────────────────────────────────────────────
public Guid? GuestAccountId { get; set; }
public Guid? GuestDeckId { get; set; }
// ── Linked game session ───────────────────────────────────────────────────
/// <summary>Set once the GameSession is created from this lobby.</summary>
public Guid? GameSessionId { get; set; }
// ── Rule overrides (null = use custom-default ruleset value) ─────────────
public int? OpeningHandSizeOverride { get; set; }
public bool? FirstPlayerSkipsDrawOverride { get; set; }
public int? SpAccumulationPerTurnOverride { get; set; }
public int? DrawPerTurnOverride { get; set; }
public bool? SpHasCapOverride { get; set; }
public int? SpCapOverride { get; set; }
// ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; }
}
@@ -0,0 +1,50 @@
namespace SOR.Database.Entities.Game;
/// <summary>
/// Named ruleset for a game mode. Stored in the DB and managed via the admin portal.
///
/// The ranked default is loaded by MatchmakerService when creating a GameSession.
/// The custom default is used as the base for custom lobby rule overrides.
///
/// Rules are snapshotted into GameSession.RuleSnapshotJson at session creation so
/// that in-flight games are not affected by ruleset changes.
/// </summary>
public sealed class GameRuleSet
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
/// <summary>If true, this ruleset is applied to all ranked matchmaking games.</summary>
public bool IsRankedDefault { get; set; }
/// <summary>If true, this ruleset is used as the base for custom lobby overrides.</summary>
public bool IsCustomDefault { get; set; }
// ── Rules ─────────────────────────────────────────────────────────────────
/// <summary>Cards drawn by all players at game start (before the first turn).</summary>
public int OpeningHandSize { get; set; } = 6;
/// <summary>
/// If true, the first player (P1) skips the Draw phase on their first turn.
/// P2 still draws once at the start of their first turn, giving them 7 cards total.
/// </summary>
public bool FirstPlayerSkipsDraw { get; set; } = true;
/// <summary>SP gained at the start of each player's turn. Accumulates; never resets.</summary>
public int SpAccumulationPerTurn { get; set; } = 3;
/// <summary>Cards drawn during the Draw phase each turn.</summary>
public int DrawPerTurn { get; set; } = 1;
/// <summary>If true, SP is capped at SpCap.</summary>
public bool SpHasCap { get; set; }
/// <summary>Maximum SP balance. Ignored if SpHasCap is false.</summary>
public int SpCap { get; set; }
// ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
@@ -57,6 +57,13 @@ public sealed class GameSession
/// </summary>
public string? StateJson { get; set; }
/// <summary>
/// JSONB blob — snapshot of the GameRuleSet applied to this session at creation.
/// Immutable once the session is created; in-flight games are not affected by
/// admin changes to the live ruleset.
/// </summary>
public string? RuleSnapshotJson { get; set; }
// ── Navigation ───────────────────────────────────────────────────────────
public ICollection<GameActionLog> ActionLog { get; set; } = new List<GameActionLog>();
@@ -44,3 +44,18 @@ public enum GamePhase
/// <summary>Game is over.</summary>
GameOver,
}
/// <summary>
/// State of a custom game lobby.
/// </summary>
public enum CustomLobbyStatus
{
/// <summary>Lobby is open and waiting for a second player to join.</summary>
Open,
/// <summary>Both players are in the lobby; game is about to start.</summary>
Full,
/// <summary>Game session has been created from this lobby.</summary>
Started,
/// <summary>Lobby was cancelled by the host before a game started.</summary>
Cancelled,
}
@@ -0,0 +1,178 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Game
{
[DbContext(typeof(GameDbContext))]
[Migration("20260226125446_AddGameRulesAndCustomLobby")]
partial class AddGameRulesAndCustomLobby
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("game")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActionType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ActorAccountId")
.HasColumnType("uuid");
b.Property<Guid>("GameSessionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("OccurredAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("PayloadJson")
.HasColumnType("jsonb")
.HasColumnName("payload");
b.Property<int>("SequenceNumber")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ActorAccountId");
b.HasIndex("GameSessionId", "SequenceNumber")
.IsUnique();
b.ToTable("action_logs", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("EndedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("PlayerOneAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerOneDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerOneReady")
.HasColumnType("boolean");
b.Property<Guid>("PlayerTwoAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerTwoDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerTwoReady")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("StartedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("StateJson")
.HasColumnType("jsonb")
.HasColumnName("state");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<string>("WinCondition")
.HasColumnType("text");
b.Property<Guid?>("WinnerAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("PlayerOneAccountId");
b.HasIndex("PlayerTwoAccountId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("game_sessions", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("DeckId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("MatchedGameSessionId")
.HasColumnType("uuid");
b.Property<int>("RankScore")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("ResolvedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("AccountId", "Status");
b.HasIndex("Status", "RankScore");
b.ToTable("matchmaking_entries", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.HasOne("SOR.Database.Entities.Game.GameSession", "Session")
.WithMany("ActionLog")
.HasForeignKey("GameSessionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Session");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Navigation("ActionLog");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,146 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Game
{
/// <inheritdoc />
public partial class AddGameRulesAndCustomLobby : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "game");
migrationBuilder.CreateTable(
name: "game_sessions",
schema: "game",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
PlayerOneAccountId = table.Column<Guid>(type: "uuid", nullable: false),
PlayerOneDeckId = table.Column<Guid>(type: "uuid", nullable: false),
PlayerTwoAccountId = table.Column<Guid>(type: "uuid", nullable: false),
PlayerTwoDeckId = table.Column<Guid>(type: "uuid", nullable: false),
PlayerOneReady = table.Column<bool>(type: "boolean", nullable: false),
PlayerTwoReady = table.Column<bool>(type: "boolean", nullable: false),
Status = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
StartedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
EndedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
WinnerAccountId = table.Column<Guid>(type: "uuid", nullable: true),
WinCondition = table.Column<string>(type: "text", nullable: true),
state = table.Column<string>(type: "jsonb", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_game_sessions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "matchmaking_entries",
schema: "game",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
AccountId = table.Column<Guid>(type: "uuid", nullable: false),
DeckId = table.Column<Guid>(type: "uuid", nullable: false),
RankScore = table.Column<int>(type: "integer", nullable: false),
Status = table.Column<string>(type: "text", nullable: false),
JoinedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
ResolvedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
MatchedGameSessionId = table.Column<Guid>(type: "uuid", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_matchmaking_entries", x => x.Id);
});
migrationBuilder.CreateTable(
name: "action_logs",
schema: "game",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
GameSessionId = table.Column<Guid>(type: "uuid", nullable: false),
ActorAccountId = table.Column<Guid>(type: "uuid", nullable: false),
ActionType = table.Column<string>(type: "text", nullable: false),
payload = table.Column<string>(type: "jsonb", nullable: true),
SequenceNumber = table.Column<int>(type: "integer", nullable: false),
OccurredAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_action_logs", x => x.Id);
table.ForeignKey(
name: "FK_action_logs_game_sessions_GameSessionId",
column: x => x.GameSessionId,
principalSchema: "game",
principalTable: "game_sessions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_action_logs_ActorAccountId",
schema: "game",
table: "action_logs",
column: "ActorAccountId");
migrationBuilder.CreateIndex(
name: "IX_action_logs_GameSessionId_SequenceNumber",
schema: "game",
table: "action_logs",
columns: new[] { "GameSessionId", "SequenceNumber" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_game_sessions_PlayerOneAccountId",
schema: "game",
table: "game_sessions",
column: "PlayerOneAccountId");
migrationBuilder.CreateIndex(
name: "IX_game_sessions_PlayerTwoAccountId",
schema: "game",
table: "game_sessions",
column: "PlayerTwoAccountId");
migrationBuilder.CreateIndex(
name: "IX_game_sessions_Status_CreatedAt",
schema: "game",
table: "game_sessions",
columns: new[] { "Status", "CreatedAt" });
migrationBuilder.CreateIndex(
name: "IX_matchmaking_entries_AccountId_Status",
schema: "game",
table: "matchmaking_entries",
columns: new[] { "AccountId", "Status" });
migrationBuilder.CreateIndex(
name: "IX_matchmaking_entries_Status_RankScore",
schema: "game",
table: "matchmaking_entries",
columns: new[] { "Status", "RankScore" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "action_logs",
schema: "game");
migrationBuilder.DropTable(
name: "matchmaking_entries",
schema: "game");
migrationBuilder.DropTable(
name: "game_sessions",
schema: "game");
}
}
}