diff options
author | MikunoNaka <bokuwakanojogahoshii@yahoo.com> | 2021-07-31 20:06:30 +0530 |
---|---|---|
committer | MikunoNaka <bokuwakanojogahoshii@yahoo.com> | 2021-07-31 20:06:30 +0530 |
commit | d43fa3768c5e9eee06c0af3b093c84aa38aedbf8 (patch) | |
tree | c598b63440e7be8e56008947e6a225507063e483 /src/server | |
parent | b353dda4df7fc7be973e52a2f529360e7bfc8fed (diff) |
Added basic rooms support
Diffstat (limited to 'src/server')
-rw-r--r-- | src/server/index.js | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/src/server/index.js b/src/server/index.js index 2799805..c770e15 100644 --- a/src/server/index.js +++ b/src/server/index.js @@ -37,6 +37,8 @@ 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)) { @@ -57,6 +59,43 @@ io.on('connection', (socket) => { }; }); }); +*/ + +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) + }); + + socket.on('join', (id) => { + socket.join(id) + // TODO: send confirmation + }); + + socket.on('update-remote-data', (data) => { + const room = Array.from(socket.rooms)[1] + + 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.to(room).emit('update-client-data', { + board: data.board, + turn: score.winner ? data.turn : (data.turn === 0 ? 1 : 0), + score: score + }); + + score.winner && io.to(room).emit('update-winner', score) + }; + }); +}); // serve static front end app.use(express.static(path.join(__dirname, '../../build'))); |