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>
182 lines
9.3 KiB
C#
182 lines
9.3 KiB
C#
namespace SOR.Game.Handlers;
|
|
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using SOR.Database.Contexts;
|
|
using SOR.Database.Enums;
|
|
using SOR.Networking.Abstractions.Messaging;
|
|
using SOR.Networking.Abstractions.Push;
|
|
using SOR.Networking.Abstractions.Transport;
|
|
using SOR.Shared.Networking;
|
|
|
|
/// <summary>
|
|
/// game.custom.join — guest joins an open custom lobby with their chosen deck.
|
|
///
|
|
/// When the guest joins, the lobby transitions to Full and both players enter
|
|
/// the lobby room. The game does NOT start here — both players must mark themselves
|
|
/// ready via game.custom.lobby.ready before the GameSession is created.
|
|
/// </summary>
|
|
internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHandler
|
|
{
|
|
private readonly IMessageSerializer _serializer;
|
|
private readonly GameDbContext _gameDb;
|
|
private readonly SorIdentityDbContext _identityDb;
|
|
private readonly IClientPush _clientPush;
|
|
|
|
public GameJoinCustomLobbyHandler(
|
|
IMessageSerializer serializer,
|
|
GameDbContext gameDb,
|
|
SorIdentityDbContext identityDb,
|
|
IClientPush clientPush)
|
|
{
|
|
_serializer = serializer;
|
|
_gameDb = gameDb;
|
|
_identityDb = identityDb;
|
|
_clientPush = clientPush;
|
|
}
|
|
|
|
public string MessageType => "game.custom.join";
|
|
|
|
public async Task<IServerMessage?> HandleAsync(
|
|
IClientMessage message,
|
|
AuthenticatedConnection connection,
|
|
CancellationToken ct)
|
|
{
|
|
var req = _serializer.DeserializePayload<JoinCustomLobbyRequest>(message.Payload);
|
|
var accountId = Guid.Parse(connection.UserId);
|
|
|
|
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
|
|
?? throw new GameException("LOBBY_NOT_FOUND");
|
|
|
|
if (lobby.Status != CustomLobbyStatus.Open)
|
|
throw new GameException("LOBBY_NOT_OPEN");
|
|
|
|
if (lobby.HostAccountId == accountId)
|
|
throw new GameException("CANNOT_JOIN_OWN_LOBBY");
|
|
|
|
// Password check.
|
|
if (lobby.Password != null && lobby.Password != req.Password)
|
|
throw new GameException("WRONG_PASSWORD");
|
|
|
|
// Compute current player count: host + guest slot + additional slots.
|
|
var additionalPlayers = string.IsNullOrEmpty(lobby.AdditionalPlayersJson)
|
|
? new List<AdditionalLobbyPlayer>()
|
|
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(lobby.AdditionalPlayersJson) ?? new();
|
|
|
|
int currentCount = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + additionalPlayers.Count;
|
|
|
|
if (currentCount >= lobby.MaxPlayers)
|
|
throw new GameException("LOBBY_FULL");
|
|
|
|
// Check not already in lobby.
|
|
if (lobby.GuestAccountId == accountId ||
|
|
additionalPlayers.Any(p => p.AccountId == accountId))
|
|
throw new GameException("ALREADY_IN_LOBBY");
|
|
|
|
bool isFirstGuest = !lobby.GuestAccountId.HasValue;
|
|
|
|
if (isFirstGuest)
|
|
{
|
|
// Seat as primary guest.
|
|
lobby.GuestAccountId = accountId;
|
|
lobby.GuestDeckId = req.DeckId;
|
|
}
|
|
else
|
|
{
|
|
// Add to additional players list.
|
|
additionalPlayers.Add(new AdditionalLobbyPlayer(accountId, req.DeckId));
|
|
lobby.AdditionalPlayersJson = JsonSerializer.Serialize(additionalPlayers);
|
|
}
|
|
|
|
int newCount = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + additionalPlayers.Count;
|
|
|
|
// Transition to Full only when the last seat is taken.
|
|
if (newCount >= lobby.MaxPlayers)
|
|
{
|
|
lobby.Status = CustomLobbyStatus.Full;
|
|
// Reset readiness — joining always starts a fresh ready-up cycle.
|
|
lobby.HostReady = false;
|
|
lobby.GuestReady = false;
|
|
lobby.HostFirstTurnPref = null;
|
|
lobby.GuestFirstTurnPref = null;
|
|
}
|
|
|
|
await _gameDb.SaveChangesAsync(ct);
|
|
|
|
// Load admin custom-default rules so the join response matches
|
|
// the same 3-tier fallback used when the game actually starts.
|
|
var dbDefaults = await _gameDb.GameRuleSets
|
|
.AsNoTracking()
|
|
.Where(r => r.IsCustomDefault)
|
|
.FirstOrDefaultAsync(ct);
|
|
|
|
// Build effective rules: lobby override → admin custom-default → hard-coded default.
|
|
var effective = new GameRules
|
|
{
|
|
OpeningHandSize = lobby.OpeningHandSizeOverride ?? dbDefaults?.OpeningHandSize ?? GameRules.Default.OpeningHandSize,
|
|
FirstPlayerSkipsDraw = lobby.FirstPlayerSkipsDrawOverride ?? dbDefaults?.FirstPlayerSkipsDraw ?? GameRules.Default.FirstPlayerSkipsDraw,
|
|
SpAccumulationPerTurn = lobby.SpAccumulationPerTurnOverride ?? dbDefaults?.SpAccumulationPerTurn ?? GameRules.Default.SpAccumulationPerTurn,
|
|
DrawPerTurn = lobby.DrawPerTurnOverride ?? dbDefaults?.DrawPerTurn ?? GameRules.Default.DrawPerTurn,
|
|
SpHasCap = lobby.SpHasCapOverride ?? dbDefaults?.SpHasCap ?? GameRules.Default.SpHasCap,
|
|
SpCap = lobby.SpCapOverride ?? dbDefaults?.SpCap ?? GameRules.Default.SpCap,
|
|
BoardWidth = lobby.BoardWidthOverride ?? dbDefaults?.BoardWidth ?? GameRules.Default.BoardWidth,
|
|
BoardHeight = lobby.BoardHeightOverride ?? dbDefaults?.BoardHeight ?? GameRules.Default.BoardHeight,
|
|
HandSizeCap = lobby.HandSizeCapOverride ?? dbDefaults?.HandSizeCap ?? GameRules.Default.HandSizeCap,
|
|
DiscardOnMaxHand = lobby.DiscardOnMaxHandOverride ?? dbDefaults?.DiscardOnMaxHand ?? GameRules.Default.DiscardOnMaxHand,
|
|
MaxDeckSize = lobby.MaxDeckSizeOverride ?? dbDefaults?.MaxDeckSize ?? GameRules.Default.MaxDeckSize,
|
|
MinDeckSize = lobby.MinDeckSizeOverride ?? dbDefaults?.MinDeckSize ?? GameRules.Default.MinDeckSize,
|
|
MaxArchTier1 = lobby.MaxArchTier1Override ?? dbDefaults?.MaxArchTier1 ?? GameRules.Default.MaxArchTier1,
|
|
TurnTimerSeconds = lobby.TurnTimerSecondsOverride ?? dbDefaults?.TurnTimerSeconds ?? GameRules.Default.TurnTimerSeconds,
|
|
TimeLimitMinutes = lobby.TimeLimitMinutesOverride ?? dbDefaults?.TimeLimitMinutes ?? GameRules.Default.TimeLimitMinutes,
|
|
TurnLimit = lobby.TurnLimitOverride ?? dbDefaults?.TurnLimit ?? GameRules.Default.TurnLimit,
|
|
MpBuff = lobby.MpBuffOverride ?? dbDefaults?.MpBuff ?? GameRules.Default.MpBuff,
|
|
StartingRandomTilePct = lobby.StartingRandomTilePctOverride ?? dbDefaults?.StartingRandomTilePct ?? GameRules.Default.StartingRandomTilePct,
|
|
};
|
|
|
|
// Fetch display names for all current lobby members.
|
|
var allMemberIds = new List<Guid> { lobby.HostAccountId };
|
|
if (lobby.GuestAccountId.HasValue) allMemberIds.Add(lobby.GuestAccountId.Value);
|
|
foreach (var ap in additionalPlayers) allMemberIds.Add(ap.AccountId);
|
|
allMemberIds.Add(accountId); // ensure joiner is included
|
|
|
|
var allIds = allMemberIds.Distinct().ToArray();
|
|
var names = await _identityDb.Users
|
|
.AsNoTracking()
|
|
.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 hostName = names.GetValueOrDefault(lobby.HostAccountId, lobby.HostAccountId.ToString()[..8]);
|
|
var guestName = names.GetValueOrDefault(accountId, accountId.ToString()[..8]);
|
|
|
|
// Notify all existing lobby members that a new player has joined.
|
|
var joinPush = ServerMessage.Push("game.custom.lobby.guest_joined",
|
|
new CustomLobbyGuestJoinedPush(
|
|
LobbyId : lobby.Id,
|
|
GuestAccountId : accountId,
|
|
GuestDisplayName: guestName,
|
|
LobbyName : lobby.Name));
|
|
|
|
var notifyTasks = new List<Task>
|
|
{
|
|
_clientPush.PushAsync(lobby.HostAccountId.ToString(), joinPush, ct),
|
|
};
|
|
if (lobby.GuestAccountId.HasValue && lobby.GuestAccountId.Value != accountId)
|
|
notifyTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), joinPush, ct));
|
|
foreach (var ap in additionalPlayers.Where(p => p.AccountId != accountId))
|
|
notifyTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), joinPush, ct));
|
|
await Task.WhenAll(notifyTasks);
|
|
|
|
return ServerMessage.Reply("game.custom.join.ack", message.Seq,
|
|
new JoinCustomLobbyResponse(
|
|
LobbyId : lobby.Id,
|
|
Status : lobby.Status == CustomLobbyStatus.Full ? "WaitingForReady" : "WaitingForPlayers",
|
|
ActiveRules : GameCreateCustomLobbyHandler.ToDto(effective, lobby.Password != null),
|
|
GameSessionId : null,
|
|
HostAccountId : lobby.HostAccountId,
|
|
HostDisplayName : hostName,
|
|
GuestAccountId : accountId,
|
|
GuestDisplayName: guestName));
|
|
}
|
|
}
|