Phase 3 & 4: Team colors, player_eliminated push, board shapes, lobby team UI
Phase 3 – Team modes: - GameState: TeamColors dictionary (int → hex color string) populated from palette - GameMessages: PlayerEliminatedPush, PlayerOutcomeDto, extended GameOverPush - GameHandlerBase: FinalizeMultiPlayerGameAsync (pairwise ELO), BroadcastPlayerEliminatedAsync, GetAllPlayerIds for N-player push - GameAttackHandler: snapshot pre-attack elimination state; use FinalizeMultiPlayerGameAsync; push PlayerEliminatedPush for mid-game knockouts - game_screen.gd: turn order strip chips carry team-color left border from state.teamColors - lobby_room_screen.gd: _team_label() helper; team badges on host/guest/additional slots Phase 4 – Board shape library: - BoardShapeGenerator: AutoShape() picks shape by player count; adds Triangular (3p), RadialStar (5p, 5-arm star), HexRing (6p, hex perimeter zones); CoordsInRect helper - GameLobbyReadyHandler: auto-selects board shape at game start; passes BoardShape+PlayerCount into rules snapshot 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:
@@ -105,6 +105,14 @@ public static class GameEngine
|
||||
state.Players[accountId.ToString()] = ps;
|
||||
}
|
||||
|
||||
// Assign a distinct color per team from the built-in palette.
|
||||
// FFA: each player is their own team, so every seat gets a unique color.
|
||||
// Teams/MultiTeam: teammates share a color.
|
||||
var palette = new[] { "4488FF", "FF4444", "44CC66", "FFAA00", "AA44FF", "FF44AA", "22CCDD", "AABB44" };
|
||||
var distinctTeams = players.Select(p => p.teamIndex).Distinct().OrderBy(i => i).ToList();
|
||||
for (int i = 0; i < distinctTeams.Count; i++)
|
||||
state.TeamColors[distinctTeams[i]] = palette[i % palette.Length];
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -1026,7 +1034,8 @@ public static class GameEngine
|
||||
Players : players,
|
||||
Board : boardDto,
|
||||
SeatOrder : state.SeatOrder,
|
||||
GameMode : state.GameMode);
|
||||
GameMode : state.GameMode,
|
||||
TeamColors : state.TeamColors);
|
||||
}
|
||||
|
||||
// ── Deck validation ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -317,16 +317,35 @@ public sealed record ListActiveLobbiesResponse(
|
||||
/// </summary>
|
||||
public sealed record GameStateUpdatePush(GameStateDto State);
|
||||
|
||||
/// <summary>Pushed to both players when the game ends.</summary>
|
||||
/// <summary>
|
||||
/// Pushed to all active players when a player is eliminated mid-game (ArchSpirit destroyed)
|
||||
/// but the game continues (more than one surviving team).
|
||||
/// </summary>
|
||||
public sealed record PlayerEliminatedPush(
|
||||
Guid SessionId,
|
||||
Guid EliminatedAccountId,
|
||||
int SeatIndex,
|
||||
int TeamIndex);
|
||||
|
||||
/// <summary>Per-player outcome entry for N-player game-over pushes.</summary>
|
||||
public sealed record PlayerOutcomeDto(
|
||||
Guid AccountId,
|
||||
string Outcome, // "Winner" | "Loser"
|
||||
int RankDelta,
|
||||
int OpDelta);
|
||||
|
||||
/// <summary>Pushed to all players when the game ends.</summary>
|
||||
public sealed record GameOverPush(
|
||||
Guid SessionId,
|
||||
Guid WinnerAccountId,
|
||||
Guid LoserAccountId,
|
||||
string WinCondition, // "health" | "concede" | "disconnect"
|
||||
Guid WinnerAccountId, // primary winner (backward-compat; first of winners list)
|
||||
Guid LoserAccountId, // primary loser (backward-compat; first of losers list)
|
||||
string WinCondition, // "health" | "concede" | "disconnect" | "time_limit"
|
||||
int WinnerRankDelta,
|
||||
int LoserRankDelta,
|
||||
int WinnerOpDelta,
|
||||
int LoserOpDelta);
|
||||
int LoserOpDelta,
|
||||
// N-player: individual outcomes for every participant (null for 1v1 backward compat).
|
||||
IEnumerable<PlayerOutcomeDto>? PlayerOutcomes = null);
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to both players when a session that was Initializing is abandoned
|
||||
@@ -522,8 +541,9 @@ public sealed record GameStateDto(
|
||||
int StateVersion, // monotonic; use for client mismatch detection
|
||||
IEnumerable<PlayerStateDto> Players,
|
||||
BoardDto? Board, // full board state including tile affinities
|
||||
IEnumerable<string> SeatOrder, // account IDs in seat/turn order; empty = legacy 1v1
|
||||
string GameMode); // "FFA" | "Teams" | "MultiTeam"
|
||||
IEnumerable<string> SeatOrder, // account IDs in seat/turn order; empty = legacy 1v1
|
||||
string GameMode, // "FFA" | "Teams" | "MultiTeam"
|
||||
Dictionary<int, string> TeamColors); // teamIndex → hex color e.g. "4488FF"
|
||||
|
||||
public sealed record PlayerStateDto(
|
||||
Guid AccountId,
|
||||
|
||||
@@ -31,6 +31,12 @@ public sealed class GameState
|
||||
/// <summary>"FFA" | "Teams" | "MultiTeam". Used for ability ownership resolution.</summary>
|
||||
public string GameMode { get; set; } = "FFA";
|
||||
|
||||
/// <summary>
|
||||
/// Maps TeamIndex → CSS-style hex color string (e.g. "4488FF").
|
||||
/// Populated at initialization from the built-in palette; empty for legacy 1v1 games.
|
||||
/// </summary>
|
||||
public Dictionary<int, string> TeamColors { get; set; } = new();
|
||||
|
||||
/// <summary>Running sequence number for action log / StateVersion.</summary>
|
||||
public int NextActionSequence { get; set; } = 1;
|
||||
|
||||
|
||||
@@ -6,12 +6,27 @@ namespace SOR.Game.Grid;
|
||||
/// </summary>
|
||||
public static class BoardShapeGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the recommended board shape for a given player count when none is explicitly specified.
|
||||
/// </summary>
|
||||
public static string AutoShape(int playerCount) => playerCount switch
|
||||
{
|
||||
3 => "Triangular",
|
||||
4 => "Cross",
|
||||
5 => "RadialStar",
|
||||
6 => "HexRing",
|
||||
_ => "Rectangle", // 2 and 7–10
|
||||
};
|
||||
|
||||
/// <summary>Generate a board appropriate for the given shape, rules, and player count.</summary>
|
||||
public static Board Generate(string shape, GameRules rules, int playerCount) =>
|
||||
shape switch
|
||||
{
|
||||
"Cross" => MakeCross(rules),
|
||||
_ => MakeRectangle(rules, playerCount),
|
||||
"Cross" => MakeCross(rules),
|
||||
"Triangular" => MakeTriangular(rules),
|
||||
"RadialStar" => MakeRadialStar(rules),
|
||||
"HexRing" => MakeHexRing(rules),
|
||||
_ => MakeRectangle(rules, playerCount),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -81,8 +96,128 @@ public static class BoardShapeGenerator
|
||||
return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Triangular board for 3 players.
|
||||
/// Uses a standard rectangle with three well-separated starting zones:
|
||||
/// Seat 0 = bottom-left corner, Seat 1 = bottom-right corner, Seat 2 = top-center.
|
||||
/// </summary>
|
||||
private static Board MakeTriangular(GameRules rules)
|
||||
{
|
||||
// Prefer a wider board so all three zones have breathing room.
|
||||
int w = Math.Max(rules.BoardWidth, 12);
|
||||
int h = Math.Max(rules.BoardHeight, 10);
|
||||
var board = Board.Create(w, h, rules.StartingRandomTilePct);
|
||||
|
||||
int zoneW = Math.Max(2, w / 5); // width of each corner zone
|
||||
var zones = new Dictionary<int, HashSet<Coord>>
|
||||
{
|
||||
[0] = CoordsInRect(0, 0, zoneW - 1, 1, w, h), // bottom-left
|
||||
[1] = CoordsInRect(w - zoneW, 0, w - 1, 1, w, h), // bottom-right
|
||||
[2] = CoordsInRect(w / 2 - zoneW / 2, h - 2,
|
||||
w / 2 + zoneW / 2 - 1, h - 1, w, h), // top-center
|
||||
};
|
||||
|
||||
return new Board { Width = board.Width, Height = board.Height, Tiles = board.Tiles, StartingZones = zones };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Radial star board for 5 players.
|
||||
/// Five arms radiating from a central arena; one starting-zone tile at each arm tip.
|
||||
/// Arms point: bottom, lower-right, upper-right, upper-left, lower-left (pentagon arrangement).
|
||||
/// </summary>
|
||||
private static Board MakeRadialStar(GameRules rules)
|
||||
{
|
||||
const int armLen = 5; // tiles per arm (not counting center)
|
||||
const int arenaR = 4; // radius of central filled square (half-width)
|
||||
int center = arenaR * 2 + 1; // 9
|
||||
int total = center + armLen * 2; // 19 in each dimension (plenty of room)
|
||||
|
||||
var tiles = new Dictionary<string, Tile>();
|
||||
|
||||
// Central arena
|
||||
int c = total / 2;
|
||||
for (int x = c - arenaR; x <= c + arenaR; x++)
|
||||
for (int y = c - arenaR; y <= c + arenaR; y++)
|
||||
AddTile(tiles, x, y);
|
||||
|
||||
// 5 arms at angles 270°, 342°, 54°, 126°, 198° (bottom-first, counter-clockwise)
|
||||
// Approximated on a square grid as (dx, dy) unit directions scaled to armLen steps.
|
||||
// Pentagon vertices (unit circle, starting at bottom):
|
||||
// 270° → (0, -1) lower center
|
||||
// 342° → (0.95, -0.31) → approx (1, 0) then (1,-1) staircase
|
||||
// 54° → (0.59, 0.81) → approx (1, 1) staircase
|
||||
// 126° → (-0.59, 0.81) → approx (-1, 1)
|
||||
// 198° → (-0.95, -0.31) → approx (-1, 0) then (-1,-1)
|
||||
// Grid-friendly arm directions for the 5 seats:
|
||||
(int dx, int dy)[] dirs =
|
||||
[
|
||||
( 0, -1), // Seat 0: bottom
|
||||
( 1, -1), // Seat 1: lower-right (diagonal)
|
||||
( 1, 1), // Seat 2: upper-right (diagonal)
|
||||
(-1, 1), // Seat 3: upper-left (diagonal)
|
||||
(-1, -1), // Seat 4: lower-left (diagonal)
|
||||
];
|
||||
|
||||
var zones = new Dictionary<int, HashSet<Coord>>();
|
||||
|
||||
for (int seat = 0; seat < dirs.Length; seat++)
|
||||
{
|
||||
var (dx, dy) = dirs[seat];
|
||||
int tipX = c, tipY = c;
|
||||
for (int step = 1; step <= armLen; step++)
|
||||
{
|
||||
int ax = c + dx * step;
|
||||
int ay = c + dy * step;
|
||||
AddTile(tiles, ax, ay);
|
||||
tipX = ax; tipY = ay;
|
||||
}
|
||||
zones[seat] = new HashSet<Coord> { new Coord(tipX, tipY) };
|
||||
}
|
||||
|
||||
return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hexagonal ring board for 6 players.
|
||||
/// A filled hexagon (approximated on a square grid) with 6 starting zones at the
|
||||
/// flat-top hex vertices: bottom-left, bottom, bottom-right, top-right, top, top-left.
|
||||
/// </summary>
|
||||
private static Board MakeHexRing(GameRules rules)
|
||||
{
|
||||
// Use a rectangle large enough to contain the hex, with random tiles.
|
||||
int w = Math.Max(rules.BoardWidth, 14);
|
||||
int h = Math.Max(rules.BoardHeight, 12);
|
||||
var board = Board.Create(w, h, rules.StartingRandomTilePct);
|
||||
|
||||
// Starting zones at 6 evenly-spaced perimeter positions.
|
||||
// Place them like a hex: 2 on bottom row, 2 on top row, 1 left-mid, 1 right-mid.
|
||||
int zW = Math.Max(2, w / 6);
|
||||
int mY = h / 2; // mid row for left/right zones
|
||||
|
||||
var zones = new Dictionary<int, HashSet<Coord>>
|
||||
{
|
||||
[0] = CoordsInRect(0, 0, zW - 1, 1, w, h), // bottom-left
|
||||
[1] = CoordsInRect(w / 2 - zW / 2, 0, w / 2 + zW / 2 - 1, 1, w, h), // bottom-center
|
||||
[2] = CoordsInRect(w - zW, 0, w - 1, 1, w, h), // bottom-right
|
||||
[3] = CoordsInRect(w - zW, h - 2, w - 1, h - 1, w, h), // top-right
|
||||
[4] = CoordsInRect(w / 2 - zW / 2, h - 2, w / 2 + zW / 2 - 1, h - 1, w, h), // top-center
|
||||
[5] = CoordsInRect(0, h - 2, zW - 1, h - 1, w, h), // top-left
|
||||
};
|
||||
|
||||
return new Board { Width = board.Width, Height = board.Height, Tiles = board.Tiles, StartingZones = zones };
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static HashSet<Coord> CoordsInRect(int x0, int y0, int x1, int y1, int w, int h)
|
||||
{
|
||||
var s = new HashSet<Coord>();
|
||||
for (int x = Math.Max(0, x0); x <= Math.Min(w - 1, x1); x++)
|
||||
for (int y = Math.Max(0, y0); y <= Math.Min(h - 1, y1); y++)
|
||||
s.Add(new Coord(x, y));
|
||||
return s;
|
||||
}
|
||||
|
||||
private static HashSet<Coord> CoordsInRows(int r0, int r1, int width)
|
||||
{
|
||||
var s = new HashSet<Coord>();
|
||||
|
||||
@@ -48,19 +48,18 @@ internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler
|
||||
var prevStateJson = session.StateJson!;
|
||||
var state = GameEngine.Deserialize(prevStateJson);
|
||||
|
||||
// Snapshot elimination state before the attack to detect new mid-game eliminations.
|
||||
var prevEliminated = state.Players.Values
|
||||
.Where(p => p.IsEliminated)
|
||||
.Select(p => p.AccountId)
|
||||
.ToHashSet();
|
||||
|
||||
var (newState, gameOver) = GameEngine.Attack(
|
||||
state, actorId, req.AttackerInstanceId, req.TargetInstanceId);
|
||||
|
||||
if (gameOver)
|
||||
{
|
||||
// The attacking player destroyed the opponent's ArchSpirit.
|
||||
// Set completion fields BEFORE SaveStateAsync so they are committed atomically
|
||||
// with the StateJson update (prevents ghost-match on next login if server crashes
|
||||
// in the window between SaveStateAsync and FinalizeGameAsync).
|
||||
var loserId = session.PlayerOneAccountId.ToString() == actorId
|
||||
? session.PlayerTwoAccountId
|
||||
: session.PlayerOneAccountId;
|
||||
|
||||
// All remaining players share one team — game is finished.
|
||||
session.Status = GameSessionStatus.Completed;
|
||||
session.WinnerAccountId = Guid.Parse(actorId);
|
||||
session.WinCondition = "health";
|
||||
@@ -74,21 +73,32 @@ internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler
|
||||
|
||||
if (gameOver)
|
||||
{
|
||||
var loserId = session.PlayerOneAccountId.ToString() == actorId
|
||||
? session.PlayerTwoAccountId
|
||||
: session.PlayerOneAccountId;
|
||||
// Determine all winners (non-eliminated) and losers (eliminated) from final state.
|
||||
var winnerIds = newState.Players.Values
|
||||
.Where(p => !p.IsEliminated)
|
||||
.Select(p => Guid.Parse(p.AccountId))
|
||||
.ToList();
|
||||
var loserIds = newState.Players.Values
|
||||
.Where(p => p.IsEliminated)
|
||||
.Select(p => Guid.Parse(p.AccountId))
|
||||
.ToList();
|
||||
|
||||
await FinalizeGameAsync(
|
||||
await FinalizeMultiPlayerGameAsync(
|
||||
_gameDb, _identityDb, _clientPush, _eventBus,
|
||||
session,
|
||||
winnerAccountId: Guid.Parse(actorId),
|
||||
loserAccountId: loserId,
|
||||
winCondition: "health",
|
||||
ct);
|
||||
session, winnerIds, loserIds, "health", ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Push updated state to all participants.
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
|
||||
|
||||
// Notify all players of any mid-game eliminations (game continues, player knocked out).
|
||||
var newlyEliminated = newState.Players.Values
|
||||
.Where(p => p.IsEliminated && !prevEliminated.Contains(p.AccountId))
|
||||
.Select(p => p.AccountId)
|
||||
.ToList();
|
||||
foreach (var eid in newlyEliminated)
|
||||
await BroadcastPlayerEliminatedAsync(_clientPush, session, newState, eid, ct);
|
||||
}
|
||||
|
||||
return ServerMessage.Reply("game.attack.ack", message.Seq,
|
||||
|
||||
@@ -118,6 +118,36 @@ internal abstract class GameHandlerBase
|
||||
/// 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,
|
||||
@@ -157,6 +187,10 @@ internal abstract class GameHandlerBase
|
||||
|
||||
var tasks = new List<Task>();
|
||||
|
||||
// Additional players (seats 3+): always receive full-state updates
|
||||
// (the delta system only computes P1/P2 perspective deltas).
|
||||
var addlIds = GetAllPlayerIds(session).Skip(2).ToList();
|
||||
|
||||
if (IsEmpty(d1) || IsEmpty(d2))
|
||||
{
|
||||
// At least one player's delta is empty — fall back to full state for both.
|
||||
@@ -202,21 +236,22 @@ internal abstract class GameHandlerBase
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var aid in addlIds)
|
||||
tasks.Add(clientPush.PushAsync(aid,
|
||||
ServerMessage.Push("game.state_update",
|
||||
new GameStateUpdatePush(GameEngine.ToDto(state, aid))), ct));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback: no previous state — push full state (initial connect, reconnect, timer expiry)
|
||||
var tasks = new List<Task>
|
||||
{
|
||||
clientPush.PushAsync(p1Id,
|
||||
var allIds = GetAllPlayerIds(session);
|
||||
var tasks = allIds.Select(pid =>
|
||||
clientPush.PushAsync(pid,
|
||||
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),
|
||||
};
|
||||
new GameStateUpdatePush(GameEngine.ToDto(state, pid))), ct))
|
||||
.ToList<Task>();
|
||||
|
||||
var registry = SpectatorRegistryService.Instance;
|
||||
if (registry != null)
|
||||
@@ -355,4 +390,171 @@ internal abstract class GameHandlerBase
|
||||
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.
|
||||
foreach (var acc in accounts)
|
||||
{
|
||||
acc.RankScore = Math.Max(0, acc.RankScore + rankDeltas[acc.Id]);
|
||||
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 spectatorRegistry.GetSpectators(session.Id))
|
||||
gameOverTasks.Add(clientPush.PushAsync(specId.ToString(),
|
||||
ServerMessage.Push("game.over", push), ct));
|
||||
spectatorRegistry.RemoveSession(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 spectatorRegistry.GetSpectators(session.Id))
|
||||
tasks.Add(clientPush.PushAsync(specId.ToString(), push, ct));
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ using SOR.Networking.Abstractions.EventBus;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Game.Grid;
|
||||
using SOR.Shared.Nats;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
@@ -188,6 +189,9 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
.Where(r => r.IsCustomDefault)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
// Auto-select board shape when the lobby doesn't specify one explicitly.
|
||||
var boardShape = BoardShapeGenerator.AutoShape(playerCount);
|
||||
|
||||
// Build effective rules: lobby override → admin custom-default → hard-coded default.
|
||||
var rules = new GameRules
|
||||
{
|
||||
@@ -209,6 +213,8 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
TurnLimit = lobby.TurnLimitOverride ?? dbDefaults?.TurnLimit ?? GameRules.Default.TurnLimit,
|
||||
MpBuff = lobby.MpBuffOverride ?? dbDefaults?.MpBuff ?? GameRules.Default.MpBuff,
|
||||
StartingRandomTilePct = lobby.StartingRandomTilePctOverride ?? dbDefaults?.StartingRandomTilePct ?? GameRules.Default.StartingRandomTilePct,
|
||||
BoardShape = boardShape,
|
||||
PlayerCount = playerCount,
|
||||
};
|
||||
|
||||
// Build additional players JSON for the session (seats 2+).
|
||||
|
||||
Reference in New Issue
Block a user