diff options
author | Vidhu Kant Sharma <araararagikoyomi@protonmail.com> | 2021-08-01 02:36:22 +0530 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-08-01 02:36:22 +0530 |
commit | 69d3376df1db5659bd413dbac2b563b2bd1850b6 (patch) | |
tree | 3aa3f708e3f3c6b7d804ecdc53c4fce755853c91 /src/server/index.js | |
parent | 6b58ffac163b9b3637bfab1294069c55b6d5702c (diff) | |
parent | b8babd592b60b1a2cfedac3956184207a3d4bb8d (diff) |
Merge pull request #2 from MikunoNaka/multiplayer
Merge multiplayer into main
Diffstat (limited to 'src/server/index.js')
-rw-r--r-- | src/server/index.js | 48 |
1 files changed, 44 insertions, 4 deletions
diff --git a/src/server/index.js b/src/server/index.js index 2799805..a5aa97f 100644 --- a/src/server/index.js +++ b/src/server/index.js @@ -3,15 +3,37 @@ const app = express(); const http = require('http').Server(app); const path = require('path'); -// const io = require('socket.io')(http); const io = require("socket.io")(http, { cors: { - origin: ["http://localhost:5000", "http://localhost:3000"], + origin: [ + "http://localhost:5000", + "http://localhost:3000", + "https://mikunonaka-tic-tac-toe.herokuapp.com", + "http://mikunonaka-tic-tac-toe.herokuapp.com" + ], "Access-Control-Allow-Origin": "*", methods: ["GET", "POST"] } }); +// check if room exists +const checkCode = (code) => { + const connectedSockets = []; + io.sockets.sockets.forEach( + (i) => connectedSockets.push(i) + ); + + // returns true if room exists + return connectedSockets.some( + (i) => Array.from(i.rooms)[1] === code + ); +} + +// generate new room code +// also checks for duplicates +const getCode = (code = `${Math.floor(1000 + Math.random() * 9000)}`) => + checkCode(code) ? getCode : code; + const allEqual = (arr) => arr.includes(2) ? false : arr.every(i => i === arr[0]) @@ -38,7 +60,25 @@ const getScore = (winner, scoreX, scoreO, board) => ({ }) io.on('connection', (socket) => { + socket.on('host', () => { + const code = getCode(); + socket.join(code); + io.to(code).emit('broadcast code', code); + }); + + socket.on('join', (code) => { + if (checkCode(code)) { + socket.join(code); + io.to(code).emit('player joined'); + } else { + // error if room doesn't exist + socket.emit('join failed') + } + }); + 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)) @@ -47,13 +87,13 @@ io.on('connection', (socket) => { ) ? data.turn : 2; const score = getScore(winner, data.scoreX, data.scoreO, data.board) - io.emit('update-client-data', { + 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.emit('update-winner', score) + score.winner && io.to(room).emit('update-winner', score) }; }); }); |