Time for action – sending total count to all users
Perform the following steps to create our foundation logic for the game:
- In the server folder, we create a new file named
game.js
. We will store the room and game logic in this file. - We define a
User
class that stores the socket connection object and creates a random ID.function User(socket) { this.socket = socket; // assign a random number to User. // Long enough to make duplication chance less. this.id = "1" + Math.floor( Math.random() * 1000000000); }
- We also define a
Room
class. We store a collection of user instances in this class.function Room() { this.users = []; }
- We define the two instance methods in the
Room
class that manages the adding and removing of users.Room.prototype.addUser = function(user){ this.users.push(user); var room = this; // handle user closing user.socket.onclose = function(){ console.log('A connection left.'); room.removeUser(user); } }; Room.prototype...