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:
@@ -78,6 +78,16 @@
|
||||
<i class="bi bi-joystick me-2"></i>Sessions
|
||||
</NavLink>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white-50 py-1" href="/game/ranked-rules">
|
||||
<i class="bi bi-sliders me-2"></i>Ranked Rules
|
||||
</NavLink>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white-50 py-1" href="/game/custom-lobbies">
|
||||
<i class="bi bi-people-fill me-2"></i>Custom Lobbies
|
||||
</NavLink>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
@page "/game/custom-lobbies"
|
||||
@using SOR.Database.Contexts
|
||||
@using SOR.Database.Entities.Game
|
||||
@using SOR.Database.Enums
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
@inject GameDbContext GameDb
|
||||
|
||||
<PageTitle>Custom Lobbies — SOR Admin</PageTitle>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1 class="h3 mb-0">Custom Lobbies</h1>
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
|
||||
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<div class="d-flex align-items-center gap-2 text-muted">
|
||||
<div class="spinner-border spinner-border-sm"></div>Loading…
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<!-- Stats row -->
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-sm-3">
|
||||
<div class="card text-center p-3">
|
||||
<div class="fs-2 fw-bold text-primary">@_lobbies.Count(l => l.Status == CustomLobbyStatus.Open)</div>
|
||||
<div class="text-muted small">Open</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-3">
|
||||
<div class="card text-center p-3">
|
||||
<div class="fs-2 fw-bold text-warning">@_lobbies.Count(l => l.Status == CustomLobbyStatus.Full)</div>
|
||||
<div class="text-muted small">Full</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-3">
|
||||
<div class="card text-center p-3">
|
||||
<div class="fs-2 fw-bold text-success">@_lobbies.Count(l => l.Status == CustomLobbyStatus.Started)</div>
|
||||
<div class="text-muted small">Started Today</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-3">
|
||||
<div class="card text-center p-3">
|
||||
<div class="fs-2 fw-bold text-secondary">@_lobbies.Count(l => l.Status == CustomLobbyStatus.Cancelled)</div>
|
||||
<div class="text-muted small">Cancelled Today</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Filter -->
|
||||
<div class="mb-3 d-flex gap-2 align-items-center">
|
||||
<label class="form-label mb-0 fw-semibold">Status:</label>
|
||||
<select class="form-select form-select-sm w-auto" @bind="_statusFilter">
|
||||
<option value="">All</option>
|
||||
<option value="Open">Open</option>
|
||||
<option value="Full">Full</option>
|
||||
<option value="Started">Started</option>
|
||||
<option value="Cancelled">Cancelled</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm table-hover align-middle">
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th>Lobby Name</th>
|
||||
<th>Host</th>
|
||||
<th>Guest</th>
|
||||
<th>Status</th>
|
||||
<th>Rules (SP/Turn, Hand)</th>
|
||||
<th>Created</th>
|
||||
<th>Session</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var lobby in FilteredLobbies)
|
||||
{
|
||||
<tr>
|
||||
<td><code>@lobby.Name</code></td>
|
||||
<td><code class="text-muted small">@lobby.HostAccountId.ToString()[..8]…</code></td>
|
||||
<td>
|
||||
@if (lobby.GuestAccountId.HasValue)
|
||||
{
|
||||
<code class="text-muted small">@lobby.GuestAccountId.Value.ToString()[..8]…</code>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="text-muted">—</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge @StatusBadge(lobby.Status)">@lobby.Status</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="text-muted small">
|
||||
+@(lobby.SpAccumulationPerTurnOverride ?? 3) SP/turn,
|
||||
@(lobby.OpeningHandSizeOverride ?? 6) card hand
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-muted small">@lobby.CreatedAt.ToLocalTime().ToString("MM/dd HH:mm")</td>
|
||||
<td>
|
||||
@if (lobby.GameSessionId.HasValue)
|
||||
{
|
||||
<code class="text-muted small">@lobby.GameSessionId.Value.ToString()[..8]…</code>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="text-muted">—</span>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
@if (!FilteredLobbies.Any())
|
||||
{
|
||||
<tr><td colspan="7" class="text-center text-muted py-3">No lobbies found.</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private List<CustomLobby> _lobbies = new();
|
||||
private bool _loading = true;
|
||||
private string _statusFilter = "";
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadAsync();
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
_loading = true;
|
||||
var cutoff = DateTimeOffset.UtcNow.Date;
|
||||
|
||||
_lobbies = await GameDb.CustomLobbies
|
||||
.AsNoTracking()
|
||||
.Where(l => l.Status == CustomLobbyStatus.Open
|
||||
|| l.Status == CustomLobbyStatus.Full
|
||||
|| l.CreatedAt >= cutoff)
|
||||
.OrderByDescending(l => l.CreatedAt)
|
||||
.Take(200)
|
||||
.ToListAsync();
|
||||
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
private IEnumerable<CustomLobby> FilteredLobbies =>
|
||||
string.IsNullOrEmpty(_statusFilter)
|
||||
? _lobbies
|
||||
: _lobbies.Where(l => l.Status.ToString() == _statusFilter);
|
||||
|
||||
private static string StatusBadge(CustomLobbyStatus status) => status switch
|
||||
{
|
||||
CustomLobbyStatus.Open => "bg-primary",
|
||||
CustomLobbyStatus.Full => "bg-warning text-dark",
|
||||
CustomLobbyStatus.Started => "bg-success",
|
||||
CustomLobbyStatus.Cancelled => "bg-secondary",
|
||||
_ => "bg-secondary",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
@page "/game/ranked-rules"
|
||||
@using SOR.Database.Contexts
|
||||
@using SOR.Database.Entities.Game
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
@inject GameDbContext GameDb
|
||||
@inject ILogger<RankedRulesPage> Logger
|
||||
|
||||
<PageTitle>Ranked Rules — SOR Admin</PageTitle>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1 class="h3 mb-0">Ranked Play Rules</h1>
|
||||
<button class="btn btn-success" @onclick="SaveAsync" disabled="@_saving">
|
||||
@if (_saving) { <span class="spinner-border spinner-border-sm me-1"></span> }
|
||||
Save Rules
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (_saved)
|
||||
{
|
||||
<div class="alert alert-success alert-dismissible fade show" role="alert">
|
||||
Ranked rules saved successfully.
|
||||
<button type="button" class="btn-close" @onclick="() => _saved = false"></button>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (_error is not null)
|
||||
{
|
||||
<div class="alert alert-danger">@_error</div>
|
||||
}
|
||||
|
||||
@if (_rules is null)
|
||||
{
|
||||
<div class="d-flex align-items-center gap-2 text-muted">
|
||||
<div class="spinner-border spinner-border-sm"></div>Loading…
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="row g-4">
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">Opening Hand</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label fw-semibold">Opening Hand Size</label>
|
||||
<input type="number" class="form-control" min="1" max="20"
|
||||
@bind="_rules.OpeningHandSize" />
|
||||
<div class="form-text">Cards each player draws at game start (before turn 1).</div>
|
||||
</div>
|
||||
<div class="form-check form-switch mb-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="skipDraw"
|
||||
@bind="_rules.FirstPlayerSkipsDraw" />
|
||||
<label class="form-check-label" for="skipDraw">
|
||||
First player skips Turn 1 draw
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-text text-muted">
|
||||
When enabled, P1 goes straight to Main on turn 1. P2 still draws once
|
||||
at the start of their first turn, giving them one extra card total.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">Spirit Points (SP)</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label fw-semibold">SP Accumulation Per Turn</label>
|
||||
<input type="number" class="form-control" min="0" max="100"
|
||||
@bind="_rules.SpAccumulationPerTurn" />
|
||||
<div class="form-text">
|
||||
SP gained at the start of each player's turn. SP accumulates — it never
|
||||
resets between turns. All players start at 0 SP.
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-check form-switch mb-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="spCap"
|
||||
@bind="_rules.SpHasCap" />
|
||||
<label class="form-check-label" for="spCap">Enforce SP cap</label>
|
||||
</div>
|
||||
@if (_rules.SpHasCap)
|
||||
{
|
||||
<div class="mt-2">
|
||||
<label class="form-label">SP Cap</label>
|
||||
<input type="number" class="form-control" min="1" max="999"
|
||||
@bind="_rules.SpCap" />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">Draw Phase</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label fw-semibold">Cards Drawn Per Turn</label>
|
||||
<input type="number" class="form-control" min="0" max="10"
|
||||
@bind="_rules.DrawPerTurn" />
|
||||
<div class="form-text">Cards drawn during the Draw phase each turn.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header text-muted">Custom Default</div>
|
||||
<div class="card-body">
|
||||
<div class="form-check form-switch">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="isCustomDefault"
|
||||
@bind="_rules.IsCustomDefault" />
|
||||
<label class="form-check-label" for="isCustomDefault">
|
||||
Also use as custom lobby default
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-text">
|
||||
When enabled, custom lobbies inherit these rules before applying their own overrides.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private GameRuleSet? _rules;
|
||||
private bool _saving;
|
||||
private bool _saved;
|
||||
private string? _error;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_rules = await GameDb.GameRuleSets
|
||||
.Where(r => r.IsRankedDefault)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (_rules is null)
|
||||
{
|
||||
_rules = new GameRuleSet
|
||||
{
|
||||
Name = "Ranked",
|
||||
IsRankedDefault = true,
|
||||
IsCustomDefault = true,
|
||||
OpeningHandSize = 6,
|
||||
FirstPlayerSkipsDraw = true,
|
||||
SpAccumulationPerTurn = 3,
|
||||
DrawPerTurn = 1,
|
||||
SpHasCap = false,
|
||||
SpCap = 0,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
GameDb.GameRuleSets.Add(_rules);
|
||||
await GameDb.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (_rules is null) return;
|
||||
_saving = true;
|
||||
_error = null;
|
||||
try
|
||||
{
|
||||
_rules.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await GameDb.SaveChangesAsync();
|
||||
_saved = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = ex.Message;
|
||||
Logger.LogError(ex, "Failed to save ranked rules.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_saving = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
Generated
+178
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,10 +26,39 @@ public sealed record GameEndTurnRequest(Guid SessionId);
|
||||
/// <summary>Concede the game (forfeit).</summary>
|
||||
public sealed record GameConcedeRequest(Guid SessionId);
|
||||
|
||||
// ── Custom lobby requests ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Create a new custom lobby. Host provides their deck and optional rule overrides.</summary>
|
||||
public sealed record CreateCustomLobbyRequest(
|
||||
string LobbyName,
|
||||
Guid DeckId,
|
||||
CustomRulesOverride? Rules = null);
|
||||
|
||||
/// <summary>
|
||||
/// Per-field rule overrides for a custom lobby. Null fields inherit from the
|
||||
/// active custom-default GameRuleSet.
|
||||
/// </summary>
|
||||
public sealed record CustomRulesOverride(
|
||||
int? OpeningHandSize = null,
|
||||
bool? FirstPlayerSkipsDraw = null,
|
||||
int? SpAccumulationPerTurn = null,
|
||||
int? DrawPerTurn = null,
|
||||
bool? SpHasCap = null,
|
||||
int? SpCap = null);
|
||||
|
||||
/// <summary>Join an open custom lobby with the specified deck.</summary>
|
||||
public sealed record JoinCustomLobbyRequest(Guid LobbyId, Guid DeckId);
|
||||
|
||||
/// <summary>Leave or cancel a custom lobby.</summary>
|
||||
public sealed record LeaveCustomLobbyRequest(Guid LobbyId);
|
||||
|
||||
/// <summary>List open custom lobbies.</summary>
|
||||
public sealed record ListCustomLobbiesRequest(int Page = 1, int PageSize = 20);
|
||||
|
||||
// ── Responses ─────────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed record GameReadyResponse(Guid SessionId, string Status);
|
||||
// Status: "WaitingForOpponent" | "Started"
|
||||
// Status: "WaitingForOpponent" | "AlreadyStarted" | "Started"
|
||||
|
||||
public sealed record GameGetStateResponse(GameStateDto State);
|
||||
|
||||
@@ -43,6 +72,26 @@ public sealed record GameEndTurnResponse(GameStateDto State);
|
||||
|
||||
public sealed record GameConcedeResponse(GameStateDto State);
|
||||
|
||||
// ── Custom lobby responses ─────────────────────────────────────────────────────
|
||||
|
||||
public sealed record CreateCustomLobbyResponse(
|
||||
Guid LobbyId,
|
||||
string LobbyName,
|
||||
CustomRulesDto ActiveRules);
|
||||
|
||||
public sealed record JoinCustomLobbyResponse(
|
||||
Guid LobbyId,
|
||||
string Status, // "WaitingForHost" | "GameCreated"
|
||||
Guid? GameSessionId); // set when Status == "GameCreated"
|
||||
|
||||
public sealed record LeaveCustomLobbyResponse(Guid LobbyId);
|
||||
|
||||
public sealed record ListCustomLobbiesResponse(
|
||||
IEnumerable<CustomLobbyDto> Lobbies,
|
||||
int TotalCount,
|
||||
int Page,
|
||||
int PageSize);
|
||||
|
||||
// ── Server Pushes ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
@@ -61,6 +110,14 @@ public sealed record GameOverPush(
|
||||
int WinnerRankDelta,
|
||||
int LoserRankDelta);
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to both players when a custom lobby is full and a GameSession has been created.
|
||||
/// Players should navigate to the game screen and send game.ready.
|
||||
/// </summary>
|
||||
public sealed record CustomLobbyGameStartedPush(
|
||||
Guid SessionId,
|
||||
Guid OpponentAccountId);
|
||||
|
||||
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
@@ -68,23 +125,21 @@ public sealed record GameOverPush(
|
||||
/// </summary>
|
||||
public sealed record GameStateDto(
|
||||
Guid SessionId,
|
||||
string Phase, // Draw | Main | End | GameOver
|
||||
string Phase, // Draw | Main | End | GameOver
|
||||
string ActivePlayerAccountId,
|
||||
int TurnNumber,
|
||||
IEnumerable<PlayerStateDto> Players);
|
||||
|
||||
public sealed record PlayerStateDto(
|
||||
Guid AccountId,
|
||||
int HandCount, // always shown; actual cards visible only for self
|
||||
int HandCount, // always shown; actual cards visible only to self
|
||||
int DeckCount,
|
||||
IEnumerable<CardInstanceDto>? Hand, // null for opponent
|
||||
IEnumerable<CardInstanceDto> Field, // always visible
|
||||
IEnumerable<CardInstanceDto> Graveyard,
|
||||
CardInstanceDto? ArchSpirit, // leader card on field
|
||||
int CurrentSp, // spirit points this turn
|
||||
int MaxSp,
|
||||
int CurrentSt, // stone points this turn
|
||||
int MaxSt);
|
||||
IEnumerable<CardInstanceDto>? Hand, // null for opponent
|
||||
IEnumerable<CardInstanceDto> Field, // always visible
|
||||
IEnumerable<CardInstanceDto> Discard, // always visible
|
||||
CardInstanceDto? ArchSpirit,
|
||||
int CurrentSp,
|
||||
int CurrentSt);
|
||||
|
||||
public sealed record CardInstanceDto(
|
||||
string InstanceId,
|
||||
@@ -99,5 +154,20 @@ public sealed record CardInstanceDto(
|
||||
int? MaxDefense,
|
||||
int? Damage,
|
||||
bool IsExhausted,
|
||||
bool IsEntrySick,
|
||||
bool IsLeader); // true for the ArchSpirit
|
||||
|
||||
public sealed record CustomLobbyDto(
|
||||
Guid LobbyId,
|
||||
string LobbyName,
|
||||
Guid HostAccountId,
|
||||
bool HasGuest,
|
||||
CustomRulesDto Rules,
|
||||
DateTimeOffset CreatedAt);
|
||||
|
||||
public sealed record CustomRulesDto(
|
||||
int OpeningHandSize,
|
||||
bool FirstPlayerSkipsDraw,
|
||||
int SpAccumulationPerTurn,
|
||||
int DrawPerTurn,
|
||||
bool SpHasCap,
|
||||
int SpCap);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
/// <summary>
|
||||
/// Active rule configuration embedded in GameState and deserialized from
|
||||
/// GameSession.RuleSnapshotJson when a game is initialized.
|
||||
///
|
||||
/// Defaults reflect the standard ruleset:
|
||||
/// - Both players draw 6 cards at game start.
|
||||
/// - P1 skips the Draw phase on turn 1 (they already drew their opening hand).
|
||||
/// P2 still draws once at the start of their first turn → 7 cards total.
|
||||
/// - SP starts at 0, gains +3 per turn, never resets, no cap.
|
||||
/// - Draw 1 card per turn during the Draw phase.
|
||||
/// </summary>
|
||||
public sealed record GameRules
|
||||
{
|
||||
public int OpeningHandSize { get; init; } = 6;
|
||||
public bool FirstPlayerSkipsDraw { get; init; } = true;
|
||||
public int SpAccumulationPerTurn { get; init; } = 3;
|
||||
public int DrawPerTurn { get; init; } = 1;
|
||||
public bool SpHasCap { get; init; } = false;
|
||||
public int SpCap { get; init; } = 0;
|
||||
|
||||
public static readonly GameRules Default = new();
|
||||
}
|
||||
@@ -8,9 +8,9 @@ using SOR.Database.Enums;
|
||||
/// </summary>
|
||||
public sealed class GameState
|
||||
{
|
||||
public Guid SessionId { get; set; }
|
||||
public GamePhase Phase { get; set; } = GamePhase.Setup;
|
||||
public int TurnNumber { get; set; } = 1;
|
||||
public Guid SessionId { get; set; }
|
||||
public GamePhase Phase { get; set; } = GamePhase.Setup;
|
||||
public int TurnNumber { get; set; } = 1;
|
||||
|
||||
/// <summary>AccountId (as string) of the player whose turn it currently is.</summary>
|
||||
public string ActivePlayerAccountId { get; set; } = string.Empty;
|
||||
@@ -20,6 +20,9 @@ public sealed class GameState
|
||||
|
||||
/// <summary>Running sequence number for action log entries.</summary>
|
||||
public int NextActionSequence { get; set; } = 1;
|
||||
|
||||
/// <summary>Rules snapshot applied to this game session.</summary>
|
||||
public GameRules Rules { get; set; } = GameRules.Default;
|
||||
}
|
||||
|
||||
public sealed class PlayerState
|
||||
@@ -28,20 +31,24 @@ public sealed class PlayerState
|
||||
|
||||
// ── Zones ────────────────────────────────────────────────────────────────
|
||||
|
||||
public List<CardInstance> Hand { get; set; } = new();
|
||||
public List<CardInstance> Deck { get; set; } = new();
|
||||
public List<CardInstance> Field { get; set; } = new();
|
||||
public List<CardInstance> Graveyard { get; set; } = new();
|
||||
public List<CardInstance> Hand { get; set; } = new();
|
||||
public List<CardInstance> Deck { get; set; } = new();
|
||||
public List<CardInstance> Field { get; set; } = new();
|
||||
public List<CardInstance> Discard { get; set; } = new();
|
||||
|
||||
// ── Resources ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Spirit points available this turn.</summary>
|
||||
/// <summary>
|
||||
/// Spirit Points — starts at 0, gains SpAccumulationPerTurn each turn.
|
||||
/// Accumulates indefinitely; never resets between turns.
|
||||
/// </summary>
|
||||
public int CurrentSp { get; set; }
|
||||
public int MaxSp { get; set; } = 5;
|
||||
|
||||
/// <summary>Stone points available this turn.</summary>
|
||||
/// <summary>
|
||||
/// Sacrifice Tokens — earned only by sacrificing Spirits (never granted per-turn).
|
||||
/// Starts at 0.
|
||||
/// </summary>
|
||||
public int CurrentSt { get; set; }
|
||||
public int MaxSt { get; set; } = 5;
|
||||
|
||||
// ── Leader ───────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -72,24 +79,21 @@ public class CardInstance
|
||||
|
||||
// ── Combat stats ─────────────────────────────────────────────────────────
|
||||
|
||||
public int? MaxHealth { get; set; }
|
||||
public int? CurrentHealth { get; set; }
|
||||
public int? MaxDefense { get; set; }
|
||||
public int? MaxHealth { get; set; }
|
||||
public int? CurrentHealth { get; set; }
|
||||
public int? MaxDefense { get; set; }
|
||||
public int? CurrentDefense { get; set; }
|
||||
public int? Damage { get; set; }
|
||||
public int? Damage { get; set; }
|
||||
|
||||
// ── State flags ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>True if the card has already attacked or used an ability this turn.</summary>
|
||||
public bool IsExhausted { get; set; }
|
||||
|
||||
/// <summary>True if the card was played this turn (cannot attack until next turn).</summary>
|
||||
public bool IsEntrySick { get; set; }
|
||||
// ── Field flags ──────────────────────────────────────────────────────────
|
||||
|
||||
// ── Field-only flags ─────────────────────────────────────────────────────
|
||||
|
||||
public bool CanAttack { get; set; }
|
||||
public bool CanDefend { get; set; }
|
||||
public bool CanAttack { get; set; }
|
||||
public bool CanDefend { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.custom.create — host creates a new custom lobby with optional rule overrides.
|
||||
///
|
||||
/// The active custom-default GameRuleSet is loaded from the DB and merged with any
|
||||
/// per-field overrides supplied by the host. The merged rules are stored as the
|
||||
/// lobby's effective ruleset.
|
||||
/// </summary>
|
||||
internal sealed class GameCreateCustomLobbyHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public GameCreateCustomLobbyHandler(IMessageSerializer serializer, GameDbContext gameDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "game.custom.create";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<CreateCustomLobbyRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
// Load custom-default rules as the base.
|
||||
var defaultRules = await _gameDb.GameRuleSets
|
||||
.AsNoTracking()
|
||||
.Where(r => r.IsCustomDefault)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
// Build effective rules by merging overrides on top of the default.
|
||||
var effective = new GameRules
|
||||
{
|
||||
OpeningHandSize = req.Rules?.OpeningHandSize ?? defaultRules?.OpeningHandSize ?? GameRules.Default.OpeningHandSize,
|
||||
FirstPlayerSkipsDraw = req.Rules?.FirstPlayerSkipsDraw ?? defaultRules?.FirstPlayerSkipsDraw ?? GameRules.Default.FirstPlayerSkipsDraw,
|
||||
SpAccumulationPerTurn = req.Rules?.SpAccumulationPerTurn ?? defaultRules?.SpAccumulationPerTurn ?? GameRules.Default.SpAccumulationPerTurn,
|
||||
DrawPerTurn = req.Rules?.DrawPerTurn ?? defaultRules?.DrawPerTurn ?? GameRules.Default.DrawPerTurn,
|
||||
SpHasCap = req.Rules?.SpHasCap ?? defaultRules?.SpHasCap ?? GameRules.Default.SpHasCap,
|
||||
SpCap = req.Rules?.SpCap ?? defaultRules?.SpCap ?? GameRules.Default.SpCap,
|
||||
};
|
||||
|
||||
var lobby = new CustomLobby
|
||||
{
|
||||
Name = req.LobbyName,
|
||||
HostAccountId = accountId,
|
||||
HostDeckId = req.DeckId,
|
||||
Status = CustomLobbyStatus.Open,
|
||||
OpeningHandSizeOverride = req.Rules?.OpeningHandSize,
|
||||
FirstPlayerSkipsDrawOverride = req.Rules?.FirstPlayerSkipsDraw,
|
||||
SpAccumulationPerTurnOverride = req.Rules?.SpAccumulationPerTurn,
|
||||
DrawPerTurnOverride = req.Rules?.DrawPerTurn,
|
||||
SpHasCapOverride = req.Rules?.SpHasCap,
|
||||
SpCapOverride = req.Rules?.SpCap,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
_gameDb.CustomLobbies.Add(lobby);
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
return ServerMessage.Reply("game.custom.create.ack", message.Seq,
|
||||
new CreateCustomLobbyResponse(
|
||||
LobbyId : lobby.Id,
|
||||
LobbyName : lobby.Name,
|
||||
ActiveRules : ToDto(effective)));
|
||||
}
|
||||
|
||||
private static CustomRulesDto ToDto(GameRules r) => new(
|
||||
OpeningHandSize : r.OpeningHandSize,
|
||||
FirstPlayerSkipsDraw : r.FirstPlayerSkipsDraw,
|
||||
SpAccumulationPerTurn : r.SpAccumulationPerTurn,
|
||||
DrawPerTurn : r.DrawPerTurn,
|
||||
SpHasCap : r.SpHasCap,
|
||||
SpCap : r.SpCap);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.custom.join — guest joins an open custom lobby with their chosen deck.
|
||||
///
|
||||
/// When the lobby is full (both host and guest present), a GameSession is created
|
||||
/// immediately and CustomLobbyGameStartedPush is sent to both players. Both players
|
||||
/// then send game.ready to start the actual game.
|
||||
/// </summary>
|
||||
internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameJoinCustomLobbyHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.custom.join";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<JoinCustomLobbyRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
|
||||
?? throw new GameException("LOBBY_NOT_FOUND");
|
||||
|
||||
if (lobby.Status != CustomLobbyStatus.Open)
|
||||
throw new GameException("LOBBY_NOT_OPEN");
|
||||
|
||||
if (lobby.HostAccountId == accountId)
|
||||
throw new GameException("CANNOT_JOIN_OWN_LOBBY");
|
||||
|
||||
lobby.GuestAccountId = accountId;
|
||||
lobby.GuestDeckId = req.DeckId;
|
||||
lobby.Status = CustomLobbyStatus.Full;
|
||||
|
||||
// Build the effective rules from stored overrides (falling back to Default).
|
||||
var rules = new GameRules
|
||||
{
|
||||
OpeningHandSize = lobby.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize,
|
||||
FirstPlayerSkipsDraw = lobby.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw,
|
||||
SpAccumulationPerTurn = lobby.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn,
|
||||
DrawPerTurn = lobby.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn,
|
||||
SpHasCap = lobby.SpHasCapOverride ?? GameRules.Default.SpHasCap,
|
||||
SpCap = lobby.SpCapOverride ?? GameRules.Default.SpCap,
|
||||
};
|
||||
|
||||
// Create the game session with the rule snapshot.
|
||||
var session = new GameSession
|
||||
{
|
||||
PlayerOneAccountId = lobby.HostAccountId,
|
||||
PlayerOneDeckId = lobby.HostDeckId,
|
||||
PlayerTwoAccountId = accountId,
|
||||
PlayerTwoDeckId = req.DeckId,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RuleSnapshotJson = JsonSerializer.Serialize(rules),
|
||||
};
|
||||
|
||||
_gameDb.GameSessions.Add(session);
|
||||
|
||||
lobby.GameSessionId = session.Id;
|
||||
lobby.Status = CustomLobbyStatus.Started;
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
// Push game-started notification to both players.
|
||||
var push = new CustomLobbyGameStartedPush(session.Id, accountId);
|
||||
var pushToHost = new CustomLobbyGameStartedPush(session.Id, accountId);
|
||||
var pushToGuest = new CustomLobbyGameStartedPush(session.Id, lobby.HostAccountId);
|
||||
|
||||
await Task.WhenAll(
|
||||
_clientPush.PushAsync(lobby.HostAccountId.ToString(),
|
||||
ServerMessage.Push("game.custom.started", pushToHost), ct),
|
||||
_clientPush.PushAsync(accountId.ToString(),
|
||||
ServerMessage.Push("game.custom.started", pushToGuest), ct));
|
||||
|
||||
return ServerMessage.Reply("game.custom.join.ack", message.Seq,
|
||||
new JoinCustomLobbyResponse(
|
||||
LobbyId : lobby.Id,
|
||||
Status : "GameCreated",
|
||||
GameSessionId : session.Id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.custom.leave — leave or cancel a custom lobby.
|
||||
///
|
||||
/// Host cancelling: marks the lobby Cancelled (removes it for guests).
|
||||
/// Guest leaving: clears their slot, resets lobby to Open.
|
||||
/// </summary>
|
||||
internal sealed class GameLeaveCustomLobbyHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public GameLeaveCustomLobbyHandler(IMessageSerializer serializer, GameDbContext gameDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "game.custom.leave";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<LeaveCustomLobbyRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
|
||||
?? throw new GameException("LOBBY_NOT_FOUND");
|
||||
|
||||
if (lobby.Status == CustomLobbyStatus.Started || lobby.Status == CustomLobbyStatus.Cancelled)
|
||||
throw new GameException("LOBBY_ALREADY_RESOLVED");
|
||||
|
||||
if (lobby.HostAccountId == accountId)
|
||||
{
|
||||
// Host cancels — closes the lobby entirely.
|
||||
lobby.Status = CustomLobbyStatus.Cancelled;
|
||||
}
|
||||
else if (lobby.GuestAccountId == accountId)
|
||||
{
|
||||
// Guest leaves — free up the slot.
|
||||
lobby.GuestAccountId = null;
|
||||
lobby.GuestDeckId = null;
|
||||
lobby.Status = CustomLobbyStatus.Open;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new GameException("NOT_IN_LOBBY");
|
||||
}
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
return ServerMessage.Reply("game.custom.leave.ack", message.Seq,
|
||||
new LeaveCustomLobbyResponse(LobbyId: lobby.Id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.custom.list — returns a paged list of open custom lobbies.
|
||||
/// </summary>
|
||||
internal sealed class GameListCustomLobbiesHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public GameListCustomLobbiesHandler(IMessageSerializer serializer, GameDbContext gameDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "game.custom.list";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<ListCustomLobbiesRequest>(message.Payload);
|
||||
|
||||
var page = Math.Max(1, req.Page);
|
||||
var pageSize = Math.Clamp(req.PageSize, 1, 100);
|
||||
|
||||
var query = _gameDb.CustomLobbies
|
||||
.AsNoTracking()
|
||||
.Where(l => l.Status == CustomLobbyStatus.Open)
|
||||
.OrderByDescending(l => l.CreatedAt);
|
||||
|
||||
var total = await query.CountAsync(ct);
|
||||
var lobbies = await query
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var dtos = lobbies.Select(l => new CustomLobbyDto(
|
||||
LobbyId : l.Id,
|
||||
LobbyName : l.Name,
|
||||
HostAccountId : l.HostAccountId,
|
||||
HasGuest : l.GuestAccountId.HasValue,
|
||||
Rules : new CustomRulesDto(
|
||||
OpeningHandSize : l.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize,
|
||||
FirstPlayerSkipsDraw : l.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw,
|
||||
SpAccumulationPerTurn : l.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn,
|
||||
DrawPerTurn : l.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn,
|
||||
SpHasCap : l.SpHasCapOverride ?? GameRules.Default.SpHasCap,
|
||||
SpCap : l.SpCapOverride ?? GameRules.Default.SpCap),
|
||||
CreatedAt : l.CreatedAt));
|
||||
|
||||
return ServerMessage.Reply("game.custom.list.ack", message.Seq,
|
||||
new ListCustomLobbiesResponse(
|
||||
Lobbies : dtos,
|
||||
TotalCount : total,
|
||||
Page : page,
|
||||
PageSize : pageSize));
|
||||
}
|
||||
}
|
||||
@@ -74,15 +74,21 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
|
||||
}
|
||||
|
||||
// Both ready — initialize game state.
|
||||
var p1DeckCards = await LoadDeckCardsAsync(session.PlayerOneDeckId, ct);
|
||||
var p2DeckCards = await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct);
|
||||
var p1ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct);
|
||||
var p2ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct);
|
||||
var p1DeckCards = await LoadDeckCardsAsync(session.PlayerOneDeckId, ct);
|
||||
var p2DeckCards = await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct);
|
||||
var p1ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct);
|
||||
var p2ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct);
|
||||
|
||||
// Deserialize rule snapshot (falls back to default if none stored).
|
||||
var rules = session.RuleSnapshotJson is not null
|
||||
? GameEngine.DeserializeRules(session.RuleSnapshotJson)
|
||||
: null;
|
||||
|
||||
var state = GameEngine.Initialize(
|
||||
session.Id,
|
||||
session.PlayerOneAccountId, p1DeckCards, session.PlayerOneDeckId, p1ArchSpirit,
|
||||
session.PlayerTwoAccountId, p2DeckCards, session.PlayerTwoDeckId, p2ArchSpirit);
|
||||
session.PlayerTwoAccountId, p2DeckCards, session.PlayerTwoDeckId, p2ArchSpirit,
|
||||
rules);
|
||||
|
||||
session.StateJson = GameEngine.Serialize(state);
|
||||
session.Status = GameSessionStatus.Active;
|
||||
|
||||
@@ -29,6 +29,12 @@ public static class ServiceRegistration
|
||||
services.AddTransient<IMessageHandler, GameEndTurnHandler>();
|
||||
services.AddTransient<IMessageHandler, GameConcedeHandler>();
|
||||
|
||||
// Custom lobby handlers
|
||||
services.AddTransient<IMessageHandler, GameCreateCustomLobbyHandler>();
|
||||
services.AddTransient<IMessageHandler, GameJoinCustomLobbyHandler>();
|
||||
services.AddTransient<IMessageHandler, GameLeaveCustomLobbyHandler>();
|
||||
services.AddTransient<IMessageHandler, GameListCustomLobbiesHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace SOR.Matchmaking;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
@@ -100,6 +101,12 @@ internal sealed class MatchmakerService : BackgroundService
|
||||
if (opponent == null)
|
||||
continue;
|
||||
|
||||
// Load the ranked ruleset and snapshot it into the session.
|
||||
var rankedRules = await gameDb.GameRuleSets
|
||||
.AsNoTracking()
|
||||
.Where(r => r.IsRankedDefault)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
// Create a game session.
|
||||
var session = new GameSession
|
||||
{
|
||||
@@ -109,6 +116,17 @@ internal sealed class MatchmakerService : BackgroundService
|
||||
PlayerTwoDeckId = opponent.DeckId,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = now,
|
||||
RuleSnapshotJson = rankedRules is not null
|
||||
? JsonSerializer.Serialize(new
|
||||
{
|
||||
rankedRules.OpeningHandSize,
|
||||
rankedRules.FirstPlayerSkipsDraw,
|
||||
rankedRules.SpAccumulationPerTurn,
|
||||
rankedRules.DrawPerTurn,
|
||||
rankedRules.SpHasCap,
|
||||
rankedRules.SpCap,
|
||||
})
|
||||
: null,
|
||||
};
|
||||
|
||||
gameDb.GameSessions.Add(session);
|
||||
|
||||
Reference in New Issue
Block a user