Add matchmaking + gameplay services (SOR.Matchmaking + SOR.Game)
DB layer:
- Account.RankScore (int, default 1000) — ELO rank for matchmaking
- GameEnums: MatchmakingStatus, GameSessionStatus, GamePhase
- Entities: MatchmakingEntry, GameSession, GameActionLog
- GameDbContext (schema: game) + AddGameDatabase() registration
- Migrations: AddRankScore (Identity), InitialCreate (Game)
SOR.Matchmaking:
- MatchmakerService (BackgroundService) — 5s poll, ELO ±100→±500 range
- Handlers: matchmaking.join, matchmaking.leave, matchmaking.status
- Pushes MatchFoundPush to both players via IClientPush on match
SOR.Game:
- GameState / PlayerState / CardInstance / FieldCard JSONB model
- GameEngine (pure static): Init, Draw, PlayCard, Attack, EndTurn, Concede
- ELO delta (K=32) computed and applied on game end
- Handlers: game.ready, game.get_state, game.draw, game.play_card,
game.attack, game.end_turn, game.concede
- State filtered per-viewer (opponent hand/deck hidden)
- GameOverPush with rank deltas to both players
Admin pages:
- /game/matchmaking — live queue stats, active entries, recent activity
- /game/sessions — session stats, filterable by status/account
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:
@@ -8,8 +8,10 @@
|
||||
<Project Path="src/SOR.Collection/SOR.Collection.csproj" />
|
||||
<Project Path="src/SOR.Content/SOR.Content.csproj" />
|
||||
<Project Path="src/SOR.Database/SOR.Database.csproj" />
|
||||
<Project Path="src/SOR.Game/SOR.Game.csproj" />
|
||||
<Project Path="src/SOR.Gateway/SOR.Gateway.csproj" />
|
||||
<Project Path="src/SOR.Host/SOR.Host.csproj" />
|
||||
<Project Path="src/SOR.Matchmaking/SOR.Matchmaking.csproj" />
|
||||
<Project Path="src/SOR.Networking.Abstractions/SOR.Networking.Abstractions.csproj" />
|
||||
<Project Path="src/SOR.Networking.Nats/SOR.Networking.Nats.csproj" />
|
||||
<Project Path="src/SOR.Networking.Redis/SOR.Networking.Redis.csproj" />
|
||||
|
||||
@@ -63,6 +63,23 @@
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white" href="/game/matchmaking" Match="NavLinkMatch.All">
|
||||
<i class="bi bi-controller me-2"></i>Game
|
||||
</NavLink>
|
||||
<ul class="nav nav-pills flex-column gap-1 ps-3 mt-1">
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white-50 py-1" href="/game/matchmaking">
|
||||
<i class="bi bi-search me-2"></i>Matchmaking
|
||||
</NavLink>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white-50 py-1" href="/game/sessions">
|
||||
<i class="bi bi-joystick me-2"></i>Sessions
|
||||
</NavLink>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white" href="/versioning/releases" Match="NavLinkMatch.All">
|
||||
<i class="bi bi-phone me-2"></i>Client Versions
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
@page "/game/sessions"
|
||||
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
@using SOR.Database.Contexts
|
||||
@using SOR.Database.Enums
|
||||
@inject GameDbContext Db
|
||||
|
||||
<PageTitle>Game Sessions – SOR Admin</PageTitle>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1 class="mb-0">Game Sessions</h1>
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
|
||||
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Stats -->
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-md-3">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-warning">@_initializingCount</div>
|
||||
<div class="text-muted small">Initializing</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-success">@_activeCount</div>
|
||||
<div class="text-muted small">Active</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-primary">@_completedToday</div>
|
||||
<div class="text-muted small">Completed Today</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-secondary">@_abandonedToday</div>
|
||||
<div class="text-muted small">Abandoned Today</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Filters -->
|
||||
<div class="card shadow-sm mb-3">
|
||||
<div class="card-body py-2">
|
||||
<div class="row g-3 align-items-end">
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small fw-medium">Status</label>
|
||||
<select @bind="_filterStatus" class="form-select form-select-sm">
|
||||
<option value="">All</option>
|
||||
@foreach (var s in Enum.GetNames<GameSessionStatus>())
|
||||
{
|
||||
<option value="@s">@s</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small fw-medium">Player Account ID</label>
|
||||
<input @bind="_filterAccountId" class="form-control form-control-sm font-monospace"
|
||||
placeholder="GUID" />
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<button class="btn btn-primary btn-sm w-100 mt-4" @onclick="LoadAsync">
|
||||
<i class="bi bi-search me-1"></i>Search
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<p class="text-muted">Loading…</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header fw-medium d-flex justify-content-between">
|
||||
<span>Sessions</span>
|
||||
<span class="badge bg-secondary">@_total</span>
|
||||
</div>
|
||||
<div class="card-body p-0">
|
||||
<table class="table table-sm table-hover mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Created</th>
|
||||
<th>Session ID</th>
|
||||
<th>P1 Account</th>
|
||||
<th>P2 Account</th>
|
||||
<th>Status</th>
|
||||
<th>Duration</th>
|
||||
<th>Winner</th>
|
||||
<th>Win Condition</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var s in _sessions)
|
||||
{
|
||||
<tr>
|
||||
<td class="text-muted small">@s.CreatedAt.ToString("yyyy-MM-dd HH:mm")</td>
|
||||
<td class="font-monospace small text-muted">@s.Id.ToString()[..8]…</td>
|
||||
<td class="font-monospace small">@s.PlayerOneAccountId.ToString()[..8]…</td>
|
||||
<td class="font-monospace small">@s.PlayerTwoAccountId.ToString()[..8]…</td>
|
||||
<td><span class="badge @StatusBadge(s.Status)">@s.Status</span></td>
|
||||
<td class="text-muted small">@s.Duration</td>
|
||||
<td class="font-monospace small">
|
||||
@(s.WinnerAccountId.HasValue ? s.WinnerAccountId.Value.ToString()[..8] + "…" : "—")
|
||||
</td>
|
||||
<td class="text-muted small">@(s.WinCondition ?? "—")</td>
|
||||
</tr>
|
||||
}
|
||||
@if (!_sessions.Any())
|
||||
{
|
||||
<tr>
|
||||
<td colspan="8" class="text-muted text-center py-3">No sessions found.</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_totalPages > 1)
|
||||
{
|
||||
<div class="d-flex justify-content-center gap-2 mt-3">
|
||||
<button class="btn btn-sm btn-outline-secondary"
|
||||
disabled="@(_page <= 1)"
|
||||
@onclick="() => ChangePage(_page - 1)">
|
||||
<i class="bi bi-chevron-left"></i>
|
||||
</button>
|
||||
<span class="btn btn-sm disabled">@_page / @_totalPages</span>
|
||||
<button class="btn btn-sm btn-outline-secondary"
|
||||
disabled="@(_page >= _totalPages)"
|
||||
@onclick="() => ChangePage(_page + 1)">
|
||||
<i class="bi bi-chevron-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@code {
|
||||
private bool _loading = true;
|
||||
private int _page = 1, _totalPages = 1, _total;
|
||||
private const int PageSize = 50;
|
||||
|
||||
private int _initializingCount, _activeCount, _completedToday, _abandonedToday;
|
||||
private string _filterStatus = string.Empty;
|
||||
private string _filterAccountId = string.Empty;
|
||||
|
||||
private record SessionRow(
|
||||
Guid Id,
|
||||
Guid PlayerOneAccountId,
|
||||
Guid PlayerTwoAccountId,
|
||||
string Status,
|
||||
DateTimeOffset CreatedAt,
|
||||
string Duration,
|
||||
Guid? WinnerAccountId,
|
||||
string? WinCondition);
|
||||
|
||||
private List<SessionRow> _sessions = new();
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadAsync();
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
_loading = true;
|
||||
var todayStart = DateTimeOffset.UtcNow.Date;
|
||||
|
||||
_initializingCount = await Db.GameSessions.CountAsync(s => s.Status == GameSessionStatus.Initializing);
|
||||
_activeCount = await Db.GameSessions.CountAsync(s => s.Status == GameSessionStatus.Active);
|
||||
_completedToday = await Db.GameSessions.CountAsync(s => s.Status == GameSessionStatus.Completed && s.EndedAt >= todayStart);
|
||||
_abandonedToday = await Db.GameSessions.CountAsync(s => s.Status == GameSessionStatus.Abandoned && s.EndedAt >= todayStart);
|
||||
|
||||
var q = Db.GameSessions.AsQueryable();
|
||||
|
||||
if (!string.IsNullOrEmpty(_filterStatus) && Enum.TryParse<GameSessionStatus>(_filterStatus, out var st))
|
||||
q = q.Where(s => s.Status == st);
|
||||
|
||||
if (Guid.TryParse(_filterAccountId, out var accId))
|
||||
q = q.Where(s => s.PlayerOneAccountId == accId || s.PlayerTwoAccountId == accId);
|
||||
|
||||
_total = await q.CountAsync();
|
||||
_totalPages = Math.Max(1, (int)Math.Ceiling(_total / (double)PageSize));
|
||||
_page = Math.Clamp(_page, 1, _totalPages);
|
||||
|
||||
_sessions = await q
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.Skip((_page - 1) * PageSize)
|
||||
.Take(PageSize)
|
||||
.Select(s => new SessionRow(
|
||||
s.Id,
|
||||
s.PlayerOneAccountId,
|
||||
s.PlayerTwoAccountId,
|
||||
s.Status.ToString(),
|
||||
s.CreatedAt,
|
||||
s.EndedAt.HasValue && s.StartedAt.HasValue
|
||||
? FormatDurationEf(s.EndedAt.Value - s.StartedAt.Value)
|
||||
: "—",
|
||||
s.WinnerAccountId,
|
||||
s.WinCondition))
|
||||
.ToListAsync();
|
||||
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
private async Task ChangePage(int p)
|
||||
{
|
||||
_page = p;
|
||||
await LoadAsync();
|
||||
}
|
||||
|
||||
private static string FormatDurationEf(TimeSpan ts)
|
||||
{
|
||||
if (ts.TotalHours >= 1) return $"{(int)ts.TotalHours}h {ts.Minutes}m";
|
||||
if (ts.TotalMinutes >= 1) return $"{(int)ts.TotalMinutes}m {ts.Seconds}s";
|
||||
return $"{(int)ts.TotalSeconds}s";
|
||||
}
|
||||
|
||||
private static string StatusBadge(string status) => status switch
|
||||
{
|
||||
nameof(GameSessionStatus.Initializing) => "bg-warning text-dark",
|
||||
nameof(GameSessionStatus.Active) => "bg-success",
|
||||
nameof(GameSessionStatus.Completed) => "bg-primary",
|
||||
nameof(GameSessionStatus.Abandoned) => "bg-secondary",
|
||||
_ => "bg-light text-dark",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
@page "/game/matchmaking"
|
||||
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
@using SOR.Database.Contexts
|
||||
@using SOR.Database.Enums
|
||||
@inject GameDbContext Db
|
||||
|
||||
<PageTitle>Matchmaking Queue – SOR Admin</PageTitle>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1 class="mb-0">Matchmaking Queue</h1>
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
|
||||
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Stats -->
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-md-4">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-primary">@_searchingCount</div>
|
||||
<div class="text-muted small">Currently Searching</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-success">@_matchedToday</div>
|
||||
<div class="text-muted small">Matched Today</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card shadow-sm text-center py-3">
|
||||
<div class="display-6 fw-bold text-secondary">@_cancelledToday</div>
|
||||
<div class="text-muted small">Cancelled Today</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<p class="text-muted">Loading…</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<!-- Active Queue -->
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header fw-medium d-flex justify-content-between">
|
||||
<span>Active Queue</span>
|
||||
<span class="badge bg-primary">@_searchingEntries.Count players waiting</span>
|
||||
</div>
|
||||
<div class="card-body p-0">
|
||||
<table class="table table-sm table-hover mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Account</th>
|
||||
<th class="text-end">Rank</th>
|
||||
<th>Waiting</th>
|
||||
<th>Deck</th>
|
||||
<th>Entry ID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var e in _searchingEntries)
|
||||
{
|
||||
<tr>
|
||||
<td class="font-monospace small">@e.AccountId.ToString()[..8]…</td>
|
||||
<td class="text-end fw-medium">@e.RankScore</td>
|
||||
<td class="text-muted small">@FormatWait(e.JoinedAt)</td>
|
||||
<td class="font-monospace small text-muted">@e.DeckId.ToString()[..8]…</td>
|
||||
<td class="font-monospace small text-muted">@e.Id.ToString()[..8]…</td>
|
||||
</tr>
|
||||
}
|
||||
@if (!_searchingEntries.Any())
|
||||
{
|
||||
<tr>
|
||||
<td colspan="5" class="text-muted text-center py-3">Queue is empty.</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Entries -->
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header fw-medium">Recent Activity (last 100)</div>
|
||||
<div class="card-body p-0">
|
||||
<table class="table table-sm table-hover mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Joined</th>
|
||||
<th>Account</th>
|
||||
<th class="text-end">Rank</th>
|
||||
<th>Status</th>
|
||||
<th>Wait</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var e in _recentEntries)
|
||||
{
|
||||
<tr>
|
||||
<td class="text-muted small">@e.JoinedAt.ToString("HH:mm:ss")</td>
|
||||
<td class="font-monospace small">@e.AccountId.ToString()[..8]…</td>
|
||||
<td class="text-end">@e.RankScore</td>
|
||||
<td>
|
||||
<span class="badge @StatusBadge(e.Status)">@e.Status</span>
|
||||
</td>
|
||||
<td class="small text-muted">
|
||||
@(e.ResolvedAt.HasValue
|
||||
? FormatDuration(e.ResolvedAt.Value - e.JoinedAt)
|
||||
: FormatWait(e.JoinedAt))
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private bool _loading = true;
|
||||
private int _searchingCount, _matchedToday, _cancelledToday;
|
||||
|
||||
private List<QueueRow> _searchingEntries = new();
|
||||
private List<QueueRow> _recentEntries = new();
|
||||
|
||||
private record QueueRow(
|
||||
Guid Id,
|
||||
Guid AccountId,
|
||||
Guid DeckId,
|
||||
int RankScore,
|
||||
string Status,
|
||||
DateTimeOffset JoinedAt,
|
||||
DateTimeOffset? ResolvedAt);
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadAsync();
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
_loading = true;
|
||||
var todayStart = DateTimeOffset.UtcNow.Date;
|
||||
|
||||
_searchingCount = await Db.MatchmakingEntries.CountAsync(e => e.Status == MatchmakingStatus.Searching);
|
||||
_matchedToday = await Db.MatchmakingEntries.CountAsync(e => e.Status == MatchmakingStatus.Matched && e.ResolvedAt >= todayStart);
|
||||
_cancelledToday = await Db.MatchmakingEntries.CountAsync(e => e.Status == MatchmakingStatus.Cancelled && e.ResolvedAt >= todayStart);
|
||||
|
||||
_searchingEntries = await Db.MatchmakingEntries
|
||||
.Where(e => e.Status == MatchmakingStatus.Searching)
|
||||
.OrderBy(e => e.JoinedAt)
|
||||
.Select(e => new QueueRow(e.Id, e.AccountId, e.DeckId, e.RankScore, e.Status.ToString(), e.JoinedAt, e.ResolvedAt))
|
||||
.ToListAsync();
|
||||
|
||||
_recentEntries = await Db.MatchmakingEntries
|
||||
.OrderByDescending(e => e.JoinedAt)
|
||||
.Take(100)
|
||||
.Select(e => new QueueRow(e.Id, e.AccountId, e.DeckId, e.RankScore, e.Status.ToString(), e.JoinedAt, e.ResolvedAt))
|
||||
.ToListAsync();
|
||||
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
private static string FormatWait(DateTimeOffset joinedAt)
|
||||
{
|
||||
var wait = DateTimeOffset.UtcNow - joinedAt;
|
||||
return FormatDuration(wait);
|
||||
}
|
||||
|
||||
private static string FormatDuration(TimeSpan ts)
|
||||
{
|
||||
if (ts.TotalHours >= 1) return $"{(int)ts.TotalHours}h {ts.Minutes}m";
|
||||
if (ts.TotalMinutes >= 1) return $"{(int)ts.TotalMinutes}m {ts.Seconds}s";
|
||||
return $"{(int)ts.TotalSeconds}s";
|
||||
}
|
||||
|
||||
private static string StatusBadge(string status) => status switch
|
||||
{
|
||||
nameof(MatchmakingStatus.Searching) => "bg-primary",
|
||||
nameof(MatchmakingStatus.Matched) => "bg-success",
|
||||
nameof(MatchmakingStatus.Cancelled) => "bg-secondary",
|
||||
_ => "bg-light text-dark",
|
||||
};
|
||||
}
|
||||
@@ -80,6 +80,7 @@ builder.Services.AddCatalogDatabase(builder.Configuration);
|
||||
builder.Services.AddCollectionDatabase(builder.Configuration);
|
||||
builder.Services.AddBazaarDatabase(builder.Configuration);
|
||||
builder.Services.AddChatDatabase(builder.Configuration);
|
||||
builder.Services.AddGameDatabase(builder.Configuration);
|
||||
|
||||
// ── HTTP pipeline ─────────────────────────────────────────────────────────
|
||||
var app = builder.Build();
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace SOR.Database.Contexts;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// EF Core DbContext for the game schema: matchmaking queue entries, game sessions,
|
||||
/// and the per-session action log.
|
||||
///
|
||||
/// StateJson (on GameSession) is stored as JSONB.
|
||||
/// Cross-schema IDs (AccountId, DeckId) are bare Guids — no EF foreign keys.
|
||||
///
|
||||
/// Schema: "game"
|
||||
/// Run migrations: dotnet ef migrations add InitialCreate
|
||||
/// --context GameDbContext
|
||||
/// --project src/SOR.Database
|
||||
/// --startup-project src/SOR.Admin
|
||||
/// --output-dir Migrations/Game
|
||||
/// </summary>
|
||||
public sealed class GameDbContext : DbContext
|
||||
{
|
||||
public GameDbContext(DbContextOptions<GameDbContext> options)
|
||||
: base(options) { }
|
||||
|
||||
public DbSet<MatchmakingEntry> MatchmakingEntries => Set<MatchmakingEntry>();
|
||||
public DbSet<GameSession> GameSessions => Set<GameSession>();
|
||||
public DbSet<GameActionLog> ActionLogs => Set<GameActionLog>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
builder.HasDefaultSchema("game");
|
||||
|
||||
builder.Entity<MatchmakingEntry>(e =>
|
||||
{
|
||||
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 });
|
||||
});
|
||||
|
||||
builder.Entity<GameSession>(e =>
|
||||
{
|
||||
e.ToTable("game_sessions");
|
||||
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.HasIndex(s => s.PlayerOneAccountId);
|
||||
e.HasIndex(s => s.PlayerTwoAccountId);
|
||||
e.HasIndex(s => new { s.Status, s.CreatedAt });
|
||||
e.HasMany(s => s.ActionLog)
|
||||
.WithOne(a => a.Session)
|
||||
.HasForeignKey(a => a.GameSessionId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
builder.Entity<GameActionLog>(e =>
|
||||
{
|
||||
e.ToTable("action_logs");
|
||||
e.HasKey(a => a.Id);
|
||||
e.Property(a => a.PayloadJson).HasColumnType("jsonb").HasColumnName("payload");
|
||||
e.HasIndex(a => new { a.GameSessionId, a.SequenceNumber }).IsUnique();
|
||||
e.HasIndex(a => a.ActorAccountId);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace SOR.Database.Entities.Game;
|
||||
|
||||
/// <summary>
|
||||
/// Immutable audit log of every action taken during a game session.
|
||||
/// Used for replay, dispute resolution, and analytics.
|
||||
///
|
||||
/// PayloadJson stores the raw action request (draw, play_card, attack, etc.)
|
||||
/// as JSONB so no schema changes are needed when actions evolve.
|
||||
/// </summary>
|
||||
public sealed class GameActionLog
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public Guid GameSessionId { get; set; }
|
||||
|
||||
/// <summary>AccountId of the player who took the action.</summary>
|
||||
public Guid ActorAccountId { get; set; }
|
||||
|
||||
/// <summary>Action type — mirrors the game message type (e.g. "game.play_card").</summary>
|
||||
public string ActionType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>JSONB: serialized action request payload.</summary>
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
/// <summary>1-based sequence number within the game session.</summary>
|
||||
public int SequenceNumber { get; set; }
|
||||
|
||||
public DateTimeOffset OccurredAt { get; set; }
|
||||
|
||||
// ── Navigation ───────────────────────────────────────────────────────────
|
||||
|
||||
public GameSession Session { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace SOR.Database.Entities.Game;
|
||||
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single game match between two players.
|
||||
///
|
||||
/// Live game state is stored as JSONB in StateJson and is updated after every action.
|
||||
/// The full GameState object (board, hands, decks, etc.) is serialized there.
|
||||
///
|
||||
/// Cross-schema: all account and deck IDs are bare Guids — no EF foreign keys.
|
||||
/// </summary>
|
||||
public sealed class GameSession
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
// ── Players ──────────────────────────────────────────────────────────────
|
||||
|
||||
public Guid PlayerOneAccountId { get; set; }
|
||||
public Guid PlayerOneDeckId { get; set; }
|
||||
|
||||
public Guid PlayerTwoAccountId { get; set; }
|
||||
public Guid PlayerTwoDeckId { get; set; }
|
||||
|
||||
// ── Readiness ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Set to true when player one sends game.ready.</summary>
|
||||
public bool PlayerOneReady { get; set; }
|
||||
|
||||
/// <summary>Set to true when player two sends game.ready.</summary>
|
||||
public bool PlayerTwoReady { get; set; }
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────────────────
|
||||
|
||||
public GameSessionStatus Status { get; set; } = GameSessionStatus.Initializing;
|
||||
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public DateTimeOffset? StartedAt { get; set; }
|
||||
public DateTimeOffset? EndedAt { get; set; }
|
||||
|
||||
// ── Result ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>AccountId of the winning player. Null until game ends.</summary>
|
||||
public Guid? WinnerAccountId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// "concede" | "health" (ArchSpirit destroyed) | "disconnect" | "timeout"
|
||||
/// </summary>
|
||||
public string? WinCondition { get; set; }
|
||||
|
||||
// ── Live state ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// JSONB blob — the full live GameState object.
|
||||
/// Updated after every game action.
|
||||
/// The GameEngine reads and writes this exclusively.
|
||||
/// </summary>
|
||||
public string? StateJson { get; set; }
|
||||
|
||||
// ── Navigation ───────────────────────────────────────────────────────────
|
||||
|
||||
public ICollection<GameActionLog> ActionLog { get; set; } = new List<GameActionLog>();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace SOR.Database.Entities.Game;
|
||||
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a player's entry in the matchmaking queue.
|
||||
/// Created when a player joins the queue; status updated when matched or cancelled.
|
||||
///
|
||||
/// Cross-schema: AccountId and DeckId are bare Guids — no EF foreign keys.
|
||||
/// </summary>
|
||||
public sealed class MatchmakingEntry
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>Identity schema account (bare Guid — no EF FK).</summary>
|
||||
public Guid AccountId { get; set; }
|
||||
|
||||
/// <summary>Deck the player intends to use for the match.</summary>
|
||||
public Guid DeckId { get; set; }
|
||||
|
||||
/// <summary>ELO rank score at the time the player joined the queue.</summary>
|
||||
public int RankScore { get; set; }
|
||||
|
||||
public MatchmakingStatus Status { get; set; } = MatchmakingStatus.Searching;
|
||||
|
||||
public DateTimeOffset JoinedAt { get; set; }
|
||||
|
||||
/// <summary>Null until a match is found or entry is cancelled.</summary>
|
||||
public DateTimeOffset? ResolvedAt { get; set; }
|
||||
|
||||
/// <summary>Set when status transitions to Matched.</summary>
|
||||
public Guid? MatchedGameSessionId { get; set; }
|
||||
}
|
||||
@@ -38,4 +38,10 @@ public sealed class Account : IdentityUser<Guid>
|
||||
/// Spent on booster packs, prebuilt decks, cosmetics, and P2P listings.
|
||||
/// </summary>
|
||||
public int OriginPoints { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ELO-style rank score used for matchmaking.
|
||||
/// Starts at 1000. Adjusted after each ranked game using K=32 factor.
|
||||
/// </summary>
|
||||
public int RankScore { get; set; } = 1000;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
namespace SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Lifecycle state of a matchmaking queue entry.
|
||||
/// </summary>
|
||||
public enum MatchmakingStatus
|
||||
{
|
||||
/// <summary>Player is actively waiting for an opponent.</summary>
|
||||
Searching,
|
||||
/// <summary>Match has been found; entry is kept for audit until game starts.</summary>
|
||||
Matched,
|
||||
/// <summary>Player cancelled before a match was found.</summary>
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lifecycle state of a game session.
|
||||
/// </summary>
|
||||
public enum GameSessionStatus
|
||||
{
|
||||
/// <summary>Both players have been matched; waiting for ready confirmations.</summary>
|
||||
Initializing,
|
||||
/// <summary>Game is in progress.</summary>
|
||||
Active,
|
||||
/// <summary>Game has ended with a winner/loser result.</summary>
|
||||
Completed,
|
||||
/// <summary>One or both players disconnected before the game could start.</summary>
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turn phases within an active game.
|
||||
/// </summary>
|
||||
public enum GamePhase
|
||||
{
|
||||
/// <summary>Game just started — both players draw their opening hands.</summary>
|
||||
Setup,
|
||||
/// <summary>Active player draws a card.</summary>
|
||||
Draw,
|
||||
/// <summary>Active player may play cards, activate abilities, and attack.</summary>
|
||||
Main,
|
||||
/// <summary>Active player has declared end of turn; cleanup runs.</summary>
|
||||
End,
|
||||
/// <summary>Game is over.</summary>
|
||||
GameOver,
|
||||
}
|
||||
+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("20260226112003_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <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 InitialCreate : 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SOR.Database.Contexts;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SOR.Database.Migrations.Game
|
||||
{
|
||||
[DbContext(typeof(GameDbContext))]
|
||||
partial class GameDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(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
|
||||
}
|
||||
}
|
||||
}
|
||||
+410
@@ -0,0 +1,410 @@
|
||||
// <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.Identity
|
||||
{
|
||||
[DbContext(typeof(SorIdentityDbContext))]
|
||||
[Migration("20260226111950_AddRankScore")]
|
||||
partial class AddRankScore
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasDefaultSchema("identity")
|
||||
.HasAnnotation("ProductVersion", "8.0.0")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex");
|
||||
|
||||
b.ToTable("roles", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("role_claims", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("account_claims", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("external_logins", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("account_roles", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("UserId", "LoginProvider", "Name");
|
||||
|
||||
b.ToTable("account_tokens", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Identity.Account", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("AvatarCdnUrl")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastLoginAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<int>("OriginPoints")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("RankScore")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("StarterDeckSelectedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DisplayName");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex");
|
||||
|
||||
b.ToTable("accounts", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Identity.AccountProperty", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AccountId");
|
||||
|
||||
b.HasIndex("AccountId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("account_properties", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Identity.AccountSession", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("DeviceId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("UserAgent")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("AccountId", "ExpiresAt");
|
||||
|
||||
b.ToTable("account_sessions", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Identity.ClientRelease", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("DownloadUrl")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsRequired")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Platform")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ReleaseNotes")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset>("ReleasedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Platform", "IsActive", "ReleasedAt");
|
||||
|
||||
b.ToTable("client_releases", "identity");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SOR.Database.Entities.Identity.Account", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SOR.Database.Entities.Identity.Account", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SOR.Database.Entities.Identity.Account", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SOR.Database.Entities.Identity.Account", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SOR.Database.Migrations.Identity
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddRankScore : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "RankScore",
|
||||
schema: "identity",
|
||||
table: "accounts",
|
||||
type: "integer",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "RankScore",
|
||||
schema: "identity",
|
||||
table: "accounts");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,6 +211,9 @@ namespace SOR.Database.Migrations.Identity
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("RankScore")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
|
||||
@@ -63,6 +63,15 @@ public static class ServiceRegistration
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddGameDatabase(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.AddDbContext<GameDbContext>(opts =>
|
||||
opts.UseNpgsql(Resolve(configuration, "Game")));
|
||||
return services;
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static string Resolve(IConfiguration configuration, string contextName)
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Entities.Catalog;
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Pure game logic — no database access, no DI. Takes a GameState, mutates it,
|
||||
/// returns the updated state. Handlers are responsible for loading and saving.
|
||||
///
|
||||
/// v1 scope: draw, play, attack, end_turn, concede.
|
||||
/// No abilities, no ascension, no positional grid.
|
||||
/// </summary>
|
||||
public static class GameEngine
|
||||
{
|
||||
private static readonly JsonSerializerOptions _json =
|
||||
new(JsonSerializerDefaults.Web) { WriteIndented = false };
|
||||
|
||||
// ── Serialization ─────────────────────────────────────────────────────────
|
||||
|
||||
public static GameState Deserialize(string json)
|
||||
=> JsonSerializer.Deserialize<GameState>(json, _json)
|
||||
?? throw new InvalidOperationException("Failed to deserialize GameState.");
|
||||
|
||||
public static string Serialize(GameState state)
|
||||
=> JsonSerializer.Serialize(state, _json);
|
||||
|
||||
// ── 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.
|
||||
/// ArchSpirit cards are placed on the field as leaders (not in the deck pile).
|
||||
/// </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)
|
||||
{
|
||||
var state = new GameState
|
||||
{
|
||||
SessionId = sessionId,
|
||||
Phase = GamePhase.Draw,
|
||||
TurnNumber = 1,
|
||||
ActivePlayerAccountId = p1AccountId.ToString(),
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
state.Phase = GamePhase.Main;
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
// ── Actions ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Draw the top card from the active player's deck into hand.
|
||||
/// Returns null if the deck is empty (no mill — just no draw).
|
||||
/// </summary>
|
||||
public static (GameState state, CardInstance? drawn) Draw(GameState state, string actorId)
|
||||
{
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Draw, GamePhase.Main);
|
||||
|
||||
var player = state.Players[actorId];
|
||||
if (player.Deck.Count == 0)
|
||||
return (state, null);
|
||||
|
||||
var card = player.Deck[0];
|
||||
player.Deck.RemoveAt(0);
|
||||
player.Hand.Add(card);
|
||||
|
||||
if (state.Phase == GamePhase.Draw)
|
||||
state.Phase = GamePhase.Main;
|
||||
|
||||
return (state, card);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Play a card from hand onto the field (non-ArchSpirit cards only).
|
||||
/// Deducts SP/ST cost; marks IsEntrySick = true.
|
||||
/// </summary>
|
||||
public static GameState PlayCard(GameState state, string actorId, string cardInstanceId)
|
||||
{
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
|
||||
var player = state.Players[actorId];
|
||||
var card = player.Hand.FirstOrDefault(c => c.InstanceId == cardInstanceId)
|
||||
?? throw new GameException("CARD_NOT_IN_HAND");
|
||||
|
||||
if (player.CurrentSp < card.SpCost)
|
||||
throw new GameException("INSUFFICIENT_SP");
|
||||
if (player.CurrentSt < card.StCost)
|
||||
throw new GameException("INSUFFICIENT_ST");
|
||||
|
||||
player.Hand.Remove(card);
|
||||
player.CurrentSp -= card.SpCost;
|
||||
player.CurrentSt -= card.StCost;
|
||||
|
||||
var field = new FieldCard
|
||||
{
|
||||
InstanceId = card.InstanceId,
|
||||
CardDefinitionId = card.CardDefinitionId,
|
||||
Name = card.Name,
|
||||
CardType = card.CardType,
|
||||
Affinity = card.Affinity,
|
||||
Rarity = card.Rarity,
|
||||
SpCost = card.SpCost,
|
||||
StCost = card.StCost,
|
||||
MaxHealth = card.MaxHealth,
|
||||
CurrentHealth = card.MaxHealth,
|
||||
MaxDefense = card.MaxDefense,
|
||||
CurrentDefense = card.MaxDefense,
|
||||
Damage = card.Damage,
|
||||
CanAttack = card.CanAttack,
|
||||
CanDefend = card.CanDefend,
|
||||
IsEntrySick = true,
|
||||
IsExhausted = false,
|
||||
IsLeader = false,
|
||||
};
|
||||
|
||||
player.Field.Add(field);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Declare an attack from one of the active player's field cards against an
|
||||
/// opponent's field card (or their ArchSpirit).
|
||||
///
|
||||
/// Combat: attacker damage hits defender's defense first, overflow hits health.
|
||||
/// Defender strikes back (damage hits attacker's health directly if no defense).
|
||||
/// Destroyed units go to graveyard.
|
||||
/// If the defending ArchSpirit is destroyed the game ends.
|
||||
/// </summary>
|
||||
public static (GameState state, bool gameOver) Attack(
|
||||
GameState state,
|
||||
string actorId,
|
||||
string attackerInstanceId,
|
||||
string targetInstanceId)
|
||||
{
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
|
||||
var opponentId = GetOpponentId(state, actorId);
|
||||
var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
|
||||
var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
|
||||
|
||||
if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
|
||||
if (attacker.IsEntrySick) throw new GameException("CARD_ENTRY_SICK");
|
||||
if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK");
|
||||
|
||||
// Attacker hits target.
|
||||
ApplyDamage(target, attacker.Damage ?? 0);
|
||||
|
||||
// Target counter-attacks if able (and still alive).
|
||||
if (target.CurrentHealth > 0 && target.CanAttack && !target.IsExhausted)
|
||||
ApplyDamage(attacker, target.Damage ?? 0);
|
||||
|
||||
attacker.IsExhausted = true;
|
||||
|
||||
// Clean up destroyed cards.
|
||||
bool gameOver = false;
|
||||
var activePlayer = state.Players[actorId];
|
||||
var opponentPlayer = state.Players[opponentId];
|
||||
|
||||
if (attacker.CurrentHealth <= 0)
|
||||
MoveToGraveyard(activePlayer, attacker);
|
||||
|
||||
if (target.CurrentHealth <= 0)
|
||||
{
|
||||
if (target.IsLeader)
|
||||
{
|
||||
// ArchSpirit destroyed — game over.
|
||||
state.Phase = GamePhase.GameOver;
|
||||
gameOver = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveToGraveyard(opponentPlayer, target);
|
||||
}
|
||||
}
|
||||
|
||||
return (state, gameOver);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// End the active player's turn. Resets resources and entry sickness; advances turn.
|
||||
/// </summary>
|
||||
public static GameState EndTurn(GameState state, string actorId)
|
||||
{
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
|
||||
// Refresh active player's field cards.
|
||||
var active = state.Players[actorId];
|
||||
foreach (var card in active.Field)
|
||||
{
|
||||
card.IsExhausted = false;
|
||||
card.IsEntrySick = false;
|
||||
}
|
||||
if (active.ArchSpirit != null)
|
||||
{
|
||||
active.ArchSpirit.IsExhausted = false;
|
||||
active.ArchSpirit.IsEntrySick = false;
|
||||
}
|
||||
|
||||
// Switch active player.
|
||||
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
|
||||
|
||||
// Next turn: advance counter, restore resources.
|
||||
var next = state.Players[state.ActivePlayerAccountId];
|
||||
state.TurnNumber++;
|
||||
next.CurrentSp = next.MaxSp;
|
||||
next.CurrentSt = next.MaxSt;
|
||||
state.Phase = GamePhase.Draw;
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/// <summary>Mark the game as over with the conceeding player as the loser.</summary>
|
||||
public static GameState Concede(GameState state, string actorId)
|
||||
{
|
||||
state.Phase = GamePhase.GameOver;
|
||||
return state;
|
||||
}
|
||||
|
||||
// ── DTO projection ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Build a client-safe GameStateDto for a specific player's perspective.
|
||||
/// Opponent's hand is hidden (null); only counts are shown.
|
||||
/// </summary>
|
||||
public static GameStateDto ToDto(GameState state, string viewerAccountId)
|
||||
{
|
||||
var players = state.Players.Values.Select(p =>
|
||||
{
|
||||
var isSelf = p.AccountId == viewerAccountId;
|
||||
|
||||
return new PlayerStateDto(
|
||||
AccountId : Guid.Parse(p.AccountId),
|
||||
HandCount : p.Hand.Count,
|
||||
DeckCount : p.Deck.Count,
|
||||
Hand : isSelf ? p.Hand.Select(ToCardDto) : null,
|
||||
Field : p.Field.Select(ToCardDto),
|
||||
Graveyard : p.Graveyard.Select(ToCardDto),
|
||||
ArchSpirit : p.ArchSpirit != null ? ToCardDto(p.ArchSpirit) : null,
|
||||
CurrentSp : p.CurrentSp,
|
||||
MaxSp : p.MaxSp,
|
||||
CurrentSt : p.CurrentSt,
|
||||
MaxSt : p.MaxSt);
|
||||
});
|
||||
|
||||
return new GameStateDto(
|
||||
SessionId : state.SessionId,
|
||||
Phase : state.Phase.ToString(),
|
||||
ActivePlayerAccountId : state.ActivePlayerAccountId,
|
||||
TurnNumber : state.TurnNumber,
|
||||
Players : players);
|
||||
}
|
||||
|
||||
// ── ELO ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Compute ELO rank score deltas after a game.
|
||||
/// Returns (winnerDelta, loserDelta) — both are positive values indicating change magnitude.
|
||||
/// </summary>
|
||||
public static (int winnerDelta, int loserDelta) ComputeEloDelta(int winnerScore, int loserScore)
|
||||
{
|
||||
const double K = 32.0;
|
||||
var expected = 1.0 / (1.0 + Math.Pow(10, (loserScore - winnerScore) / 400.0));
|
||||
var winnerDelta = (int)Math.Round(K * (1.0 - expected));
|
||||
var loserDelta = (int)Math.Round(K * expected);
|
||||
return (Math.Max(1, winnerDelta), Math.Max(1, loserDelta));
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static PlayerState BuildPlayerState(
|
||||
Guid accountId,
|
||||
IEnumerable<(CardDefinition def, int qty)> deckCards,
|
||||
CardDefinition archSpiritDef)
|
||||
{
|
||||
var ps = new PlayerState { AccountId = accountId.ToString() };
|
||||
|
||||
// Build deck pile (expand quantity).
|
||||
var pile = new List<CardInstance>();
|
||||
foreach (var (def, qty) in deckCards)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
pile.Add(DefinitionToInstance(def));
|
||||
}
|
||||
|
||||
// Shuffle.
|
||||
var rng = new Random();
|
||||
for (int i = pile.Count - 1; i > 0; i--)
|
||||
{
|
||||
int j = rng.Next(i + 1);
|
||||
(pile[i], pile[j]) = (pile[j], pile[i]);
|
||||
}
|
||||
ps.Deck = pile;
|
||||
|
||||
// ArchSpirit starts on the field as the leader.
|
||||
ps.ArchSpirit = new FieldCard
|
||||
{
|
||||
InstanceId = $"arch_{accountId:N}"[..8],
|
||||
CardDefinitionId = archSpiritDef.Id,
|
||||
Name = archSpiritDef.Name,
|
||||
CardType = archSpiritDef.CardType.ToString(),
|
||||
Affinity = archSpiritDef.Affinity.ToString(),
|
||||
Rarity = archSpiritDef.Rarity.ToString(),
|
||||
MaxHealth = archSpiritDef.MaxHealth,
|
||||
CurrentHealth = archSpiritDef.MaxHealth,
|
||||
MaxDefense = archSpiritDef.MaxDefense,
|
||||
CurrentDefense = archSpiritDef.MaxDefense,
|
||||
Damage = archSpiritDef.Damage,
|
||||
CanAttack = archSpiritDef.CanAttack ?? false,
|
||||
CanDefend = archSpiritDef.CanDefend ?? false,
|
||||
IsLeader = true,
|
||||
};
|
||||
|
||||
// Starting resources.
|
||||
ps.CurrentSp = ps.MaxSp;
|
||||
ps.CurrentSt = ps.MaxSt;
|
||||
|
||||
return ps;
|
||||
}
|
||||
|
||||
private static CardInstance DefinitionToInstance(CardDefinition def)
|
||||
=> new()
|
||||
{
|
||||
InstanceId = Guid.NewGuid().ToString("N")[..8],
|
||||
CardDefinitionId = def.Id,
|
||||
Name = def.Name,
|
||||
CardType = def.CardType.ToString(),
|
||||
Affinity = def.Affinity.ToString(),
|
||||
Rarity = def.Rarity.ToString(),
|
||||
SpCost = def.SpCost,
|
||||
StCost = def.StCost,
|
||||
MaxHealth = def.MaxHealth,
|
||||
CurrentHealth = def.MaxHealth,
|
||||
MaxDefense = def.MaxDefense,
|
||||
CurrentDefense = def.MaxDefense,
|
||||
Damage = def.Damage,
|
||||
CanAttack = def.CanAttack ?? false,
|
||||
CanDefend = def.CanDefend ?? false,
|
||||
};
|
||||
|
||||
private static void DrawCards(PlayerState player, int count)
|
||||
{
|
||||
for (int i = 0; i < count && player.Deck.Count > 0; i++)
|
||||
{
|
||||
var card = player.Deck[0];
|
||||
player.Deck.RemoveAt(0);
|
||||
player.Hand.Add(card);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplyDamage(CardInstance target, int damage)
|
||||
{
|
||||
if (target.CurrentDefense > 0)
|
||||
{
|
||||
var defVal = target.CurrentDefense.GetValueOrDefault();
|
||||
var overflow = damage - defVal;
|
||||
target.CurrentDefense = Math.Max(0, defVal - damage);
|
||||
if (overflow > 0 && target.CurrentHealth.HasValue)
|
||||
target.CurrentHealth = Math.Max(0, target.CurrentHealth.Value - overflow);
|
||||
}
|
||||
else if (target.CurrentHealth.HasValue)
|
||||
{
|
||||
target.CurrentHealth = Math.Max(0, target.CurrentHealth.Value - damage);
|
||||
}
|
||||
}
|
||||
|
||||
private static void MoveToGraveyard(PlayerState player, FieldCard card)
|
||||
{
|
||||
player.Field.Remove(card);
|
||||
player.Graveyard.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;
|
||||
|
||||
throw new GameException("CARD_NOT_ON_FIELD");
|
||||
}
|
||||
|
||||
private static string GetOpponentId(GameState state, string actorId)
|
||||
=> state.Players.Keys.First(k => k != actorId);
|
||||
|
||||
private static void ValidateActivePlayer(GameState state, string actorId)
|
||||
{
|
||||
if (state.ActivePlayerAccountId != actorId)
|
||||
throw new GameException("NOT_YOUR_TURN");
|
||||
}
|
||||
|
||||
private static void ValidatePhase(GameState state, params GamePhase[] allowed)
|
||||
{
|
||||
if (!allowed.Contains(state.Phase))
|
||||
throw new GameException($"INVALID_PHASE:{state.Phase}");
|
||||
}
|
||||
|
||||
private static CardInstanceDto ToCardDto(CardInstance c)
|
||||
=> new(
|
||||
InstanceId : c.InstanceId,
|
||||
CardDefinitionId : c.CardDefinitionId,
|
||||
Name : c.Name,
|
||||
CardType : c.CardType,
|
||||
Affinity : c.Affinity,
|
||||
Rarity : c.Rarity,
|
||||
CurrentHealth : c.CurrentHealth,
|
||||
MaxHealth : c.MaxHealth,
|
||||
CurrentDefense : c.CurrentDefense,
|
||||
MaxDefense : c.MaxDefense,
|
||||
Damage : c.Damage,
|
||||
IsExhausted : c.IsExhausted,
|
||||
IsEntrySick : c.IsEntrySick,
|
||||
IsLeader : c is FieldCard fc && fc.IsLeader);
|
||||
}
|
||||
|
||||
/// <summary>Game-rule violation — maps to a client error code.</summary>
|
||||
public sealed class GameException : Exception
|
||||
{
|
||||
public string ErrorCode { get; }
|
||||
public GameException(string code) : base(code) => ErrorCode = code;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
// ── Requests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Signal that the player has loaded the game screen and is ready to start.</summary>
|
||||
public sealed record GameReadyRequest(Guid SessionId);
|
||||
|
||||
/// <summary>Request the current (filtered) game state for the caller.</summary>
|
||||
public sealed record GameGetStateRequest(Guid SessionId);
|
||||
|
||||
/// <summary>Draw a card from the player's deck.</summary>
|
||||
public sealed record GameDrawRequest(Guid SessionId);
|
||||
|
||||
/// <summary>Play a card from hand onto the field.</summary>
|
||||
public sealed record GamePlayCardRequest(Guid SessionId, string CardInstanceId);
|
||||
|
||||
/// <summary>Attack an opponent card (or their ArchSpirit) with one of your field cards.</summary>
|
||||
public sealed record GameAttackRequest(
|
||||
Guid SessionId,
|
||||
string AttackerInstanceId,
|
||||
string TargetInstanceId);
|
||||
|
||||
/// <summary>End the active player's turn.</summary>
|
||||
public sealed record GameEndTurnRequest(Guid SessionId);
|
||||
|
||||
/// <summary>Concede the game (forfeit).</summary>
|
||||
public sealed record GameConcedeRequest(Guid SessionId);
|
||||
|
||||
// ── Responses ─────────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed record GameReadyResponse(Guid SessionId, string Status);
|
||||
// Status: "WaitingForOpponent" | "Started"
|
||||
|
||||
public sealed record GameGetStateResponse(GameStateDto State);
|
||||
|
||||
public sealed record GameDrawResponse(GameStateDto State);
|
||||
|
||||
public sealed record GamePlayCardResponse(GameStateDto State);
|
||||
|
||||
public sealed record GameAttackResponse(GameStateDto State);
|
||||
|
||||
public sealed record GameEndTurnResponse(GameStateDto State);
|
||||
|
||||
public sealed record GameConcedeResponse(GameStateDto State);
|
||||
|
||||
// ── Server Pushes ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to both players after any game action that changes state.
|
||||
/// Each player receives a version filtered for their perspective
|
||||
/// (opponent hand/deck contents are hidden).
|
||||
/// </summary>
|
||||
public sealed record GameStateUpdatePush(GameStateDto State);
|
||||
|
||||
/// <summary>Pushed to both players when the game ends.</summary>
|
||||
public sealed record GameOverPush(
|
||||
Guid SessionId,
|
||||
Guid WinnerAccountId,
|
||||
Guid LoserAccountId,
|
||||
string WinCondition, // "health" | "concede" | "disconnect"
|
||||
int WinnerRankDelta,
|
||||
int LoserRankDelta);
|
||||
|
||||
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Client-facing game state — opponent's private zones (hand, deck) are filtered.
|
||||
/// </summary>
|
||||
public sealed record GameStateDto(
|
||||
Guid SessionId,
|
||||
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 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);
|
||||
|
||||
public sealed record CardInstanceDto(
|
||||
string InstanceId,
|
||||
Guid CardDefinitionId,
|
||||
string Name,
|
||||
string CardType,
|
||||
string Affinity,
|
||||
string Rarity,
|
||||
int? CurrentHealth,
|
||||
int? MaxHealth,
|
||||
int? CurrentDefense,
|
||||
int? MaxDefense,
|
||||
int? Damage,
|
||||
bool IsExhausted,
|
||||
bool IsEntrySick,
|
||||
bool IsLeader); // true for the ArchSpirit
|
||||
@@ -0,0 +1,102 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Full live game state — serialized as JSONB in GameSession.StateJson.
|
||||
/// The GameEngine owns all mutations; handlers call into it exclusively.
|
||||
/// </summary>
|
||||
public sealed class GameState
|
||||
{
|
||||
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;
|
||||
|
||||
/// <summary>Per-player state, keyed by AccountId.ToString().</summary>
|
||||
public Dictionary<string, PlayerState> Players { get; set; } = new();
|
||||
|
||||
/// <summary>Running sequence number for action log entries.</summary>
|
||||
public int NextActionSequence { get; set; } = 1;
|
||||
}
|
||||
|
||||
public sealed class PlayerState
|
||||
{
|
||||
public string AccountId { get; set; } = string.Empty;
|
||||
|
||||
// ── 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();
|
||||
|
||||
// ── Resources ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Spirit points available this turn.</summary>
|
||||
public int CurrentSp { get; set; }
|
||||
public int MaxSp { get; set; } = 5;
|
||||
|
||||
/// <summary>Stone points available this turn.</summary>
|
||||
public int CurrentSt { get; set; }
|
||||
public int MaxSt { get; set; } = 5;
|
||||
|
||||
// ── Leader ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The player's ArchSpirit — starts on the field at game start.
|
||||
/// If destroyed the game ends (this player loses).
|
||||
/// </summary>
|
||||
public FieldCard? ArchSpirit { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A card instance in play. Carries mutable combat state.
|
||||
/// </summary>
|
||||
public class CardInstance
|
||||
{
|
||||
/// <summary>Unique instance ID within the game session (not a DB id).</summary>
|
||||
public string InstanceId { get; set; } = Guid.NewGuid().ToString("N")[..8];
|
||||
|
||||
// ── Definition mirror (denormalized for performance) ─────────────────────
|
||||
|
||||
public Guid CardDefinitionId { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string CardType { get; set; } = string.Empty;
|
||||
public string Affinity { get; set; } = string.Empty;
|
||||
public string Rarity { get; set; } = string.Empty;
|
||||
public int SpCost { get; set; }
|
||||
public int StCost { get; set; }
|
||||
|
||||
// ── Combat stats ─────────────────────────────────────────────────────────
|
||||
|
||||
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; }
|
||||
|
||||
// ── 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-only flags ─────────────────────────────────────────────────────
|
||||
|
||||
public bool CanAttack { get; set; }
|
||||
public bool CanDefend { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A CardInstance that is on the field (includes the ArchSpirit leader).
|
||||
/// </summary>
|
||||
public sealed class FieldCard : CardInstance
|
||||
{
|
||||
/// <summary>True for the player's starting ArchSpirit (the win-condition target).</summary>
|
||||
public bool IsLeader { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.attack — active player attacks with one of their field cards.
|
||||
/// </summary>
|
||||
internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameAttackHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
SorIdentityDbContext identityDb,
|
||||
IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_identityDb = identityDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.attack";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameAttackRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
|
||||
var (newState, gameOver) = GameEngine.Attack(
|
||||
state, actorId, req.AttackerInstanceId, req.TargetInstanceId);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.attack",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
if (gameOver)
|
||||
{
|
||||
// The attacking player destroyed the opponent's ArchSpirit.
|
||||
var loserId = session.PlayerOneAccountId.ToString() == actorId
|
||||
? session.PlayerTwoAccountId
|
||||
: session.PlayerOneAccountId;
|
||||
|
||||
await FinalizeGameAsync(
|
||||
_gameDb, _identityDb, _clientPush,
|
||||
session,
|
||||
winnerAccountId: Guid.Parse(actorId),
|
||||
loserAccountId: loserId,
|
||||
winCondition: "health",
|
||||
ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
|
||||
}
|
||||
|
||||
return ServerMessage.Reply("game.attack.ack", message.Seq,
|
||||
new GameAttackResponse(GameEngine.ToDto(newState, actorId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.concede — the calling player forfeits the match.
|
||||
/// </summary>
|
||||
internal sealed class GameConcedeHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameConcedeHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
SorIdentityDbContext identityDb,
|
||||
IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_identityDb = identityDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.concede";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameConcedeRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
var newState = GameEngine.Concede(state, actorId);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.concede",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
var winnerId = session.PlayerOneAccountId.ToString() == actorId
|
||||
? session.PlayerTwoAccountId
|
||||
: session.PlayerOneAccountId;
|
||||
|
||||
await FinalizeGameAsync(
|
||||
_gameDb, _identityDb, _clientPush,
|
||||
session,
|
||||
winnerAccountId: winnerId,
|
||||
loserAccountId: Guid.Parse(actorId),
|
||||
winCondition: "concede",
|
||||
ct);
|
||||
|
||||
return ServerMessage.Reply("game.concede.ack", message.Seq,
|
||||
new GameConcedeResponse(GameEngine.ToDto(newState, actorId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.draw — active player draws a card from their deck.
|
||||
/// </summary>
|
||||
internal sealed class GameDrawHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameDrawHandler(IMessageSerializer serializer, GameDbContext gameDb, IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.draw";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameDrawRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
|
||||
var (newState, drawn) = GameEngine.Draw(state, actorId);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.draw",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
|
||||
|
||||
return ServerMessage.Reply("game.draw.ack", message.Seq,
|
||||
new GameDrawResponse(GameEngine.ToDto(newState, actorId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.end_turn — active player ends their turn.
|
||||
/// </summary>
|
||||
internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameEndTurnHandler(IMessageSerializer serializer, GameDbContext gameDb, IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.end_turn";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameEndTurnRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
var newState = GameEngine.EndTurn(state, actorId);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.end_turn",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
|
||||
|
||||
return ServerMessage.Reply("game.end_turn.ack", message.Seq,
|
||||
new GameEndTurnResponse(GameEngine.ToDto(newState, actorId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.get_state — returns the current game state filtered for the caller's perspective.
|
||||
/// Useful for reconnects or initial load.
|
||||
/// </summary>
|
||||
internal sealed class GameGetStateHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public GameGetStateHandler(IMessageSerializer serializer, GameDbContext gameDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "game.get_state";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameGetStateRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
|
||||
if (session.StateJson == null)
|
||||
throw new GameException("STATE_NOT_INITIALIZED");
|
||||
|
||||
var state = GameEngine.Deserialize(session.StateJson);
|
||||
|
||||
return ServerMessage.Reply("game.get_state.ack", message.Seq,
|
||||
new GameGetStateResponse(GameEngine.ToDto(state, actorId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Shared helpers for all game message handlers.
|
||||
/// </summary>
|
||||
internal abstract class GameHandlerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Load and validate an active game session for the calling player.
|
||||
/// Throws GameException on any validation failure.
|
||||
/// </summary>
|
||||
protected static async Task<GameSession> LoadActiveSessionAsync(
|
||||
GameDbContext gameDb,
|
||||
Guid sessionId,
|
||||
string actorId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var session = await gameDb.GameSessions.FindAsync([sessionId], ct)
|
||||
?? throw new GameException("SESSION_NOT_FOUND");
|
||||
|
||||
if (session.PlayerOneAccountId.ToString() != actorId &&
|
||||
session.PlayerTwoAccountId.ToString() != actorId)
|
||||
throw new GameException("NOT_IN_SESSION");
|
||||
|
||||
if (session.Status != GameSessionStatus.Active)
|
||||
throw new GameException("SESSION_NOT_ACTIVE");
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persist the updated state JSON and append an action log entry.
|
||||
/// </summary>
|
||||
protected static async Task SaveStateAsync(
|
||||
GameDbContext gameDb,
|
||||
GameSession session,
|
||||
GameState state,
|
||||
string actorId,
|
||||
string actionType,
|
||||
string? payloadJson,
|
||||
CancellationToken ct)
|
||||
{
|
||||
session.StateJson = GameEngine.Serialize(state);
|
||||
|
||||
var seqNum = state.NextActionSequence++;
|
||||
gameDb.ActionLogs.Add(new GameActionLog
|
||||
{
|
||||
GameSessionId = session.Id,
|
||||
ActorAccountId = Guid.Parse(actorId),
|
||||
ActionType = actionType,
|
||||
PayloadJson = payloadJson,
|
||||
SequenceNumber = seqNum,
|
||||
OccurredAt = DateTimeOffset.UtcNow,
|
||||
});
|
||||
|
||||
await gameDb.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Push the updated (filtered) game state to both players.
|
||||
/// </summary>
|
||||
protected static async Task PushStateToPlayersAsync(
|
||||
IClientPush clientPush,
|
||||
GameSession session,
|
||||
GameState state,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var p1Id = session.PlayerOneAccountId.ToString();
|
||||
var p2Id = session.PlayerTwoAccountId.ToString();
|
||||
|
||||
await Task.WhenAll(
|
||||
clientPush.PushAsync(p1Id,
|
||||
ServerMessage.Push("game.state_update",
|
||||
new GameStateUpdatePush(GameEngine.ToDto(state, p1Id))), ct),
|
||||
clientPush.PushAsync(p2Id,
|
||||
ServerMessage.Push("game.state_update",
|
||||
new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finalize a completed game: update session status, adjust ELO ranks,
|
||||
/// push game-over to both players.
|
||||
/// </summary>
|
||||
protected static async Task FinalizeGameAsync(
|
||||
GameDbContext gameDb,
|
||||
SorIdentityDbContext identityDb,
|
||||
IClientPush clientPush,
|
||||
GameSession session,
|
||||
Guid winnerAccountId,
|
||||
Guid loserAccountId,
|
||||
string winCondition,
|
||||
CancellationToken ct)
|
||||
{
|
||||
session.Status = GameSessionStatus.Completed;
|
||||
session.WinnerAccountId = winnerAccountId;
|
||||
session.WinCondition = winCondition;
|
||||
session.EndedAt = DateTimeOffset.UtcNow;
|
||||
|
||||
// Load both accounts for ELO adjustment.
|
||||
var accounts = await identityDb.Users
|
||||
.Where(a => a.Id == winnerAccountId || a.Id == loserAccountId)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var winner = accounts.First(a => a.Id == winnerAccountId);
|
||||
var loser = accounts.First(a => a.Id == loserAccountId);
|
||||
|
||||
var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winner.RankScore, loser.RankScore);
|
||||
|
||||
winner.RankScore += winnerDelta;
|
||||
loser.RankScore = Math.Max(0, loser.RankScore - loserDelta);
|
||||
|
||||
await identityDb.SaveChangesAsync(ct);
|
||||
await gameDb.SaveChangesAsync(ct);
|
||||
|
||||
var push = new GameOverPush(
|
||||
SessionId : session.Id,
|
||||
WinnerAccountId : winnerAccountId,
|
||||
LoserAccountId : loserAccountId,
|
||||
WinCondition : winCondition,
|
||||
WinnerRankDelta : winnerDelta,
|
||||
LoserRankDelta : loserDelta);
|
||||
|
||||
await Task.WhenAll(
|
||||
clientPush.PushAsync(winnerAccountId.ToString(),
|
||||
ServerMessage.Push("game.over", push), ct),
|
||||
clientPush.PushAsync(loserAccountId.ToString(),
|
||||
ServerMessage.Push("game.over", push), ct));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.play_card — active player plays a card from their hand onto the field.
|
||||
/// </summary>
|
||||
internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GamePlayCardHandler(IMessageSerializer serializer, GameDbContext gameDb, IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.play_card";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GamePlayCardRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var state = GameEngine.Deserialize(session.StateJson!);
|
||||
var newState = GameEngine.PlayCard(state, actorId, req.CardInstanceId);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.play_card",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct);
|
||||
|
||||
return ServerMessage.Reply("game.play_card.ack", message.Seq,
|
||||
new GamePlayCardResponse(GameEngine.ToDto(newState, actorId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Catalog;
|
||||
using SOR.Database.Entities.Collection;
|
||||
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.ready — player signals they are on the game screen and ready to start.
|
||||
///
|
||||
/// When BOTH players have sent ready, the game state is initialized and
|
||||
/// pushed to both clients.
|
||||
/// </summary>
|
||||
internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly CollectionDbContext _collectionDb;
|
||||
private readonly CatalogDbContext _catalogDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameReadyHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
CollectionDbContext collectionDb,
|
||||
CatalogDbContext catalogDb,
|
||||
IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_collectionDb = collectionDb;
|
||||
_catalogDb = catalogDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.ready";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameReadyRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var session = await _gameDb.GameSessions.FindAsync([req.SessionId], ct)
|
||||
?? throw new GameException("SESSION_NOT_FOUND");
|
||||
|
||||
if (session.PlayerOneAccountId != accountId && session.PlayerTwoAccountId != accountId)
|
||||
throw new GameException("NOT_IN_SESSION");
|
||||
|
||||
if (session.Status == GameSessionStatus.Active)
|
||||
return ServerMessage.Reply("game.ready.ack", message.Seq,
|
||||
new GameReadyResponse(session.Id, "AlreadyStarted"));
|
||||
|
||||
if (session.Status != GameSessionStatus.Initializing)
|
||||
throw new GameException("SESSION_NOT_INITIALIZING");
|
||||
|
||||
// Mark this player ready.
|
||||
if (session.PlayerOneAccountId == accountId) session.PlayerOneReady = true;
|
||||
else session.PlayerTwoReady = true;
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
if (!session.PlayerOneReady || !session.PlayerTwoReady)
|
||||
{
|
||||
return ServerMessage.Reply("game.ready.ack", message.Seq,
|
||||
new GameReadyResponse(session.Id, "WaitingForOpponent"));
|
||||
}
|
||||
|
||||
// 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 state = GameEngine.Initialize(
|
||||
session.Id,
|
||||
session.PlayerOneAccountId, p1DeckCards, session.PlayerOneDeckId, p1ArchSpirit,
|
||||
session.PlayerTwoAccountId, p2DeckCards, session.PlayerTwoDeckId, p2ArchSpirit);
|
||||
|
||||
session.StateJson = GameEngine.Serialize(state);
|
||||
session.Status = GameSessionStatus.Active;
|
||||
session.StartedAt = DateTimeOffset.UtcNow;
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
// Push initial state to both players.
|
||||
await PushStateToPlayersAsync(_clientPush, session, state, ct);
|
||||
|
||||
return ServerMessage.Reply("game.ready.ack", message.Seq,
|
||||
new GameReadyResponse(session.Id, "Started"));
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private async Task<IEnumerable<(CardDefinition, int)>> LoadDeckCardsAsync(Guid deckId, CancellationToken ct)
|
||||
{
|
||||
var deck = await _collectionDb.Decks
|
||||
.AsNoTracking()
|
||||
.Include(d => d.Cards)
|
||||
.FirstOrDefaultAsync(d => d.Id == deckId, ct)
|
||||
?? throw new GameException("DECK_NOT_FOUND");
|
||||
|
||||
var defIds = deck.Cards.Select(c => c.CardDefinitionId).ToList();
|
||||
var defs = await _catalogDb.Set<CardDefinition>()
|
||||
.AsNoTracking()
|
||||
.Where(d => defIds.Contains(d.Id))
|
||||
.ToDictionaryAsync(d => d.Id, ct);
|
||||
|
||||
return deck.Cards
|
||||
.Where(c => defs.ContainsKey(c.CardDefinitionId))
|
||||
.Select(c => (defs[c.CardDefinitionId], c.Quantity));
|
||||
}
|
||||
|
||||
private async Task<CardDefinition> LoadDeckArchSpiritAsync(Guid deckId, CancellationToken ct)
|
||||
{
|
||||
var deck = await _collectionDb.Decks
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(d => d.Id == deckId, ct)
|
||||
?? throw new GameException("DECK_NOT_FOUND");
|
||||
|
||||
if (deck.ArchSpiritCardDefinitionId == Guid.Empty)
|
||||
throw new GameException("DECK_HAS_NO_ARCH_SPIRIT");
|
||||
|
||||
return await _catalogDb.Set<CardDefinition>()
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(d => d.Id == deck.ArchSpiritCardDefinitionId, ct)
|
||||
?? throw new GameException("ARCH_SPIRIT_DEFINITION_NOT_FOUND");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Game</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Database;
|
||||
using SOR.Game.Handlers;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Registers all game service components into the DI container.
|
||||
/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "game".
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
public static IServiceCollection AddGameService(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.AddGameDatabase(configuration);
|
||||
services.AddIdentityDatabase(configuration);
|
||||
services.AddCollectionDatabase(configuration);
|
||||
services.AddCatalogDatabase(configuration);
|
||||
|
||||
services.AddTransient<IMessageHandler, GameReadyHandler>();
|
||||
services.AddTransient<IMessageHandler, GameGetStateHandler>();
|
||||
services.AddTransient<IMessageHandler, GameDrawHandler>();
|
||||
services.AddTransient<IMessageHandler, GamePlayCardHandler>();
|
||||
services.AddTransient<IMessageHandler, GameAttackHandler>();
|
||||
services.AddTransient<IMessageHandler, GameEndTurnHandler>();
|
||||
services.AddTransient<IMessageHandler, GameConcedeHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,9 @@ using SOR.Bazaar;
|
||||
using SOR.Chat;
|
||||
using SOR.Collection;
|
||||
using SOR.Content;
|
||||
using SOR.Game;
|
||||
using SOR.Gateway;
|
||||
using SOR.Matchmaking;
|
||||
using SOR.Versioning;
|
||||
using SOR.Networking.Nats;
|
||||
using SOR.Networking.Redis;
|
||||
@@ -140,6 +142,8 @@ if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configur
|
||||
if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
|
||||
if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration);
|
||||
if (IsEnabled("versioning")) builder.Services.AddVersioningService(builder.Configuration);
|
||||
if (IsEnabled("matchmaking")) builder.Services.AddMatchmakingService(builder.Configuration);
|
||||
if (IsEnabled("game")) builder.Services.AddGameService(builder.Configuration);
|
||||
|
||||
// TODO: Uncomment as each service is implemented:
|
||||
// if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
|
||||
|
||||
@@ -34,5 +34,7 @@
|
||||
<ProjectReference Include="..\SOR.Bazaar\SOR.Bazaar.csproj" />
|
||||
<ProjectReference Include="..\SOR.Content\SOR.Content.csproj" />
|
||||
<ProjectReference Include="..\SOR.Versioning\SOR.Versioning.csproj" />
|
||||
<ProjectReference Include="..\SOR.Matchmaking\SOR.Matchmaking.csproj" />
|
||||
<ProjectReference Include="..\SOR.Game\SOR.Game.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
namespace SOR.Matchmaking.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>
|
||||
/// matchmaking.status — returns the caller's current queue status.
|
||||
/// </summary>
|
||||
internal sealed class MatchmakingGetStatusHandler : IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public MatchmakingGetStatusHandler(IMessageSerializer serializer, GameDbContext gameDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "matchmaking.status";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var entry = await _gameDb.MatchmakingEntries
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(
|
||||
e => e.AccountId == accountId && e.Status == MatchmakingStatus.Searching,
|
||||
ct);
|
||||
|
||||
return ServerMessage.Reply("matchmaking.status.ack", message.Seq,
|
||||
entry == null
|
||||
? new GetQueueStatusResponse(false, null, null, null)
|
||||
: new GetQueueStatusResponse(true, entry.Id, entry.RankScore, entry.JoinedAt));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace SOR.Matchmaking.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Entities.Identity;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// matchmaking.join — places the authenticated player in the matchmaking queue.
|
||||
/// Idempotent: if already searching, returns the existing entry with "AlreadyQueued".
|
||||
/// </summary>
|
||||
internal sealed class MatchmakingJoinHandler : IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
|
||||
public MatchmakingJoinHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
SorIdentityDbContext identityDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_identityDb = identityDb;
|
||||
}
|
||||
|
||||
public string MessageType => "matchmaking.join";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<JoinQueueRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
// Check for an existing active queue entry.
|
||||
var existing = await _gameDb.MatchmakingEntries
|
||||
.FirstOrDefaultAsync(
|
||||
e => e.AccountId == accountId && e.Status == MatchmakingStatus.Searching,
|
||||
ct);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
return ServerMessage.Reply("matchmaking.join.ack", message.Seq,
|
||||
new JoinQueueResponse(existing.Id, existing.RankScore, "AlreadyQueued"));
|
||||
}
|
||||
|
||||
// Fetch current rank score.
|
||||
var account = await _identityDb.Set<Account>()
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(a => a.Id == accountId, ct);
|
||||
|
||||
var rankScore = account?.RankScore ?? 1000;
|
||||
|
||||
var entry = new MatchmakingEntry
|
||||
{
|
||||
AccountId = accountId,
|
||||
DeckId = req.DeckId,
|
||||
RankScore = rankScore,
|
||||
Status = MatchmakingStatus.Searching,
|
||||
JoinedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
_gameDb.MatchmakingEntries.Add(entry);
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
return ServerMessage.Reply("matchmaking.join.ack", message.Seq,
|
||||
new JoinQueueResponse(entry.Id, rankScore, "Searching"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace SOR.Matchmaking.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>
|
||||
/// matchmaking.leave — removes the authenticated player from the matchmaking queue.
|
||||
/// </summary>
|
||||
internal sealed class MatchmakingLeaveHandler : IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
|
||||
public MatchmakingLeaveHandler(IMessageSerializer serializer, GameDbContext gameDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
}
|
||||
|
||||
public string MessageType => "matchmaking.leave";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var entry = await _gameDb.MatchmakingEntries
|
||||
.FirstOrDefaultAsync(
|
||||
e => e.AccountId == accountId && e.Status == MatchmakingStatus.Searching,
|
||||
ct);
|
||||
|
||||
if (entry == null)
|
||||
{
|
||||
return ServerMessage.Reply("matchmaking.leave.ack", message.Seq,
|
||||
new LeaveQueueResponse(Cancelled: false));
|
||||
}
|
||||
|
||||
entry.Status = MatchmakingStatus.Cancelled;
|
||||
entry.ResolvedAt = DateTimeOffset.UtcNow;
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
return ServerMessage.Reply("matchmaking.leave.ack", message.Seq,
|
||||
new LeaveQueueResponse(Cancelled: true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
namespace SOR.Matchmaking;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Entities.Identity;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Background service that polls the matchmaking queue every 5 seconds and pairs
|
||||
/// players using ELO-based range matching.
|
||||
///
|
||||
/// Matching algorithm:
|
||||
/// - Initial search range: ±100 rank score.
|
||||
/// - Range expands by ±100 every 30 seconds in queue, capping at ±500.
|
||||
/// - Picks the closest-ranked opponent within the current range.
|
||||
/// - On match: creates a GameSession, updates both MatchmakingEntry records,
|
||||
/// then pushes MatchFoundPush to both players via IClientPush.
|
||||
/// </summary>
|
||||
internal sealed class MatchmakerService : BackgroundService
|
||||
{
|
||||
private const int PollIntervalMs = 5_000;
|
||||
private const int InitialRange = 100;
|
||||
private const int RangeExpandStep = 100;
|
||||
private const int MaxRange = 500;
|
||||
private const int ExpandEverySeconds = 30;
|
||||
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger<MatchmakerService> _logger;
|
||||
|
||||
public MatchmakerService(IServiceScopeFactory scopeFactory, ILogger<MatchmakerService> logger)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_logger.LogInformation("MatchmakerService started.");
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await TickAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogError(ex, "Error in matchmaker tick.");
|
||||
}
|
||||
|
||||
await Task.Delay(PollIntervalMs, stoppingToken);
|
||||
}
|
||||
|
||||
_logger.LogInformation("MatchmakerService stopped.");
|
||||
}
|
||||
|
||||
private async Task TickAsync(CancellationToken ct)
|
||||
{
|
||||
await using var scope = _scopeFactory.CreateAsyncScope();
|
||||
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
var identityDb = scope.ServiceProvider.GetRequiredService<SorIdentityDbContext>();
|
||||
var clientPush = scope.ServiceProvider.GetRequiredService<IClientPush>();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
// Load all searching entries, ordered by wait time (longest waiting first).
|
||||
var entries = await gameDb.MatchmakingEntries
|
||||
.Where(e => e.Status == MatchmakingStatus.Searching)
|
||||
.OrderBy(e => e.JoinedAt)
|
||||
.ToListAsync(ct);
|
||||
|
||||
if (entries.Count < 2)
|
||||
return;
|
||||
|
||||
var matched = new HashSet<Guid>(); // entry IDs already paired this tick
|
||||
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (matched.Contains(entry.Id))
|
||||
continue;
|
||||
|
||||
var waitSeconds = (now - entry.JoinedAt).TotalSeconds;
|
||||
var expansions = (int)(waitSeconds / ExpandEverySeconds);
|
||||
var range = Math.Min(InitialRange + expansions * RangeExpandStep, MaxRange);
|
||||
|
||||
// Find closest opponent not already paired.
|
||||
var opponent = entries
|
||||
.Where(e => e.Id != entry.Id
|
||||
&& !matched.Contains(e.Id)
|
||||
&& Math.Abs(e.RankScore - entry.RankScore) <= range)
|
||||
.OrderBy(e => Math.Abs(e.RankScore - entry.RankScore))
|
||||
.ThenBy(e => e.JoinedAt)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (opponent == null)
|
||||
continue;
|
||||
|
||||
// Create a game session.
|
||||
var session = new GameSession
|
||||
{
|
||||
PlayerOneAccountId = entry.AccountId,
|
||||
PlayerOneDeckId = entry.DeckId,
|
||||
PlayerTwoAccountId = opponent.AccountId,
|
||||
PlayerTwoDeckId = opponent.DeckId,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = now,
|
||||
};
|
||||
|
||||
gameDb.GameSessions.Add(session);
|
||||
|
||||
entry.Status = MatchmakingStatus.Matched;
|
||||
entry.ResolvedAt = now;
|
||||
entry.MatchedGameSessionId = session.Id;
|
||||
|
||||
opponent.Status = MatchmakingStatus.Matched;
|
||||
opponent.ResolvedAt = now;
|
||||
opponent.MatchedGameSessionId = session.Id;
|
||||
|
||||
await gameDb.SaveChangesAsync(ct);
|
||||
|
||||
matched.Add(entry.Id);
|
||||
matched.Add(opponent.Id);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Match found: {A} vs {B} (session {S})",
|
||||
entry.AccountId, opponent.AccountId, session.Id);
|
||||
|
||||
// Fetch display names for the push payloads.
|
||||
var names = await identityDb.Set<Account>()
|
||||
.AsNoTracking()
|
||||
.Where(a => a.Id == entry.AccountId || a.Id == opponent.AccountId)
|
||||
.ToDictionaryAsync(a => a.Id, a => a.DisplayName ?? a.Email ?? a.Id.ToString(), ct);
|
||||
|
||||
names.TryGetValue(entry.AccountId, out var entryName);
|
||||
names.TryGetValue(opponent.AccountId, out var opponentName);
|
||||
|
||||
// Push to player one.
|
||||
await clientPush.PushAsync(
|
||||
entry.AccountId.ToString(),
|
||||
ServerMessage.Push("matchmaking.match_found",
|
||||
new MatchFoundPush(
|
||||
session.Id,
|
||||
opponent.AccountId,
|
||||
opponentName,
|
||||
opponent.RankScore)),
|
||||
ct);
|
||||
|
||||
// Push to player two.
|
||||
await clientPush.PushAsync(
|
||||
opponent.AccountId.ToString(),
|
||||
ServerMessage.Push("matchmaking.match_found",
|
||||
new MatchFoundPush(
|
||||
session.Id,
|
||||
entry.AccountId,
|
||||
entryName,
|
||||
entry.RankScore)),
|
||||
ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace SOR.Matchmaking;
|
||||
|
||||
// ── Requests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Join the matchmaking queue with a specific deck.
|
||||
/// </summary>
|
||||
public sealed record JoinQueueRequest(Guid DeckId);
|
||||
|
||||
/// <summary>
|
||||
/// Leave the matchmaking queue (cancel search).
|
||||
/// </summary>
|
||||
public sealed record LeaveQueueRequest;
|
||||
|
||||
/// <summary>
|
||||
/// Get the caller's current matchmaking status.
|
||||
/// </summary>
|
||||
public sealed record GetQueueStatusRequest;
|
||||
|
||||
// ── Responses ─────────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed record JoinQueueResponse(
|
||||
Guid EntryId,
|
||||
int RankScore,
|
||||
string Status); // "Searching" | "AlreadyQueued"
|
||||
|
||||
public sealed record LeaveQueueResponse(bool Cancelled);
|
||||
|
||||
public sealed record GetQueueStatusResponse(
|
||||
bool IsInQueue,
|
||||
Guid? EntryId,
|
||||
int? RankScore,
|
||||
DateTimeOffset? JoinedAt);
|
||||
|
||||
// ── Server Pushes (unsolicited) ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to both players when a match is found.
|
||||
/// Clients should navigate to the game screen and send game.ready.
|
||||
/// </summary>
|
||||
public sealed record MatchFoundPush(
|
||||
Guid GameSessionId,
|
||||
Guid OpponentAccountId,
|
||||
string? OpponentDisplayName,
|
||||
int OpponentRankScore);
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Matchmaking</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace SOR.Matchmaking;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Database;
|
||||
using SOR.Matchmaking.Handlers;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Registers all matchmaking service components into the DI container.
|
||||
/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "matchmaking".
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
public static IServiceCollection AddMatchmakingService(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.AddGameDatabase(configuration);
|
||||
services.AddIdentityDatabase(configuration);
|
||||
|
||||
services.AddTransient<IMessageHandler, MatchmakingJoinHandler>();
|
||||
services.AddTransient<IMessageHandler, MatchmakingLeaveHandler>();
|
||||
services.AddTransient<IMessageHandler, MatchmakingGetStatusHandler>();
|
||||
|
||||
// Background service that continuously polls the queue and pairs players.
|
||||
services.AddHostedService<MatchmakerService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user