2020-04-09 12:04:20 +00:00
|
|
|
const chars = require('./characters.json');
|
2020-04-09 10:42:19 +00:00
|
|
|
const rooms = {};
|
|
|
|
|
2020-04-09 12:16:21 +00:00
|
|
|
function shuffle(a) {
|
|
|
|
for (let i = a.length - 1; i > 0; i--) {
|
|
|
|
const j = Math.floor(Math.random() * (i + 1));
|
|
|
|
[a[i], a[j]] = [a[j], a[i]];
|
|
|
|
}
|
|
|
|
return a;
|
|
|
|
}
|
|
|
|
|
2020-04-09 10:53:21 +00:00
|
|
|
function getOrCreateRoom(roomId) {
|
2020-04-09 10:42:19 +00:00
|
|
|
let room = rooms[roomId];
|
|
|
|
|
|
|
|
if (!room) {
|
|
|
|
room = {
|
|
|
|
roomId: roomId,
|
2020-04-09 12:04:20 +00:00
|
|
|
participants: [],
|
2020-04-09 15:38:44 +00:00
|
|
|
audience: [],
|
2020-04-09 12:16:21 +00:00
|
|
|
characters: shuffle(chars)
|
2020-04-09 10:42:19 +00:00
|
|
|
};
|
|
|
|
rooms[roomId] = room;
|
|
|
|
}
|
|
|
|
|
|
|
|
return room;
|
|
|
|
}
|
|
|
|
|
2020-04-09 10:53:21 +00:00
|
|
|
function addParticipant(roomId, participantId, participantName) {
|
|
|
|
let room = getOrCreateRoom(roomId);
|
|
|
|
|
|
|
|
room.participants.push({
|
|
|
|
participantId,
|
|
|
|
participantName,
|
2020-04-09 12:16:21 +00:00
|
|
|
character: room.characters[room.participants.length]
|
2020-04-09 10:53:21 +00:00
|
|
|
});
|
2020-04-09 10:42:19 +00:00
|
|
|
|
2020-04-09 10:53:21 +00:00
|
|
|
rooms[roomId] = room;
|
|
|
|
}
|
|
|
|
|
2020-04-09 15:14:45 +00:00
|
|
|
function addParticipantWS(roomId, participantId, ws) {
|
|
|
|
let room = getOrCreateRoom(roomId);
|
|
|
|
room.participants.find(p => p.participantId === participantId).ws = ws;
|
|
|
|
}
|
|
|
|
|
2020-04-09 15:38:44 +00:00
|
|
|
function addAudienceWS(roomId, ws) {
|
|
|
|
let room = getOrCreateRoom(roomId);
|
|
|
|
room.audience.push(ws);
|
|
|
|
}
|
|
|
|
|
2020-04-09 15:26:47 +00:00
|
|
|
function buzz(roomId, participant) {
|
|
|
|
let room = getOrCreateRoom(roomId);
|
|
|
|
room.participants.forEach(p => {
|
|
|
|
if (p.ws) {
|
|
|
|
p.ws.send(JSON.stringify({
|
|
|
|
type: "buzz",
|
|
|
|
participant: participant.participantName
|
|
|
|
}));
|
|
|
|
}
|
2020-04-09 15:38:44 +00:00
|
|
|
});
|
|
|
|
room.audience.forEach(ws => {
|
|
|
|
ws.send(JSON.stringify({
|
|
|
|
type: "buzz",
|
|
|
|
participant: participant
|
|
|
|
}));
|
|
|
|
});
|
2020-04-09 15:26:47 +00:00
|
|
|
}
|
|
|
|
|
2020-04-09 15:38:44 +00:00
|
|
|
module.exports = {getOrCreateRoom, addParticipant, addParticipantWS, addAudienceWS, buzz}
|