aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/components/MultiplayerGrid.js12
-rw-r--r--src/server/index.js39
2 files changed, 50 insertions, 1 deletions
diff --git a/src/components/MultiplayerGrid.js b/src/components/MultiplayerGrid.js
index 88a8259..3db9dc6 100644
--- a/src/components/MultiplayerGrid.js
+++ b/src/components/MultiplayerGrid.js
@@ -28,9 +28,19 @@ const MultiplayerGrid = (props) => {
const [board, setBoard] = useState([2,2,2,2,2,2,2,2,2]);
const turn = props.turn;
+ const isHost = props.isHost;
+ useEffect(() => {
+ if (isHost) {
+ socket.emit("host");
+ socket.on("set-host-id", (id) => alert(id));
+ } else {
+ socket.emit("join", prompt("Enter ID"));
+ }
+ }, [isHost]);
+
const getBoard = (index) => {
// if it's not your turn you can't play
- if ((turn === 0) === props.isHost) return;
+ if ((turn === 0) === isHost) return;
const newBoard = board.slice(0, index).concat(turn).concat(board.slice(index+1, 9));
socket.emit("update-remote-data", {
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')));