Implement multiplayer extension: 2-10 players FFA/Team/Multi-Team
Core engine: - Add SeatIndex, TeamIndex, IsEliminated to PlayerState - Add SeatOrder, GameMode to GameState with helpers: ActiveSeats(), GetNextActiveSeat(), GetEnemyIds(), AreAllies() - Add StartingZones to Board for per-seat placement validation - Add BoardShape, PlayerCount to GameRules - New BoardShapeGenerator: Rectangle (up to 4 seats) + Cross shapes - N-player Initialize() overload; old 2-player overload delegates to it - EndTurn uses GetNextActiveSeat() instead of hardcoded GetOpponentId() - Attack finds target across all enemy players; EliminatePlayer() helper allows multi-player elimination without immediate game over - PlaceArchSpirit validates via StartingZones (legacy row fallback preserved) - AbilitySystem.Own() uses AreAllies() for team-aware ownership checks Database: - GameSession: +player_count, +game_mode, +additional_players_json - CustomLobby: +game_mode, +team_count, +additional_players_json - EF migration: AddMultiplayerSlots (applied) Handlers: - GameCreateCustomLobbyHandler: honours MaxPlayers/GameMode/TeamCount from request - GameJoinCustomLobbyHandler: multi-slot join up to MaxPlayers - GameLobbyReadyHandler: N-player all-ready check; seats/team assignment by mode - GameReadyHandler: builds N-player list from AdditionalPlayersJson - GameHandlerBase.LoadActiveSessionAsync: recognises additional players Client: - Game.gd: get_opponents() returns all non-local players; get_opponent() kept as backward-compat alias returning first opponent 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:
@@ -1,6 +1,7 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Database.Contexts;
|
||||
@@ -64,7 +65,18 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
var isHost = lobby.HostAccountId == accountId;
|
||||
var isGuest = lobby.GuestAccountId == accountId;
|
||||
|
||||
if (!isHost && !isGuest)
|
||||
// For 3+ player lobbies, also accept additional players.
|
||||
bool isAdditional = false;
|
||||
if (!isHost && !isGuest && lobby.AdditionalPlayersJson != null)
|
||||
{
|
||||
var addlCheck = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>(
|
||||
lobby.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
isAdditional = addlCheck.Any(p => p.AccountId == accountId);
|
||||
}
|
||||
|
||||
if (!isHost && !isGuest && !isAdditional)
|
||||
throw new GameException("NOT_IN_LOBBY");
|
||||
|
||||
// Update deck and first-turn pref, then mark ready.
|
||||
@@ -83,16 +95,42 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
// Push updated ready status to both participants.
|
||||
// Update readiness in AdditionalPlayersJson for players 3+.
|
||||
if (!isHost && !isGuest && lobby.AdditionalPlayersJson != null)
|
||||
{
|
||||
var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>(
|
||||
lobby.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
var entry = addl.FirstOrDefault(p => p.AccountId == accountId);
|
||||
if (entry != null)
|
||||
entry.IsReady = true;
|
||||
lobby.AdditionalPlayersJson = JsonSerializer.Serialize(addl);
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
// Push updated ready status to all participants.
|
||||
var readyPush = ServerMessage.Push("game.custom.lobby.ready_status",
|
||||
new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady));
|
||||
|
||||
await Task.WhenAll(
|
||||
var pushTasks = new List<Task>
|
||||
{
|
||||
_clientPush.PushAsync(lobby.HostAccountId.ToString(), readyPush, ct),
|
||||
_clientPush.PushAsync(lobby.GuestAccountId!.Value.ToString(), readyPush, ct));
|
||||
};
|
||||
if (lobby.GuestAccountId.HasValue)
|
||||
pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), readyPush, ct));
|
||||
await Task.WhenAll(pushTasks);
|
||||
|
||||
// All-ready check.
|
||||
// All-ready check: host + guest must be ready; for 3+ players all must be ready.
|
||||
bool allReady = lobby.GuestAccountId.HasValue && lobby.HostReady && lobby.GuestReady;
|
||||
if (allReady && lobby.AdditionalPlayersJson != null)
|
||||
{
|
||||
var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>(
|
||||
lobby.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
allReady = addl.All(p => p.IsReady);
|
||||
}
|
||||
|
||||
if (allReady)
|
||||
await StartGameAsync(lobby, accountId, ct);
|
||||
@@ -121,9 +159,30 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
var p1DeckId = playerOneId == lobby.HostAccountId ? lobby.HostDeckId : lobby.GuestDeckId!.Value;
|
||||
var p2DeckId = playerTwoId == lobby.HostAccountId ? lobby.HostDeckId : lobby.GuestDeckId!.Value;
|
||||
|
||||
// Load the admin-configured custom-default ruleset so that lobby fields not
|
||||
// explicitly overridden by the host inherit the current admin settings rather
|
||||
// than the hard-coded GameRules.Default values.
|
||||
// Additional players (seats 2+).
|
||||
var additionalPlayers = string.IsNullOrEmpty(lobby.AdditionalPlayersJson)
|
||||
? new List<AdditionalLobbyPlayer>()
|
||||
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(lobby.AdditionalPlayersJson) ?? new();
|
||||
|
||||
// Build the full ordered player list: [P1, P2, P3, ...].
|
||||
var allPlayerIds = new List<Guid> { playerOneId, playerTwoId };
|
||||
var allDeckIds = new List<Guid> { p1DeckId, p2DeckId };
|
||||
foreach (var ap in additionalPlayers)
|
||||
{
|
||||
allPlayerIds.Add(ap.AccountId);
|
||||
allDeckIds.Add(ap.DeckId);
|
||||
}
|
||||
|
||||
int playerCount = allPlayerIds.Count;
|
||||
int teamCount = Math.Max(1, lobby.TeamCount);
|
||||
|
||||
// Compute team indices based on game mode:
|
||||
// FFA → teamIndex = seatIndex (everyone on own team)
|
||||
// Teams (≥2) → teamIndex = seatIndex % teamCount (alternating assignment)
|
||||
static int ComputeTeamIndex(string gameMode, int seatIndex, int teamCount) =>
|
||||
gameMode == "FFA" ? seatIndex : seatIndex % teamCount;
|
||||
|
||||
// Load the admin-configured custom-default ruleset.
|
||||
var dbDefaults = await _gameDb.GameRuleSets
|
||||
.AsNoTracking()
|
||||
.Where(r => r.IsCustomDefault)
|
||||
@@ -152,15 +211,32 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
StartingRandomTilePct = lobby.StartingRandomTilePctOverride ?? dbDefaults?.StartingRandomTilePct ?? GameRules.Default.StartingRandomTilePct,
|
||||
};
|
||||
|
||||
// Build additional players JSON for the session (seats 2+).
|
||||
string? sessionAdditionalJson = null;
|
||||
if (additionalPlayers.Count > 0)
|
||||
{
|
||||
var sessionAddl = additionalPlayers.Select((ap, i) => new
|
||||
{
|
||||
accountId = ap.AccountId,
|
||||
deckId = ap.DeckId,
|
||||
seatIndex = i + 2,
|
||||
teamIndex = ComputeTeamIndex(lobby.GameMode, i + 2, teamCount),
|
||||
});
|
||||
sessionAdditionalJson = JsonSerializer.Serialize(sessionAddl);
|
||||
}
|
||||
|
||||
var session = new GameSession
|
||||
{
|
||||
PlayerOneAccountId = playerOneId,
|
||||
PlayerOneDeckId = p1DeckId,
|
||||
PlayerTwoAccountId = playerTwoId,
|
||||
PlayerTwoDeckId = p2DeckId,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RuleSnapshotJson = JsonSerializer.Serialize(rules),
|
||||
PlayerOneAccountId = playerOneId,
|
||||
PlayerOneDeckId = p1DeckId,
|
||||
PlayerTwoAccountId = playerTwoId,
|
||||
PlayerTwoDeckId = p2DeckId,
|
||||
PlayerCount = playerCount,
|
||||
GameMode = lobby.GameMode,
|
||||
AdditionalPlayersJson = sessionAdditionalJson,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RuleSnapshotJson = JsonSerializer.Serialize(rules),
|
||||
};
|
||||
|
||||
_gameDb.GameSessions.Add(session);
|
||||
@@ -176,7 +252,7 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
NatsSubjects.GameStarted,
|
||||
new GameStartedEvent(
|
||||
session.Id,
|
||||
new[] { playerOneId, playerTwoId },
|
||||
allPlayerIds.ToArray(),
|
||||
DateTimeOffset.UtcNow),
|
||||
ct);
|
||||
}
|
||||
@@ -187,24 +263,45 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
session.Id);
|
||||
}
|
||||
|
||||
// Fetch display names for both players for the game-started push.
|
||||
var ids = new[] { playerOneId, playerTwoId };
|
||||
var names = await _identityDb.Users
|
||||
// Fetch display names for all players for the game-started push.
|
||||
var allIds = allPlayerIds.ToArray();
|
||||
var names = await _identityDb.Users
|
||||
.AsNoTracking()
|
||||
.Where(a => ids.Contains(a.Id))
|
||||
.Where(a => allIds.Contains(a.Id))
|
||||
.Select(a => new { a.Id, Name = a.DisplayName ?? a.UserName ?? a.Id.ToString().Substring(0, 8) })
|
||||
.ToDictionaryAsync(a => a.Id, a => a.Name, ct);
|
||||
|
||||
var p1Name = names.GetValueOrDefault(playerOneId, playerOneId.ToString()[..8]);
|
||||
var p2Name = names.GetValueOrDefault(playerTwoId, playerTwoId.ToString()[..8]);
|
||||
|
||||
// Push game-started notification to both players.
|
||||
await Task.WhenAll(
|
||||
// Push game-started notification to all players.
|
||||
var startTasks = new List<Task>
|
||||
{
|
||||
_clientPush.PushAsync(playerOneId.ToString(),
|
||||
ServerMessage.Push("game.custom.started",
|
||||
new CustomLobbyGameStartedPush(session.Id, playerTwoId, p2Name)), ct),
|
||||
_clientPush.PushAsync(playerTwoId.ToString(),
|
||||
ServerMessage.Push("game.custom.started",
|
||||
new CustomLobbyGameStartedPush(session.Id, playerOneId, p1Name)), ct),
|
||||
};
|
||||
for (int i = 0; i < additionalPlayers.Count; i++)
|
||||
{
|
||||
var apId = additionalPlayers[i].AccountId;
|
||||
var apName = names.GetValueOrDefault(apId, apId.ToString()[..8]);
|
||||
startTasks.Add(_clientPush.PushAsync(apId.ToString(),
|
||||
ServerMessage.Push("game.custom.started",
|
||||
new CustomLobbyGameStartedPush(session.Id, playerOneId, p1Name)), ct));
|
||||
}
|
||||
await Task.WhenAll(startTasks);
|
||||
}
|
||||
|
||||
// ── Helper types ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Tracks a player's readiness state within AdditionalPlayersJson.</summary>
|
||||
private sealed class AdditionalLobbyPlayerReady
|
||||
{
|
||||
[JsonPropertyName("accountId")] public Guid AccountId { get; set; }
|
||||
[JsonPropertyName("deckId")] public Guid DeckId { get; set; }
|
||||
[JsonPropertyName("isReady")] public bool IsReady { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user