Fix 3+ player custom lobby state/ready sync

This commit is contained in:
Shard
2026-03-27 00:47:48 +00:00
parent 4737d337fa
commit 32aa8165bb
6 changed files with 96 additions and 47 deletions
+16 -3
View File
@@ -148,6 +148,7 @@ func join(lid: String, deck_id: String, password: String,
lobby["guestAccountId"] = str(d.get("guestAccountId", "")) lobby["guestAccountId"] = str(d.get("guestAccountId", ""))
lobby["guestDisplayName"] = str(d.get("guestDisplayName", "")) lobby["guestDisplayName"] = str(d.get("guestDisplayName", ""))
lobby["hasGuest"] = true lobby["hasGuest"] = true
lobby["additionalPlayers"] = d.get("additionalPlayers", [])
if on_success.is_valid(): on_success.call(d), if on_success.is_valid(): on_success.call(d),
func(code: String, msg: String) -> void: func(code: String, msg: String) -> void:
print("[CustomLobby] ERR join ", code, " ", msg) print("[CustomLobby] ERR join ", code, " ", msg)
@@ -287,6 +288,13 @@ func _on_server_push(type: String, payload: Variant) -> void:
var d := payload as Dictionary var d := payload as Dictionary
var gid : String = str(d.get("guestAccountId", "")) var gid : String = str(d.get("guestAccountId", ""))
var gname: String = str(d.get("guestDisplayName", gid.substr(0, 8))) var gname: String = str(d.get("guestDisplayName", gid.substr(0, 8)))
# Keep local lobby snapshot current so LobbyRoomScreen can render seat updates.
if d.has("additionalPlayers"):
lobby["additionalPlayers"] = d.get("additionalPlayers", [])
if str(lobby.get("guestAccountId", "")).is_empty():
lobby["guestAccountId"] = gid
lobby["guestDisplayName"] = gname
lobby["hasGuest"] = true
guest_joined.emit(gid, gname) guest_joined.emit(gid, gname)
"game.custom.lobby_updated": "game.custom.lobby_updated":
@@ -304,13 +312,18 @@ func _on_server_push(type: String, payload: Variant) -> void:
var d := payload as Dictionary var d := payload as Dictionary
var hr : bool = d.get("hostReady", false) var hr : bool = d.get("hostReady", false)
var gr : bool = d.get("guestReady", false) var gr : bool = d.get("guestReady", false)
if d.has("additionalPlayers"):
lobby["additionalPlayers"] = d.get("additionalPlayers", [])
if is_host: if is_host:
i_am_ready = hr i_am_ready = hr
partner_ready = gr partner_ready = gr
elif is_additional: elif is_additional:
# Additional players (3rd+) are neither host nor guest. # Additional players (3rd+) resolve self-ready from the participant snapshot when present.
# Their own ready state is managed by the set_ready ack — don't overwrite it. if d.has("additionalPlayers"):
# partner_ready reflects whether the two main slots are ready. for ap: Dictionary in (d.get("additionalPlayers", []) as Array):
if str(ap.get("accountId", "")) == Auth.user_id:
i_am_ready = bool(ap.get("isReady", false))
break
partner_ready = hr and gr partner_ready = hr and gr
else: else:
# First guest # First guest
@@ -310,6 +310,8 @@ func _on_guest_joined(_guest_account_id: String, _guest_display_name: String) ->
func _on_ready_status_changed(host_ready: bool, guest_ready: bool) -> void: func _on_ready_status_changed(host_ready: bool, guest_ready: bool) -> void:
_update_ready_indicators(host_ready, guest_ready) _update_ready_indicators(host_ready, guest_ready)
# Additional-player readiness can change via ready_status pushes.
_refresh_display()
func _on_rules_updated(new_rules: Dictionary) -> void: func _on_rules_updated(new_rules: Dictionary) -> void:
+16 -4
View File
@@ -133,7 +133,7 @@ public sealed record JoinCustomLobbyRequest(Guid LobbyId, Guid DeckId, string? P
/// <summary> /// <summary>
/// Serialized JSON entry in CustomLobby.AdditionalPlayersJson and GameSession.AdditionalPlayersJson. /// Serialized JSON entry in CustomLobby.AdditionalPlayersJson and GameSession.AdditionalPlayersJson.
/// </summary> /// </summary>
public sealed record AdditionalLobbyPlayer(Guid AccountId, Guid DeckId); public sealed record AdditionalLobbyPlayer(Guid AccountId, Guid DeckId, bool IsReady = false);
/// <summary>Leave or cancel a custom lobby.</summary> /// <summary>Leave or cancel a custom lobby.</summary>
public sealed record LeaveCustomLobbyRequest(Guid LobbyId); public sealed record LeaveCustomLobbyRequest(Guid LobbyId);
@@ -262,7 +262,8 @@ public sealed record JoinCustomLobbyResponse(
int MaxPlayers, int MaxPlayers,
string GameMode, string GameMode,
int TeamCount, int TeamCount,
bool IsAdditionalPlayer = false); // true for 3rd+ players (not host or first guest) bool IsAdditionalPlayer = false, // true for 3rd+ players (not host or first guest)
IEnumerable<AdditionalLobbyPlayerViewDto>? AdditionalPlayers = null);
public sealed record LeaveCustomLobbyResponse(Guid LobbyId); public sealed record LeaveCustomLobbyResponse(Guid LobbyId);
@@ -393,7 +394,8 @@ public sealed record CustomLobbyGuestJoinedPush(
Guid LobbyId, Guid LobbyId,
Guid GuestAccountId, Guid GuestAccountId,
string GuestDisplayName, string GuestDisplayName,
string LobbyName); string LobbyName,
IEnumerable<AdditionalLobbyPlayerViewDto>? AdditionalPlayers = null);
/// <summary> /// <summary>
/// Pushed to the non-proposing participant when the host proposes loading a preset. /// Pushed to the non-proposing participant when the host proposes loading a preset.
@@ -414,7 +416,11 @@ public sealed record LobbyUpdatedPush(Guid LobbyId, CustomRulesDto NewRules);
public sealed record PresetVoteRejectedPush(Guid LobbyId, Guid PresetId); public sealed record PresetVoteRejectedPush(Guid LobbyId, Guid PresetId);
/// <summary>Pushed to both participants whenever a lobby participant's ready status changes.</summary> /// <summary>Pushed to both participants whenever a lobby participant's ready status changes.</summary>
public sealed record LobbyReadyStatusPush(Guid LobbyId, bool HostReady, bool GuestReady); public sealed record LobbyReadyStatusPush(
Guid LobbyId,
bool HostReady,
bool GuestReady,
IEnumerable<AdditionalLobbyPlayerViewDto>? AdditionalPlayers = null);
/// <summary>Pushed to both participants when a lobby participant changes their selected deck.</summary> /// <summary>Pushed to both participants when a lobby participant changes their selected deck.</summary>
public sealed record LobbyDeckChangedPush(Guid LobbyId, Guid AccountId, Guid DeckId); public sealed record LobbyDeckChangedPush(Guid LobbyId, Guid AccountId, Guid DeckId);
@@ -621,6 +627,12 @@ public sealed record TileDto(
/// <summary>Client-facing 2D coordinate.</summary> /// <summary>Client-facing 2D coordinate.</summary>
public sealed record CoordDto(int X, int Y); public sealed record CoordDto(int X, int Y);
/// <summary>Client-facing additional (3rd+) custom-lobby participant.</summary>
public sealed record AdditionalLobbyPlayerViewDto(
Guid AccountId,
string DisplayName,
bool IsReady);
public sealed record CustomLobbyDto( public sealed record CustomLobbyDto(
Guid LobbyId, Guid LobbyId,
string LobbyName, string LobbyName,
@@ -61,7 +61,9 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
// Compute current player count: host + guest slot + additional slots. // Compute current player count: host + guest slot + additional slots.
var additionalPlayers = string.IsNullOrEmpty(lobby.AdditionalPlayersJson) var additionalPlayers = string.IsNullOrEmpty(lobby.AdditionalPlayersJson)
? new List<AdditionalLobbyPlayer>() ? new List<AdditionalLobbyPlayer>()
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(lobby.AdditionalPlayersJson) ?? new(); : JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new();
int currentCount = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + additionalPlayers.Count; int currentCount = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + additionalPlayers.Count;
@@ -149,13 +151,21 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
var hostName = names.GetValueOrDefault(lobby.HostAccountId, lobby.HostAccountId.ToString()[..8]); var hostName = names.GetValueOrDefault(lobby.HostAccountId, lobby.HostAccountId.ToString()[..8]);
var guestName = names.GetValueOrDefault(accountId, accountId.ToString()[..8]); var guestName = names.GetValueOrDefault(accountId, accountId.ToString()[..8]);
var additionalViews = additionalPlayers
.Select(p => new AdditionalLobbyPlayerViewDto(
p.AccountId,
names.GetValueOrDefault(p.AccountId, p.AccountId.ToString()[..8]),
p.IsReady))
.ToList();
// Notify all existing lobby members that a new player has joined. // Notify all existing lobby members that a new player has joined.
var joinPush = ServerMessage.Push("game.custom.lobby.guest_joined", var joinPush = ServerMessage.Push("game.custom.lobby.guest_joined",
new CustomLobbyGuestJoinedPush( new CustomLobbyGuestJoinedPush(
LobbyId : lobby.Id, LobbyId : lobby.Id,
GuestAccountId : accountId, GuestAccountId : accountId,
GuestDisplayName: guestName, GuestDisplayName: guestName,
LobbyName : lobby.Name)); LobbyName : lobby.Name,
AdditionalPlayers: additionalViews));
var notifyTasks = new List<Task> var notifyTasks = new List<Task>
{ {
@@ -180,6 +190,7 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
MaxPlayers : lobby.MaxPlayers, MaxPlayers : lobby.MaxPlayers,
GameMode : lobby.GameMode, GameMode : lobby.GameMode,
TeamCount : lobby.TeamCount, TeamCount : lobby.TeamCount,
IsAdditionalPlayer : !isFirstGuest)); IsAdditionalPlayer : !isFirstGuest,
AdditionalPlayers : additionalViews));
} }
} }
@@ -1,7 +1,6 @@
namespace SOR.Game.Handlers; namespace SOR.Game.Handlers;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SOR.Database.Contexts; using SOR.Database.Contexts;
@@ -70,7 +69,7 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
bool isAdditional = false; bool isAdditional = false;
if (!isHost && !isGuest && lobby.AdditionalPlayersJson != null) if (!isHost && !isGuest && lobby.AdditionalPlayersJson != null)
{ {
var addlCheck = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>( var addlCheck = JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson, lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new(); ?? new();
@@ -103,23 +102,43 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
// Update readiness and deck in AdditionalPlayersJson for players 3+. // Update readiness and deck in AdditionalPlayersJson for players 3+.
if (isAdditional && lobby.AdditionalPlayersJson != null) if (isAdditional && lobby.AdditionalPlayersJson != null)
{ {
var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>( var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson, lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new(); ?? new();
var entry = addl.FirstOrDefault(p => p.AccountId == accountId); var idx = addl.FindIndex(p => p.AccountId == accountId);
if (entry != null) if (idx >= 0)
{ addl[idx] = addl[idx] with { IsReady = true, DeckId = req.DeckId };
entry.IsReady = true;
entry.DeckId = req.DeckId;
}
lobby.AdditionalPlayersJson = JsonSerializer.Serialize(addl); lobby.AdditionalPlayersJson = JsonSerializer.Serialize(addl);
await _gameDb.SaveChangesAsync(ct); await _gameDb.SaveChangesAsync(ct);
} }
// Build additional-player readiness snapshot for pushes.
var addlPush = lobby.AdditionalPlayersJson is null
? new List<AdditionalLobbyPlayer>()
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new();
var addlIds = addlPush.Select(p => p.AccountId).Distinct().ToArray();
var addlNames = addlIds.Length == 0
? new Dictionary<Guid, string>()
: await _identityDb.Users
.AsNoTracking()
.Where(u => addlIds.Contains(u.Id))
.Select(u => new { u.Id, Name = u.DisplayName ?? u.UserName ?? u.Id.ToString().Substring(0, 8) })
.ToDictionaryAsync(u => u.Id, u => u.Name, ct);
var additionalViews = addlPush
.Select(p => new AdditionalLobbyPlayerViewDto(
p.AccountId,
addlNames.GetValueOrDefault(p.AccountId, p.AccountId.ToString()[..8]),
p.IsReady))
.ToList();
// Push updated ready status to all participants (host, guest, and additional players). // Push updated ready status to all participants (host, guest, and additional players).
var readyPush = ServerMessage.Push("game.custom.lobby.ready_status", var readyPush = ServerMessage.Push("game.custom.lobby.ready_status",
new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady)); new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady, additionalViews));
var pushTasks = new List<Task> var pushTasks = new List<Task>
{ {
@@ -127,22 +146,15 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
}; };
if (lobby.GuestAccountId.HasValue) if (lobby.GuestAccountId.HasValue)
pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), readyPush, ct)); pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), readyPush, ct));
if (lobby.AdditionalPlayersJson != null) foreach (var ap in addlPush)
{ pushTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), readyPush, ct));
var addlPush = JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (addlPush != null)
foreach (var ap in addlPush)
pushTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), readyPush, ct));
}
await Task.WhenAll(pushTasks); await Task.WhenAll(pushTasks);
// All-ready check: host + guest must be ready; for 3+ players all must be ready. // All-ready check: host + guest must be ready; for 3+ players all must be ready.
bool allReady = lobby.GuestAccountId.HasValue && lobby.HostReady && lobby.GuestReady; bool allReady = lobby.GuestAccountId.HasValue && lobby.HostReady && lobby.GuestReady;
if (allReady && lobby.AdditionalPlayersJson != null) if (allReady && lobby.AdditionalPlayersJson != null)
{ {
var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>( var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson, lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new(); ?? new();
@@ -323,13 +335,4 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
await Task.WhenAll(startTasks); 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; }
}
} }
@@ -80,8 +80,21 @@ internal sealed class GameUnreadyHandler : GameHandlerBase, IMessageHandler
await _gameDb.SaveChangesAsync(ct); await _gameDb.SaveChangesAsync(ct);
var addlList = lobby.AdditionalPlayersJson is null
? new List<AdditionalLobbyPlayer>()
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
lobby.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new();
var additionalViews = addlList
.Select(p => new AdditionalLobbyPlayerViewDto(
p.AccountId,
p.AccountId.ToString()[..8],
p.IsReady))
.ToList();
var readyPush = ServerMessage.Push("game.custom.lobby.ready_status", var readyPush = ServerMessage.Push("game.custom.lobby.ready_status",
new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady)); new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady, additionalViews));
var pushTasks = new List<Task> var pushTasks = new List<Task>
{ {
@@ -89,13 +102,8 @@ internal sealed class GameUnreadyHandler : GameHandlerBase, IMessageHandler
}; };
if (lobby.GuestAccountId.HasValue) if (lobby.GuestAccountId.HasValue)
pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), readyPush, ct)); pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), readyPush, ct));
if (lobby.AdditionalPlayersJson != null) foreach (var ap in addlList)
{ pushTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), readyPush, ct));
var addlList = JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(lobby.AdditionalPlayersJson);
if (addlList != null)
foreach (var ap in addlList)
pushTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), readyPush, ct));
}
await Task.WhenAll(pushTasks); await Task.WhenAll(pushTasks);
return ServerMessage.Reply("game.custom.lobby.unready.ack", message.Seq, return ServerMessage.Reply("game.custom.lobby.unready.ack", message.Seq,