Added support for dynamic room creation

This commit is contained in:
Arne van Iterson 2020-04-24 22:52:55 +02:00
parent b0d0eb01aa
commit 6965c823fc

View File

@ -17,6 +17,12 @@ colours.setTheme({
error: "red"
});
const traffic = {
in: colours.data("-> "),
out: colours.data("<- "),
int: colours.data("-- ")
};
var path = require("path");
// Send html & css files
@ -46,7 +52,7 @@ io.on("connection", (socket) => {
io.in(room).emit("roomUpdate", playerUpdate);
console.log(colours.warn(`User ${String(socket.id)} disconnected from room ${room}`));
console.log(traffic.out + colours.warn(`User ${String(socket.id)} disconnected from room ${room}`));
});
// Request identification
@ -54,32 +60,58 @@ io.on("connection", (socket) => {
// Wait for identification
socket.on("identification", (data) => {
var room;
switch (data.gamemode) {
case 2:
room = "2_01";
break;
case 4:
room = "4_01";
break;
console.log(traffic.in + colours.info(`User ${String(socket.id)} trying to join with gamemode ${data.gamemode}`));
// Define room to be joined
var join = "";
// Check if there are any available rooms for the requested gamemode
for (const room in io.sockets.adapter.rooms) {
if (/[0-9]_[0-9].*/i.test(room)) {
var roomId = room.split("_");
if (roomId[0] == data.gamemode) {
if (Object.keys(io.sockets.adapter.rooms[room].sockets).length <= data.gamemode) {
join = room;
// Start game if the max number of players is reached
if (Object.keys(io.sockets.adapter.rooms[room].sockets).length == data.gamemode) {
io.in(room).emit("gameStart");
}
} else {
console.log(traffic.int + colours.warn(`Room ${room} is full, skipping.`));
}
}
}
}
socket.join(room);
// If no available room is found, make one
if (join == "") {
var count = 0;
var regex = new RegExp(data.gamemode + "_[0-9].*");
Object.keys(io.sockets.adapter.rooms).forEach(room => {
if (regex.test(room)) {
count++;
}
});
join = data.gamemode + "_" + count;
console.log(traffic.int + colours.warn(`There is no room available for the requested gamemode, making ${join}`));
}
socket.join(join);
players[socket.id] = {
username: data.name,
controls: data.controls,
room: room
room: join
};
var playerUpdate = {};
for (const id in io.sockets.adapter.rooms[room].sockets) {
for (const id in io.sockets.adapter.rooms[join].sockets) {
playerUpdate[id] = players[id];
}
io.in(room).emit("roomUpdate", playerUpdate);
io.in(join).emit("roomUpdate", playerUpdate);
console.log(colours.help(`User ${String(socket.id)} connected to room ${room}`));
console.log(traffic.in + colours.help(`User ${String(socket.id)} connected to room ${join}`));
});
socket.on("update", (data) => {