refactor: update player handling and dashboard display in client and server
This commit is contained in:
15
server.js
15
server.js
@@ -156,6 +156,7 @@ function createRoom(name, host) {
|
||||
timeline: {}, // playerId -> [{trackId, year, title, artist}]
|
||||
tokens: {}, // playerId -> number
|
||||
ready: { [host.id]: false }, // playerId -> boolean
|
||||
spectators: {}, // playerId -> boolean (joined after game start)
|
||||
phase: 'guess', // 'guess' | 'reveal'
|
||||
lastResult: null, // { playerId, correct }
|
||||
trackStartAt: null, // ms epoch for synced start time
|
||||
@@ -186,6 +187,7 @@ function roomSummary(room) {
|
||||
name: p.name,
|
||||
connected: p.connected,
|
||||
ready: !!room.state.ready?.[p.id],
|
||||
spectator: !!room.state.spectators?.[p.id] || !!p.spectator,
|
||||
})),
|
||||
state: room.state,
|
||||
};
|
||||
@@ -331,6 +333,14 @@ wss.on('connection', (ws) => {
|
||||
room.players.set(player.id, player);
|
||||
player.roomId = room.id;
|
||||
room.state.ready[player.id] = false;
|
||||
// If the game already started, mark as spectator
|
||||
if (room.state.status === 'playing' || room.state.status === 'ended') {
|
||||
room.state.spectators[player.id] = true;
|
||||
player.spectator = true;
|
||||
} else {
|
||||
delete room.state.spectators[player.id];
|
||||
player.spectator = false;
|
||||
}
|
||||
broadcast(room, 'room_update', { room: roomSummary(room) });
|
||||
return;
|
||||
}
|
||||
@@ -342,6 +352,7 @@ wss.on('connection', (ws) => {
|
||||
room.players.delete(player.id);
|
||||
player.roomId = null;
|
||||
if (room.state.ready) delete room.state.ready[player.id];
|
||||
if (room.state.spectators) delete room.state.spectators[player.id];
|
||||
if (room.players.size === 0) rooms.delete(room.id);
|
||||
else broadcast(room, 'room_update', { room: roomSummary(room) });
|
||||
return;
|
||||
@@ -361,7 +372,9 @@ wss.on('connection', (ws) => {
|
||||
if (!room) return;
|
||||
if (room.hostId !== player.id) return send('error', { message: 'Only host can start' });
|
||||
// All players must be ready
|
||||
const pids = [...room.players.keys()];
|
||||
const pids = [...room.players.values()]
|
||||
.filter(p => !room.state.spectators?.[p.id])
|
||||
.map(p => p.id);
|
||||
const allReady = pids.every((pid) => !!room.state.ready?.[pid]);
|
||||
if (!allReady) return send('error', { message: 'All players must be ready' });
|
||||
room.state.status = 'playing';
|
||||
|
||||
Reference in New Issue
Block a user