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:
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user