following application: Users can join Rooms. A Gameroom inherits from Room and has a queue where Users can queue for a game. If enough people queue they get thrown into a game lobby. Lobby also inherits from Room. Rooms implement chat functionality which should be used in Gamerooms and Lobbies aswell.
Right now I am passing the io Object to the instantiations and use it to listen to events specific to their class features.
What improvements can I do? Why is this a bad or good design choice? What alternatives are there? What is there to consider? Should I split the classes "Room", "Gameroom" and "Lobby" into a more distinct Model & Controller?
Server instantiates the Rooms.
Server.js
const io = socket.listen(
http.createServer(app).listen(8080)
);
console.log('Server listening..');
app.get('/', function (req, res) {
res.sendFile(__dirname + '/test.html');
});
var main = new Room('', io);
var a = new Gameroom('a', io);
var b = new Gameroom('b', io);
Room is the parent class, but can also be instantiated. It should be a root channel where everyone joins when they login.
Room.js
class Room {
constructor(name, io) {
this.name = name;
this.users = [];
this.namespace = io.of('/' + name);
this.listenOnRoom();
}
listenOnRoom() {
this.namespace.on('connection', (socket) => {
...
socket.on('disconnect', (msg) => {
...
});
socket.on('chatMessage', (msg) => {
...
});
});
}
}
module.exports = Room;
Gameroom adds the ability to queue for a game.
Gameroom.js
class Gameroom extends Room {
constructor(name, io) {
super(name, io);
this.io = io;
this.queue = [];
this.lobbies = [];
this.listenOnGameroom();
}
listenOnGameroom() {
this.namespace.on('connection', (socket) => {
socket.on('userJoinQueue', () => {
...
this.lobbies.push(new Lobby(this.name ,lobbyId, participants, this.io));
});
socket.on('userLeaveQueue', () => {
...
});
socket.on('userLeaveLobby', () => {
...
});
});
}
}
module.exports = Gameroom;
Lobby is instantiated by the Gameroom when there are enough players in the queue.
Lobby.js
class Lobby extends Room {
constructor(gameroom, name, users, io) {
super(gameroom + '/' + name, io);
this.users = users;
this.readyUsers = [];
this.listenOnLobby();
}
listenOnLobby() {
this.namespace.on('connection', (socket) => {
socket.on('userReady', () => {
...
});
socket.on('userUnready', () => {
...
});
});
}
}
module.exports = Lobby;