From 356e1a50e3cc1a8b1a71292bf80ab38503c9c276 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 26 Mar 2026 05:50:55 -0400 Subject: [PATCH] Phase 3 & 4: Team colors, player_eliminated push, board shapes, lobby team UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Co-Authored-By: Happy --- .../scenes/free_play/lobby_room_screen.gd | 30 ++- .../origin-client/scenes/game/game_screen.gd | 17 +- Server/src/SOR.Game/GameEngine.cs | 11 +- Server/src/SOR.Game/GameMessages.cs | 34 ++- Server/src/SOR.Game/GameState.cs | 6 + .../src/SOR.Game/Grid/BoardShapeGenerator.cs | 139 ++++++++++- .../SOR.Game/Handlers/GameAttackHandler.cs | 44 ++-- .../src/SOR.Game/Handlers/GameHandlerBase.cs | 218 +++++++++++++++++- .../Handlers/GameLobbyReadyHandler.cs | 6 + 9 files changed, 462 insertions(+), 43 deletions(-) diff --git a/Client/origin-client/scenes/free_play/lobby_room_screen.gd b/Client/origin-client/scenes/free_play/lobby_room_screen.gd index f0fc4d6..05eb115 100644 --- a/Client/origin-client/scenes/free_play/lobby_room_screen.gd +++ b/Client/origin-client/scenes/free_play/lobby_room_screen.gd @@ -153,14 +153,16 @@ func _refresh_display() -> void: game_mode_label.text = "Mode: %s (%d players)" % [mode_label, max_players] game_mode_label.visible = max_players > 2 or game_mode != "FFA" - # Host slot - host_name_label.text = "Host: %s" % str(lobby.get("hostDisplayName", Auth.display_name)) + # Host slot — show team badge when not FFA. + var team_suffix_0 : String = _team_label(game_mode, 0, team_count) + host_name_label.text = "Host: %s%s" % [str(lobby.get("hostDisplayName", Auth.display_name)), team_suffix_0] host_deck_label.text = "Deck: (selected)" # Guest slot + var team_suffix_1 : String = _team_label(game_mode, 1, team_count) var has_guest : bool = lobby.get("hasGuest", false) or lobby.get("guestAccountId", "") != "" if has_guest: - guest_name_label.text = "Guest: %s" % str(lobby.get("guestDisplayName", "Guest")) + guest_name_label.text = "Guest: %s%s" % [str(lobby.get("guestDisplayName", "Guest")), team_suffix_1] guest_deck_label.text = "Deck: (selected)" else: guest_name_label.text = "Waiting for guest…" @@ -191,6 +193,9 @@ func _rebuild_additional_players_panel(lobby: Dictionary, max_players: int) -> v additional_players_container.visible = false return + var gm : String = str(lobby.get("gameMode", "FFA")) + var tc : int = int(lobby.get("teamCount", 1)) + # The lobby dict may contain additionalPlayers array (from server push or join response). var addl : Array = lobby.get("additionalPlayers", []) as Array if addl.is_empty(): @@ -200,18 +205,31 @@ func _rebuild_additional_players_panel(lobby: Dictionary, max_players: int) -> v var has_guest : bool = lobby.get("hasGuest", false) or str(lobby.get("guestAccountId", "")) != "" var taken_slots : int = (1 if has_host else 0) + (1 if has_guest else 0) for i in range(max_players - taken_slots): - var row := _make_player_slot_row("Seat %d: Waiting…" % (taken_slots + i + 1), false) + var seat_n : int = taken_slots + i + var tsuf : String = _team_label(gm, seat_n, tc) + var row := _make_player_slot_row("Seat %d: Waiting…%s" % [seat_n + 1, tsuf], false) additional_players_container.add_child(row) else: - for entry: Dictionary in addl: + for i2: int in addl.size(): + var entry : Dictionary = addl[i2] as Dictionary var aname : String = str(entry.get("displayName", str(entry.get("accountId", "Player")).substr(0, 8))) var ready : bool = bool(entry.get("isReady", false)) - var row := _make_player_slot_row("Player: %s" % aname, ready) + var seat_n2 : int = i2 + 2 + var tsuf2 : String = _team_label(gm, seat_n2, tc) + var row := _make_player_slot_row("Player: %s%s" % [aname, tsuf2], ready) additional_players_container.add_child(row) additional_players_container.visible = true +## Returns a short team label like " [T0]" when in a team mode, else "". +func _team_label(game_mode: String, seat_index: int, team_count: int) -> String: + if game_mode == "FFA" or team_count <= 1: + return "" + var tidx : int = seat_index % team_count + return " [T%d]" % tidx + + func _make_player_slot_row(label_text: String, is_ready: bool) -> HBoxContainer: var hbox := HBoxContainer.new() hbox.add_theme_constant_override("separation", 8) diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd index affd79e..8e2b5a3 100644 --- a/Client/origin-client/scenes/game/game_screen.gd +++ b/Client/origin-client/scenes/game/game_screen.gd @@ -3266,8 +3266,9 @@ func _rebuild_turn_order_strip(state: Dictionary) -> void: for c in _turn_order_strip.get_children(): c.queue_free() - var active_id : String = str(state.get("activePlayerAccountId", "")) - var players : Array = state.get("players", []).duplicate() + var active_id : String = str(state.get("activePlayerAccountId", "")) + var players : Array = state.get("players", []).duplicate() + var team_colors : Dictionary = state.get("teamColors", {}) # Sort by seatIndex so chips appear in turn order. players.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: @@ -3278,11 +3279,23 @@ func _rebuild_turn_order_strip(state: Dictionary) -> void: var is_me : bool = (not _is_spectating) and pid == Auth.user_id var is_active : bool = pid == active_id var eliminated : bool = bool(p.get("isEliminated", false)) + var team_idx : int = int(p.get("teamIndex", -1)) + var hex_str : String = str(team_colors.get(str(team_idx), "")) var chip := PanelContainer.new() chip.custom_minimum_size = Vector2(72, 36) chip.self_modulate = Color(1, 1, 1, 0.3 if eliminated else (0.95 if is_active else 0.6)) + # Team-color left border via StyleBoxFlat. + var style := StyleBoxFlat.new() + style.bg_color = Color(0.12, 0.12, 0.14, 0.85) + style.border_width_left = 3 + if not hex_str.is_empty(): + style.border_color = Color.html("#" + hex_str) + else: + style.border_color = Color(0.4, 0.4, 0.4) + chip.add_theme_stylebox_override("panel", style) + var lbl := Label.new() var display : String = "You" if is_me else pid.substr(0, 8) lbl.text = ("★ " if is_active else "") + display + (" ✗" if eliminated else "") diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index 62f5a15..9bbd5d3 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -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 ─────────────────────────────────────────────────────── diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index d7498a9..6b39efe 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -317,16 +317,35 @@ public sealed record ListActiveLobbiesResponse( /// public sealed record GameStateUpdatePush(GameStateDto State); -/// Pushed to both players when the game ends. +/// +/// Pushed to all active players when a player is eliminated mid-game (ArchSpirit destroyed) +/// but the game continues (more than one surviving team). +/// +public sealed record PlayerEliminatedPush( + Guid SessionId, + Guid EliminatedAccountId, + int SeatIndex, + int TeamIndex); + +/// Per-player outcome entry for N-player game-over pushes. +public sealed record PlayerOutcomeDto( + Guid AccountId, + string Outcome, // "Winner" | "Loser" + int RankDelta, + int OpDelta); + +/// Pushed to all players when the game ends. 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? PlayerOutcomes = null); /// /// 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 Players, BoardDto? Board, // full board state including tile affinities - IEnumerable SeatOrder, // account IDs in seat/turn order; empty = legacy 1v1 - string GameMode); // "FFA" | "Teams" | "MultiTeam" + IEnumerable SeatOrder, // account IDs in seat/turn order; empty = legacy 1v1 + string GameMode, // "FFA" | "Teams" | "MultiTeam" + Dictionary TeamColors); // teamIndex → hex color e.g. "4488FF" public sealed record PlayerStateDto( Guid AccountId, diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 4568fec..1b28623 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -31,6 +31,12 @@ public sealed class GameState /// "FFA" | "Teams" | "MultiTeam". Used for ability ownership resolution. public string GameMode { get; set; } = "FFA"; + /// + /// Maps TeamIndex → CSS-style hex color string (e.g. "4488FF"). + /// Populated at initialization from the built-in palette; empty for legacy 1v1 games. + /// + public Dictionary TeamColors { get; set; } = new(); + /// Running sequence number for action log / StateVersion. public int NextActionSequence { get; set; } = 1; diff --git a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs index 1ac3c4d..bf44ed5 100644 --- a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs +++ b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs @@ -6,12 +6,27 @@ namespace SOR.Game.Grid; /// public static class BoardShapeGenerator { + /// + /// Returns the recommended board shape for a given player count when none is explicitly specified. + /// + public static string AutoShape(int playerCount) => playerCount switch + { + 3 => "Triangular", + 4 => "Cross", + 5 => "RadialStar", + 6 => "HexRing", + _ => "Rectangle", // 2 and 7–10 + }; + /// Generate a board appropriate for the given shape, rules, and player count. 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), }; /// @@ -81,8 +96,128 @@ public static class BoardShapeGenerator return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones }; } + /// + /// 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. + /// + 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> + { + [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 }; + } + + /// + /// 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). + /// + 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(); + + // 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>(); + + 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 { new Coord(tipX, tipY) }; + } + + return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones }; + } + + /// + /// 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. + /// + 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> + { + [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 CoordsInRect(int x0, int y0, int x1, int y1, int w, int h) + { + var s = new HashSet(); + 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 CoordsInRows(int r0, int r1, int width) { var s = new HashSet(); diff --git a/Server/src/SOR.Game/Handlers/GameAttackHandler.cs b/Server/src/SOR.Game/Handlers/GameAttackHandler.cs index bc50bbc..49ab2f6 100644 --- a/Server/src/SOR.Game/Handlers/GameAttackHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameAttackHandler.cs @@ -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, diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs index 6ebec30..aa62f18 100644 --- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs +++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs @@ -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. /// + /// + /// Returns all player account-ID strings in the session: P1, P2, and any additional players + /// from AdditionalPlayersJson (seats 3+). + /// + private static List GetAllPlayerIds(GameSession session) + { + var ids = new List + { + session.PlayerOneAccountId.ToString(), + session.PlayerTwoAccountId.ToString(), + }; + if (!string.IsNullOrEmpty(session.AdditionalPlayersJson)) + { + try + { + var addl = JsonSerializer.Deserialize>( + 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(); + // 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 - { - 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(); var registry = SpectatorRegistryService.Instance; if (registry != null) @@ -355,4 +390,171 @@ internal abstract class GameHandlerBase EndedAt : session.EndedAt.Value), ct); } + + /// + /// Finalize an N-player game (3+ players or team modes). + /// Applies pairwise ELO: each winner beats every loser individually. + /// Pushes with full list to all participants. + /// + internal static async Task FinalizeMultiPlayerGameAsync( + GameDbContext gameDb, + SorIdentityDbContext identityDb, + IClientPush clientPush, + IEventBus eventBus, + GameSession session, + IReadOnlyList winnerIds, + IReadOnlyList 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( + 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(); + 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(); + + 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); + } + + /// + /// Push a to all active (non-eliminated) players and spectators. + /// Called when a player is knocked out mid-game but the game continues. + /// + 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(); + + 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); + } } diff --git a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs index da81aa3..4c2c61c 100644 --- a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs @@ -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+).