To create a real-time game where players receive randomly assigned instructions, use Socket.IO's event-driven architecture. The server handles game start and refresh events, shuffling the command list and emitting the assignments to all connected clients. The client listens for these events to update the UI with the specific command assigned to the current user.
// Server Side: Handle game start and refresh
socket.on('start_game', (username) => {
if (socket.isAdmin) {
userCommands = assignCommands(users, commands);
io.emit('game_started', userCommands);
io.emit('command_list_update', userCommands);
}
});
socket.on('refresh', (username) => {
if (socket.isAdmin) {
userCommands = assignCommands(users, commands);
io.emit('commands_refreshed', userCommands);
io.emit('command_list_update', userCommands);
}
});
// Client Side: Update UI based on assigned command
socket.on("game_started", userCommands => {
const command = userCommands[username];
document.querySelector("#command").textContent = `${command}`;
});
socket.on("commands_refreshed", userCommands => {
const command = userCommands[username];
document.querySelector("#command").textContent = `${command}`;
});