aboutsummaryrefslogtreecommitdiff
path: root/src/server/index.js
diff options
context:
space:
mode:
authorMikunoNaka <bokuwakanojogahoshii@yahoo.com>2021-08-01 01:52:33 +0530
committerMikunoNaka <bokuwakanojogahoshii@yahoo.com>2021-08-01 01:52:33 +0530
commit4766a5d0caac22453ab99f386d80c6c132407904 (patch)
tree7cdaa1f012d574936b8a1d4d90c96186b267b6a9 /src/server/index.js
parentd43fa3768c5e9eee06c0af3b093c84aa38aedbf8 (diff)
Added protection against duplicate room codes
Diffstat (limited to 'src/server/index.js')
-rw-r--r--src/server/index.js52
1 files changed, 20 insertions, 32 deletions
diff --git a/src/server/index.js b/src/server/index.js
index c770e15..a4c9c5c 100644
--- a/src/server/index.js
+++ b/src/server/index.js
@@ -12,6 +12,20 @@ const io = require("socket.io")(http, {
}
});
+// also checks for duplicates
+const getCode = () => {
+ const code = `${Math.floor(1000 + Math.random() * 9000)}`;
+
+ const connectedSockets = [];
+ io.sockets.sockets.forEach(
+ (i) => connectedSockets.push(i)
+ );
+
+ return connectedSockets.some(
+ (i) => Array.from(i.rooms)[1] === code
+ ) ? getCode() : code;
+}
+
const allEqual = (arr) =>
arr.includes(2) ? false : arr.every(i => i === arr[0])
@@ -37,42 +51,16 @@ const getScore = (winner, scoreX, scoreO, board) => ({
scoreO: winner === 0 ? scoreO + 1 : scoreO
})
-// old WORKING code
-/*
-io.on('connection', (socket) => {
- socket.on('update-remote-data', (data) => {
- if (data.board.includes(0) || data.board.includes(1)) {
- const rows = getRows(data.board);
- const winner = (rows.some((i) => allEqual(i))
- || getCols(rows).some((i) => allEqual(i))
- || [getLeftDiagonal(data.board), getRightDiagonal(data.board)].some((i) => allEqual(i))
- ) ? data.turn : 2;
-
- const score = getScore(winner, data.scoreX, data.scoreO, data.board)
- io.emit('update-client-data', {
- board: data.board,
- turn: score.winner ? data.turn : (data.turn === 0 ? 1 : 0),
- score: score
- });
-
- score.winner && io.emit('update-winner', score)
- };
- });
-});
-*/
-
-const getID = () => Math.floor(1000 + Math.random() * 9000);
-
io.on('connection', (socket) => {
socket.on('host', () => {
- const id = (`${getID()}`);
- socket.join(id);
- io.to(id).emit('set-host-id', id)
+ const code = getCode();
+ socket.join(code);
+ io.to(code).emit('broadcast code', code);
});
- socket.on('join', (id) => {
- socket.join(id)
- // TODO: send confirmation
+ socket.on('join', (code) => {
+ socket.join(code);
+ io.to(code).emit('user joined');
});
socket.on('update-remote-data', (data) => {