93 lines
2.4 KiB
JavaScript
93 lines
2.4 KiB
JavaScript
let rooms = {};
|
|
|
|
module.exports.roomExists = (roomId) => rooms[roomId] !== undefined;
|
|
|
|
module.exports.isRoomOpen = (roomId) => rooms[roomId] && rooms[roomId].state === 'waiting';
|
|
|
|
module.exports.connectUserToRoom = (roomId, user) => {
|
|
roomId = roomId.toUpperCase();
|
|
if (rooms[roomId]) {
|
|
rooms[roomId].members.push({...user, creator: false});
|
|
} else {
|
|
rooms[roomId] = {
|
|
members: [{...user, creator: true}],
|
|
settings: {},
|
|
state: 'waiting'
|
|
};
|
|
}
|
|
console.log(`User ${user.name} connected to room ${roomId}`);
|
|
}
|
|
|
|
module.exports.getUserRoom = (userId) => {
|
|
for (const roomId in rooms) {
|
|
const room = rooms[roomId];
|
|
const memberIndex = room.members.findIndex(member => member.id === userId);
|
|
|
|
if (memberIndex !== -1) return roomId;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
module.exports.getRoomUsers = (roomId) => {
|
|
if (rooms[roomId]) {
|
|
return rooms[roomId].members;
|
|
}
|
|
return [];
|
|
}
|
|
|
|
module.exports.getRoomCreator = (roomId) => {
|
|
if (rooms[roomId]) {
|
|
return rooms[roomId].members.find(member => member.creator);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
module.exports.isUserHost = (userId) => {
|
|
for (const roomId in rooms) {
|
|
const room = rooms[roomId];
|
|
const member = room.members.find(m => m.id === userId);
|
|
if (member && member.creator) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
module.exports.startGame = (roomId) => {
|
|
if (rooms[roomId]) {
|
|
rooms[roomId].state = 'playing';
|
|
console.log(`Game started in room ${roomId}`);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
module.exports.getRoomState = (roomId) => {
|
|
if (rooms[roomId]) {
|
|
return rooms[roomId].state;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
module.exports.disconnectUser = (userId) => {
|
|
for (const roomId in rooms) {
|
|
const room = rooms[roomId];
|
|
const memberIndex = room.members.findIndex(member => member.id === userId);
|
|
|
|
if (memberIndex !== -1) {
|
|
if (room.members[memberIndex].creator && room.members.length > 1) {
|
|
room.members[1].creator = true;
|
|
}
|
|
|
|
room.members.splice(memberIndex, 1);
|
|
console.log(`User ${userId} disconnected from room ${roomId}`);
|
|
|
|
if (room.members.length === 0) {
|
|
delete rooms[roomId];
|
|
console.log(`Room ${roomId} deleted because it's empty`);
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
} |