Files
sor/Server/src/SOR.Game/Handlers/GameHandlerBase.cs
T
dingoandClaude Fable 5 4961696fee Ability system: zone-scope card picks, target-pick prompts, builder filter editor, tests
Server engine (SOR.Game):
- Zone-scope card targets (Hand/Deck/Discard/AnyZone) pause with a server-
  enumerated candidates list (PendingTargetPick.CandidatesJson) instead of
  failing when the client submits player accountIds for hidden zones
- Missing mandatory target picks now prompt (PendingTargetPick) rather than
  throwing INSUFFICIENT_TARGETS; all post-pick resume flows run with
  requireClientTargets so actions never silently auto-hit the first candidate
- ChannelCardFromZone: Filters + InOwn/InTargetChannelRange enforced via shared
  IsWithinChannelConstraints (incl. player-picked tile validation)
- TakeControl duration reversal via internal __ReturnControl effect; board
  occupant-owner kept in sync both ways
- TrackedDuration gains SourceOwnerAccountId (UntilStartOfSourceOwnerTurn now
  anchors correctly) and IsAura (aura reapply no longer strips unrelated buffs)
- RevealCards honours N for player targets; IsAllyTurn means teammate's turn;
  content-keyed ParseAbilities cache; AbilityValidator for save-time linting;
  duplicate PolyType attributes removed (converter reads base registry only)

Admin builder (AbilityBuilder/CardEditor):
- Full multi-filter editor (28 filter types with parameter fields) replacing
  the single param-less dropdown; raw-JSON ChooseOne editor per action
- Cost PickMode, TriggerLimitPerGame, SourceZoneGate inputs
- Save-time ability validation with error list (blocks invalid saves)

Client (Godot):
- Card-list picker for zone-scope target picks; OR/XOR-root abilities skip
  speculative upfront targeting; ally units included in team-aware highlight
  pools (Game.get_ally_units); state re-sync on rejected pick responses

Tests: new SOR.Game.Tests project (21 passing) covering the regression suite
from SOR.Abilities-Review-and-solutions.md §8 plus validator rules.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 06:23:17 -04:00

818 lines
34 KiB
C#

namespace SOR.Game.Handlers;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SOR.Game.Abilities;
using SOR.Database.Contexts;
using SOR.Database.Entities.Game;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Nats;
using SOR.Shared.Networking;
/// <summary>
/// Shared helpers for all game message handlers.
/// </summary>
internal abstract class GameHandlerBase
{
private static readonly JsonSerializerOptions AbilityJsonOptions = AbilitySystem.CreateJsonOptions();
/// <summary>
/// Load and validate an active game session for the calling player,
/// acquiring a row-level lock (SELECT FOR UPDATE) inside an explicit
/// transaction so that concurrent mutations to the same session are
/// serialized. The transaction is committed by <see cref="SaveStateAsync"/>.
/// Throws GameException on any validation failure.
/// </summary>
protected static async Task<GameSession> LoadActiveSessionAsync(
GameDbContext gameDb,
Guid sessionId,
string actorId,
CancellationToken ct)
{
// Begin a transaction so the FOR UPDATE lock is held until SaveStateAsync commits.
if (gameDb.Database.CurrentTransaction == null)
await gameDb.Database.BeginTransactionAsync(ct);
// Lock the row so concurrent handlers for the same session queue up.
var session = await gameDb.GameSessions
.FromSqlInterpolated(
$"""
SELECT * FROM game.game_sessions
WHERE "Id" = {sessionId}
FOR UPDATE
""")
.SingleOrDefaultAsync(ct)
?? throw new GameException("SESSION_NOT_FOUND");
bool isKnownPlayer = session.PlayerOneAccountId.ToString() == actorId ||
session.PlayerTwoAccountId.ToString() == actorId ||
(session.AdditionalPlayersJson != null &&
session.AdditionalPlayersJson.Contains(actorId));
if (!isKnownPlayer)
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,
/// then commit the transaction opened by <see cref="LoadActiveSessionAsync"/>.
/// </summary>
internal static async Task SaveStateAsync(
GameDbContext gameDb,
GameSession session,
GameState state,
string actorId,
string actionType,
string? payloadJson,
CancellationToken ct,
string? resultJson = null)
{
var seqNum = state.NextActionSequence++; // increment before serialize so the saved JSON reflects the consumed number
session.StateJson = GameEngine.Serialize(state);
session.LastActionAt = DateTimeOffset.UtcNow;
gameDb.ActionLogs.Add(new GameActionLog
{
GameSessionId = session.Id,
ActorAccountId = Guid.Parse(actorId),
ActionType = actionType,
PayloadJson = payloadJson,
ResultJson = resultJson,
SequenceNumber = seqNum,
OccurredAt = DateTimeOffset.UtcNow,
});
await gameDb.SaveChangesAsync(ct);
// Commit and release the FOR UPDATE lock.
if (gameDb.Database.CurrentTransaction != null)
await gameDb.Database.CommitTransactionAsync(ct);
}
/// <summary>
/// Broadcast a game activity event (session started / ended) to all subscribed clients.
/// Used by the live-star skybox feature. Best-effort; subscriber list is in-memory only.
/// </summary>
internal static async Task BroadcastActivityAsync(
IClientPush clientPush,
string eventType,
Guid sessionId,
CancellationToken ct)
{
var subs = GameActivityRegistry.Instance?.Subscribers;
if (subs is null || subs.Count == 0) return;
var push = ServerMessage.Push("game.activity",
new GameActivityPush(eventType, sessionId.ToString()));
await Task.WhenAll(subs.Select(uid => clientPush.PushAsync(uid, push, ct)));
}
// ── Visual push helpers ────────────────────────────────────────────────────
/// <summary>
/// Searches all players' Field lists and ArchSpirit slots for a unit with the
/// given instance ID. Returns null when not found.
/// </summary>
protected static CardInstance? FindSourceUnit(GameState state, string instanceId)
{
foreach (var player in state.Players.Values)
{
if (player.ArchSpirit?.InstanceId == instanceId)
return player.ArchSpirit;
var onField = player.Field.FirstOrDefault(c => c.InstanceId == instanceId);
if (onField is not null)
return onField;
}
return null;
}
/// <summary>
/// Derives the best visual targets for a Repentance card placeholder VFX.
/// Prefers explicit client targets (InstanceId / Coord); falls back to the
/// first live enemy ArchSpirit so the projectile always has a destination.
/// </summary>
protected static IReadOnlyList<AbilityTarget> ComputeVisualTargets(
IReadOnlyList<AbilityTarget>? clientTargets,
GameState state,
string actorId)
{
if (clientTargets is { Count: > 0 })
{
var usable = clientTargets
.Where(t => !string.IsNullOrEmpty(t.InstanceId) || t.Coord is not null)
.ToList();
if (usable.Count > 0) return usable;
}
var enemyArch = state.GetEnemyIds(actorId)
.Select(id => state.Players[id].ArchSpirit)
.FirstOrDefault(a => a is not null);
return enemyArch is not null
? [new AbilityTarget(ActionIndex: 0, InstanceId: enemyArch.InstanceId)]
: [];
}
/// <summary>
/// Derives the best visual targets for an Active ability placeholder VFX.
/// Self/ExactSelf-ownership and All-count abilities resolve to the source unit.
/// Other targetless cases fall back to the first live enemy ArchSpirit.
/// </summary>
protected static IReadOnlyList<AbilityTarget> ComputeAbilityVisualTargets(
IReadOnlyList<AbilityTarget>? clientTargets,
Abilities.Models.AbilityDefinition ability,
GameState state,
string actorId,
string sourceInstanceId)
{
if (clientTargets is { Count: > 0 })
{
var usable = clientTargets
.Where(t => !string.IsNullOrEmpty(t.InstanceId) || t.Coord is not null)
.ToList();
if (usable.Count > 0) return usable;
}
// Self/auto-resolved — point at the source unit.
var firstAction = GetFirstAction(ability);
if (firstAction is not null)
{
var own = firstAction.Target.Ownership;
if (own is Abilities.Models.TargetOwnership.Self
or Abilities.Models.TargetOwnership.ExactSelf
|| firstAction.Target.Count.All)
return [new AbilityTarget(ActionIndex: 0, InstanceId: sourceInstanceId)];
}
// External target absent: aim at first live enemy ArchSpirit.
var enemyArch = state.GetEnemyIds(actorId)
.Select(id => state.Players[id].ArchSpirit)
.FirstOrDefault(a => a is not null);
return enemyArch is not null
? [new AbilityTarget(ActionIndex: 0, InstanceId: enemyArch.InstanceId)]
: [];
}
/// <summary>
/// Derives the TargetMode string the client uses to choose its VFX behaviour.
/// </summary>
protected static string ComputeAbilityTargetMode(
IReadOnlyList<AbilityTarget> visualTargets,
GameState state,
string sourceInstanceId)
{
if (visualTargets.Count == 0) return "None";
var first = visualTargets[0];
if (first.Coord is not null) return "Tile";
var id = first.InstanceId ?? string.Empty;
if (id.Length == 0) return "None";
if (id == sourceInstanceId) return "Self";
if (state.Players.ContainsKey(id)) return "PlayerZone";
return "Unit";
}
// Returns the first concrete Action from an ability definition,
// checking ActionGroup before the legacy Actions array.
private static Abilities.Models.Action? GetFirstAction(
Abilities.Models.AbilityDefinition ability)
{
#pragma warning disable CS0618
if (ability.ActionGroup?.Actions is { Length: > 0 } ag) return ag[0];
if (ability.Actions is { Length: > 0 } lx) return lx[0];
#pragma warning restore CS0618
return null;
}
/// <summary>
/// Broadcast an arbitrary push message to all players and spectators in a session.
/// </summary>
internal static async Task BroadcastToAllViewersAsync(
IClientPush clientPush,
GameSession session,
ServerMessage push,
CancellationToken ct)
{
var allIds = GetAllPlayerIds(session);
var tasks = allIds.Select(pid => clientPush.PushAsync(pid, push, ct)).ToList<Task>();
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
foreach (var specId in await registry.GetSpectatorsAsync(session.Id))
tasks.Add(clientPush.PushAsync(specId.ToString(), push, ct));
}
await Task.WhenAll(tasks);
}
/// <summary>
/// Push the updated game state to both players and any current spectators.
/// When <paramref name="prevStateJson"/> is supplied a structured delta (<c>game.state_delta</c>)
/// is sent instead of the full state, reducing payload size.
/// Falls back to a full <c>game.state_update</c> push when prevStateJson is null.
/// IMPORTANT: prevStateJson must be captured from session.StateJson BEFORE SaveStateAsync
/// overwrites it and BEFORE the engine method mutates the state object.
/// </summary>
/// <summary>
/// Returns all player account-ID strings in the session: P1, P2, and any additional players
/// from AdditionalPlayersJson (seats 3+).
/// </summary>
private static List<string> GetAllPlayerIds(GameSession session)
{
var ids = new List<string>
{
session.PlayerOneAccountId.ToString(),
session.PlayerTwoAccountId.ToString(),
};
if (!string.IsNullOrEmpty(session.AdditionalPlayersJson))
{
try
{
var addl = JsonSerializer.Deserialize<List<AdditionalPlayerRef>>(
session.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new();
foreach (var p in addl)
ids.Add(p.AccountId.ToString());
}
catch { /* malformed JSON — ignore additional players */ }
}
return ids;
}
// Minimal deserialization shape for additional player entries in AdditionalPlayersJson.
private sealed class AdditionalPlayerRef { public Guid AccountId { get; set; } }
internal static async Task PushStateToPlayersAsync(
IClientPush clientPush,
GameSession session,
GameState state,
CancellationToken ct,
string? prevStateJson = null)
{
if (prevStateJson != null)
{
var prevState = GameEngine.Deserialize(prevStateJson);
var allIds = GetAllPlayerIds(session);
static bool IsEmpty(GameStateDelta d) =>
d.MetaDelta == null &&
d.ChangedTiles == null &&
d.UnitsAdded == null &&
d.UnitsRemoved == null &&
d.UnitsChanged == null &&
d.ArchSpiritByAccount == null &&
d.PlayerStatsByAccount == null &&
d.PublicCountsByAccount == null &&
d.PrivateByViewer == null;
// ActiveEffects is excluded: it is always populated in every delta
var deltas = allIds.ToDictionary(
pid => pid,
pid => GameStateDiffer.ComputeDelta(prevState, state, pid));
var tasks = new List<Task>();
if (deltas.Values.Any(IsEmpty))
{
foreach (var pid in allIds)
tasks.Add(clientPush.PushAsync(pid,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, pid))), ct));
var regFull = SpectatorRegistryService.Instance;
if (regFull != null)
{
var spectatorsFull = await regFull.GetSpectatorsAsync(session.Id);
if (spectatorsFull.Count > 0)
{
var spectatorDto = GameEngine.ToDtoSpectator(state);
foreach (var specId in spectatorsFull)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(spectatorDto)), ct));
}
}
}
else
{
foreach (var (pid, delta) in deltas)
tasks.Add(clientPush.PushAsync(pid,
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(delta)), ct));
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
var spectators = await registry.GetSpectatorsAsync(session.Id);
if (spectators.Count > 0)
{
var spectatorDto = GameEngine.ToDtoSpectator(state);
foreach (var specId in spectators)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(spectatorDto)), ct));
}
}
}
await Task.WhenAll(tasks);
}
else
{
// Fallback: no previous state — push full state (initial connect, reconnect, timer expiry)
var allIds = GetAllPlayerIds(session);
var tasks = allIds.Select(pid =>
clientPush.PushAsync(pid,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, pid))), ct))
.ToList<Task>();
var registry = SpectatorRegistryService.Instance;
if (registry != null)
{
var spectators = await registry.GetSpectatorsAsync(session.Id);
if (spectators.Count > 0)
{
var spectatorDto = GameEngine.ToDtoSpectator(state);
foreach (var specId in spectators)
tasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(spectatorDto)), ct));
}
}
await Task.WhenAll(tasks);
}
await PushPendingPromptsAsync(clientPush, state, ct);
}
/// <summary>
/// Pushes any active ability-pause prompts to the appropriate chooser player.
/// Called both from <see cref="PushStateToPlayersAsync"/> (after every state mutation)
/// and from <see cref="GameGetStateHandler"/> (reconnect/sync path).
/// </summary>
internal static async Task PushPendingPromptsAsync(
IClientPush clientPush,
GameState state,
CancellationToken ct)
{
if (state.PendingTriggeredTarget is { } pending)
{
// Send the FULL action array. ResumeTriggeredAbility replays the whole array
// with original action indices, so the client must walk every action
// (auto-skipping server-resolved ones) and submit targets with matching
// indices. Sending only the first pick action broke any triggered ability
// whose pick action was not at index 0.
var actionJson = pending.ActionsJson;
var targetPlayer = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
await clientPush.PushAsync(targetPlayer,
ServerMessage.Push("game.ability.triggered_target_request",
new TriggeredTargetRequestPush(
pending.RequestId,
pending.SourceInstanceId,
pending.AbilityName,
actionJson,
pending.RangeJson)), ct);
}
if (state.PendingCostPick is { } cp)
await clientPush.PushAsync(cp.PickerActorId,
ServerMessage.Push("game.ability.cost_pick_request",
new CostPickRequestPush(
cp.RequestId,
cp.SourceInstanceId,
cp.CostType,
cp.Amount,
cp.PickMode,
cp.FiltersJson,
cp.CandidatesJson)), ct);
if (state.PendingCostGroupPick is { } cgp)
{
var chooser = string.IsNullOrEmpty(cgp.ChooserActorId) ? cgp.ActorId : cgp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.cost_group_pick_request",
new CostGroupPickRequestPush(
cgp.RequestId,
cgp.SourceInstanceId,
cgp.CostGroupJson)), ct);
}
if (state.PendingActionGroupPick is { } agp)
{
var chooser = string.IsNullOrEmpty(agp.ChooserActorId) ? agp.ActorId : agp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.action_group_pick_request",
new ActionGroupPickRequestPush(
agp.RequestId,
agp.SourceInstanceId,
agp.ActionGroupJson)), ct);
}
if (state.PendingBranchPick is { } bp)
{
var chooser = string.IsNullOrEmpty(bp.ChooserActorId) ? bp.ActorId : bp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.branch_pick_request",
new BranchPickRequestPush(
bp.RequestId,
bp.SourceInstanceId,
bp.BranchCount,
bp.BranchesJson)), ct);
}
if (state.PendingTargetPick is { } ttp)
{
var chooser = string.IsNullOrEmpty(ttp.ChooserActorId) ? ttp.ActorId : ttp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.target_pick_request",
new TargetPickRequestPush(
ttp.RequestId,
ttp.SourceInstanceId,
ttp.ActionJson,
ttp.RangeJson,
ttp.CandidatesJson)), ct);
}
if (state.PendingTilePick is { } tp)
{
var chooser = string.IsNullOrEmpty(tp.ChooserActorId) ? tp.ActorId : tp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.tile_pick_request",
new TilePickRequestPush(
tp.RequestId,
tp.SourceInstanceId,
tp.EffectType,
tp.RequireEmpty,
tp.RequireOccupied,
tp.OccupantOwnership,
tp.MaxRange,
tp.TargetInstanceId)), ct);
}
if (state.PendingPlayerPick is { } pp)
{
var chooser = string.IsNullOrEmpty(pp.ChooserActorId) ? pp.ActorId : pp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.player_pick_request",
new PlayerPickRequestPush(
pp.RequestId,
pp.SourceInstanceId,
pp.EffectType,
pp.Ownership,
pp.ValidPlayerIds,
pp.TargetInstanceId)), ct);
}
if (state.PendingRevealChoicePick is { } rcp)
{
var chooser = string.IsNullOrEmpty(rcp.ChooserActorId) ? rcp.ActorId : rcp.ChooserActorId;
await clientPush.PushAsync(chooser,
ServerMessage.Push("game.ability.reveal_choice_pick_request",
new RevealChoicePickRequestPush(
rcp.RequestId,
rcp.SourceInstanceId,
rcp.EffectType,
rcp.RevealedCardsJson,
rcp.Count)), ct);
}
}
// OP config snapshot — read from RuleSnapshotJson at finalization time.
private sealed record OpSnapshot(
int WinnerOpReward = 50,
int LoserOpReward = 10,
int RankDiffOpMultiplierPct = 0);
/// <summary>
/// Finalize a completed game: update session status, adjust ELO ranks,
/// award OriginPoints, push game-over to both players, publish GameEndedEvent.
/// </summary>
internal static async Task FinalizeGameAsync(
GameDbContext gameDb,
SorIdentityDbContext identityDb,
IClientPush clientPush,
IEventBus eventBus,
GameSession session,
Guid winnerAccountId,
Guid loserAccountId,
string winCondition,
CancellationToken ct)
{
// Cancel any pending turn timer — the game is over.
GameTurnTimerService.Instance?.CancelTimer(session.Id);
// These fields may already be set by the calling handler (so they are committed
// atomically with the StateJson update in SaveStateAsync). Setting them here again
// is idempotent and ensures correctness even if called without the pre-set pattern.
session.Status = GameSessionStatus.Completed;
session.WinnerAccountId = winnerAccountId;
session.WinCondition = winCondition;
session.EndedAt = DateTimeOffset.UtcNow;
// Mark the linked custom lobby as Completed so it disappears from the active-games
// browser. Ranked sessions have no linked lobby; the query safely returns null.
var linkedLobby = await gameDb.CustomLobbies
.FirstOrDefaultAsync(l => l.GameSessionId == session.Id, ct);
if (linkedLobby != null && linkedLobby.Status == CustomLobbyStatus.Started)
linkedLobby.Status = CustomLobbyStatus.Completed;
// Save game session status FIRST — this must succeed before we touch ELO.
// If identity DB fails below, the session is still correctly marked Completed
// so players won't be stuck in a ghost match on next login.
await gameDb.SaveChangesAsync(ct);
// Load both accounts for ELO + OP 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);
// Capture pre-ELO ranks for OP scaling.
var winnerPreRank = winner.RankScore;
var loserPreRank = loser.RankScore;
var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winner.RankScore, loser.RankScore);
// AI accounts track ELO separately — don't adjust player RankScore.
if (!winner.IsAi) winner.RankScore += winnerDelta;
if (!loser.IsAi) loser.RankScore = Math.Max(0, loser.RankScore - loserDelta);
// Compute OriginPoints rewards from the rule snapshot.
var snap = JsonSerializer.Deserialize<OpSnapshot>(
session.RuleSnapshotJson ?? "{}",
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new OpSnapshot();
var rankDiff = loserPreRank - winnerPreRank; // positive = winner was underdog
var adjustment = rankDiff * snap.RankDiffOpMultiplierPct / 1000;
var winnerOp = Math.Max(1, snap.WinnerOpReward + adjustment);
var loserOp = Math.Max(0, snap.LoserOpReward - adjustment);
if (!winner.IsAi) winner.OriginPoints += winnerOp;
if (!loser.IsAi) loser.OriginPoints += loserOp;
await identityDb.SaveChangesAsync(ct);
var push = new GameOverPush(
SessionId : session.Id,
WinnerAccountId : winnerAccountId,
LoserAccountId : loserAccountId,
WinCondition : winCondition,
WinnerRankDelta : winnerDelta,
LoserRankDelta : loserDelta,
WinnerOpDelta : winnerOp,
LoserOpDelta : loserOp);
var gameOverTasks = new List<Task>
{
clientPush.PushAsync(winnerAccountId.ToString(),
ServerMessage.Push("game.over", push), ct),
clientPush.PushAsync(loserAccountId.ToString(),
ServerMessage.Push("game.over", push), ct),
};
// Push game.over to spectators then evict the session from the registry.
var spectatorRegistry = SpectatorRegistryService.Instance;
if (spectatorRegistry != null)
{
foreach (var specId in await spectatorRegistry.GetSpectatorsAsync(session.Id))
gameOverTasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.over", push), ct));
await spectatorRegistry.RemoveSessionAsync(session.Id);
}
await Task.WhenAll(gameOverTasks);
// Notify skybox activity subscribers that this game has ended.
await BroadcastActivityAsync(clientPush, "ended", session.Id, ct);
// Publish inter-service event so ChatLifecycleHostedService archives the match channel.
await eventBus.PublishAsync(NatsSubjects.GameEnded,
new GameEndedEvent(
GameId : session.Id,
WinnerId : winnerAccountId,
LoserId : loserAccountId,
DurationSeconds : (int)(session.EndedAt!.Value - session.CreatedAt).TotalSeconds,
EndedAt : session.EndedAt.Value),
ct);
}
/// <summary>
/// Finalize an N-player game (3+ players or team modes).
/// Applies pairwise ELO: each winner beats every loser individually.
/// Pushes <see cref="GameOverPush"/> with full <see cref="PlayerOutcomeDto"/> list to all participants.
/// </summary>
internal static async Task FinalizeMultiPlayerGameAsync(
GameDbContext gameDb,
SorIdentityDbContext identityDb,
IClientPush clientPush,
IEventBus eventBus,
GameSession session,
IReadOnlyList<Guid> winnerIds,
IReadOnlyList<Guid> loserIds,
string winCondition,
CancellationToken ct)
{
if (winnerIds.Count == 0) throw new InvalidOperationException("Must have at least one winner.");
// For single-winner single-loser games just delegate to the existing path.
if (winnerIds.Count == 1 && loserIds.Count == 1)
{
await FinalizeGameAsync(gameDb, identityDb, clientPush, eventBus,
session, winnerIds[0], loserIds[0], winCondition, ct);
return;
}
GameTurnTimerService.Instance?.CancelTimer(session.Id);
session.Status = GameSessionStatus.Completed;
session.WinnerAccountId = winnerIds[0];
session.WinCondition = winCondition;
session.EndedAt = DateTimeOffset.UtcNow;
var linkedLobby = await gameDb.CustomLobbies
.FirstOrDefaultAsync(l => l.GameSessionId == session.Id, ct);
if (linkedLobby != null && linkedLobby.Status == CustomLobbyStatus.Started)
linkedLobby.Status = CustomLobbyStatus.Completed;
await gameDb.SaveChangesAsync(ct);
// Load all participants.
var allIds = winnerIds.Concat(loserIds).Distinct().ToArray();
var accounts = await identityDb.Users
.Where(a => allIds.Contains(a.Id))
.ToListAsync(ct);
var snap = JsonSerializer.Deserialize<OpSnapshot>(
session.RuleSnapshotJson ?? "{}",
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new OpSnapshot();
// Track per-player ELO/OP deltas.
var rankDeltas = allIds.ToDictionary(id => id, _ => 0);
var opDeltas = allIds.ToDictionary(id => id, _ => 0);
// Pairwise ELO: each winner beats each loser.
foreach (var wid in winnerIds)
{
var wAcc = accounts.FirstOrDefault(a => a.Id == wid);
if (wAcc == null) continue;
foreach (var lid in loserIds)
{
var lAcc = accounts.FirstOrDefault(a => a.Id == lid);
if (lAcc == null) continue;
var (wd, ld) = GameEngine.ComputeEloDelta(wAcc.RankScore, lAcc.RankScore);
rankDeltas[wid] += wd;
rankDeltas[lid] -= ld;
// OP: base winner reward ÷ loser count, base loser reward ÷ winner count.
var rankDiff = lAcc.RankScore - wAcc.RankScore;
var adjustment = rankDiff * snap.RankDiffOpMultiplierPct / 1000;
opDeltas[wid] += Math.Max(0, (snap.WinnerOpReward + adjustment) / Math.Max(1, loserIds.Count));
opDeltas[lid] -= Math.Max(0, (snap.LoserOpReward - adjustment) / Math.Max(1, winnerIds.Count));
}
}
// Apply clamped deltas — AI accounts are excluded from player RankScore/OP.
foreach (var acc in accounts)
{
if (!acc.IsAi) acc.RankScore = Math.Max(0, acc.RankScore + rankDeltas[acc.Id]);
if (!acc.IsAi) acc.OriginPoints += Math.Max(0, opDeltas[acc.Id]);
}
await identityDb.SaveChangesAsync(ct);
// Build per-player outcome list.
var outcomes = new List<PlayerOutcomeDto>();
foreach (var wid in winnerIds)
outcomes.Add(new PlayerOutcomeDto(wid, "Winner", rankDeltas[wid], opDeltas[wid]));
foreach (var lid in loserIds)
outcomes.Add(new PlayerOutcomeDto(lid, "Loser",
rankDeltas.GetValueOrDefault(lid, 0),
Math.Max(0, opDeltas.GetValueOrDefault(lid, 0))));
var push = new GameOverPush(
SessionId : session.Id,
WinnerAccountId : winnerIds[0],
LoserAccountId : loserIds[0],
WinCondition : winCondition,
WinnerRankDelta : rankDeltas[winnerIds[0]],
LoserRankDelta : Math.Abs(rankDeltas[loserIds[0]]),
WinnerOpDelta : opDeltas[winnerIds[0]],
LoserOpDelta : Math.Max(0, opDeltas[loserIds[0]]),
PlayerOutcomes : outcomes);
var allParticipants = GetAllPlayerIds(session);
var gameOverTasks = allParticipants
.Select(pid => clientPush.PushAsync(pid, ServerMessage.Push("game.over", push), ct))
.ToList<Task>();
var spectatorRegistry = SpectatorRegistryService.Instance;
if (spectatorRegistry != null)
{
foreach (var specId in await spectatorRegistry.GetSpectatorsAsync(session.Id))
gameOverTasks.Add(clientPush.PushAsync(specId.ToString(),
ServerMessage.Push("game.over", push), ct));
await spectatorRegistry.RemoveSessionAsync(session.Id);
}
await Task.WhenAll(gameOverTasks);
await BroadcastActivityAsync(clientPush, "ended", session.Id, ct);
await eventBus.PublishAsync(NatsSubjects.GameEnded,
new GameEndedEvent(
GameId : session.Id,
WinnerId : winnerIds[0],
LoserId : loserIds[0],
DurationSeconds : (int)(session.EndedAt!.Value - session.CreatedAt).TotalSeconds,
EndedAt : session.EndedAt.Value),
ct);
}
/// <summary>
/// Push a <see cref="PlayerEliminatedPush"/> to all active (non-eliminated) players and spectators.
/// Called when a player is knocked out mid-game but the game continues.
/// </summary>
internal static async Task BroadcastPlayerEliminatedAsync(
IClientPush clientPush,
GameSession session,
GameState state,
string eliminatedId,
CancellationToken ct)
{
if (!state.Players.TryGetValue(eliminatedId, out var ep)) return;
var push = ServerMessage.Push("game.player_eliminated",
new PlayerEliminatedPush(
SessionId : session.Id,
EliminatedAccountId: Guid.Parse(eliminatedId),
SeatIndex : ep.SeatIndex,
TeamIndex : ep.TeamIndex));
// Push to all non-eliminated session participants.
var allIds = GetAllPlayerIds(session);
var tasks = allIds
.Select(pid => clientPush.PushAsync(pid, push, ct))
.ToList<Task>();
var spectatorRegistry = SpectatorRegistryService.Instance;
if (spectatorRegistry != null)
{
foreach (var specId in await spectatorRegistry.GetSpectatorsAsync(session.Id))
tasks.Add(clientPush.PushAsync(specId.ToString(), push, ct));
}
await Task.WhenAll(tasks);
}
}