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