diff --git a/README.md b/README.md index bd92b9c..fe3a403 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # GIM, LLC + ## General Industrial Manufacturing, LLC _"Commited to providing the best industrial supplies for your company"_ diff --git a/lib/socket/user-utils.js b/lib/socket/user-utils.js index f2c3dc4..991ea41 100644 --- a/lib/socket/user-utils.js +++ b/lib/socket/user-utils.js @@ -1,30 +1,38 @@ const ROOM_THRESHOLD = 3; +// track current room, and number of connected users in the current room let roomNumber = 0; let currentUsers = 0; +//step to the next room, and set current users back to 0 +const incrementRoom = () => { + roomNumber++; + currentUsers = 0; +}; + +//called whenever there is a new socket connection const addUser = (socket, userObj, gamesArr) => { + //keep an ongoing record of how many users are in a given room, and each user globally currentUsers += 1; userObj[socket.id] = socket; + //does the current room have an ongoing game? if so join the next room if (gamesArr.includes(String(roomNumber))) { - roomNumber++; - currentUsers = 0; + incrementRoom(); userObj[socket.id].room = String(roomNumber); + // if there is no ongoing game, but we have exceeded the max room size join the next room } else if (currentUsers >= ROOM_THRESHOLD) { - roomNumber++; - currentUsers = 0; + incrementRoom(); userObj[socket.id].room = String(roomNumber); + // if there's no ongoing game, and enough spaces in the room join this current room } else { userObj[socket.id].room = String(roomNumber); } - console.log(`new user in room ${userObj[socket.id].room}: ${socket.id}`); }; +// called once a user disconnects, remove their tracked socket and decrement current users in the room const deleteUser = (socket, userObj) => { if(currentUsers > 0) currentUsers--; - console.log('user left: ', socket.id); - delete userObj[socket.id]; }; diff --git a/server.js b/server.js index b88d8a9..e637f98 100644 --- a/server.js +++ b/server.js @@ -7,6 +7,7 @@ const io = new Server(server, { cors: true }); const PORT = process.env.PORT || 8080; +//global state management for active users and ongoing games const users = {}; const games = []; @@ -19,12 +20,13 @@ const onConnection = (socket) => { const currentRoom = `${users[socket.id].room}`; socket.join(currentRoom); socket.broadcast.to(currentRoom).emit('new user', { [socket.id]: socket.id }); - // socket.to(socket.id).emit('current users', Object.keys(users)); + // take in cursor movement data and broadcast to other clients const onMovement = (movementData) => { movementData.id = socket.id; socket.broadcast.to(currentRoom).emit('moving', movementData); }; + // once game has started, add to ongoing games state const onGameStart = () => { if (!games.includes(currentRoom)) games.push(currentRoom); }; @@ -154,6 +156,7 @@ const onConnection = (socket) => { socket.on('footerTitleClick', onFooterTitleClick); }; +//runs when a client connects io.sockets.on('connection', onConnection); server.listen(PORT, () => {