-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (64 loc) · 1.92 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const express = require("express");
const app = express();
const http = require("http");
const socketIo = require("socket.io");
const server = http.createServer(app);
const port = process.env.PORT || 4000;
const { v4: uuidv4 } = require("uuid");
const io = socketIo(server, { cors: { origin: "*" } });
let clientRooms = []
// roomId , arrayOfMoves , nameOfX , nameOfO , currentPlayer
io.on("connection", (socket) => {
console.log("id", socket.id);
socket.on("newGame" ,handleNewGame)
socket.on("joinGame",handleJoinGame)
socket.on("move1",receiveIndex)
// socket.on("disconnect",handleDisconnect);
function handleNewGame (nameOfPlayer) {
let roomName = uuidv4();
let instance = { roomId: roomName, nameOfX: nameOfPlayer , count:1 };
clientRooms.push(instance);
socket.join(roomName);
socket.emit("gameCode", instance);
console.log(clientRooms);
};
function handleJoinGame({ roomName, nameOfPlayer }) {
console.log("someone slides in");
const room = io.sockets.adapter.rooms.has(roomName);
let numClients = 0;
if (room) {
numClients = io.sockets.adapter.rooms.get(roomName).size;
console.log(numClients);
}
if (numClients == 0) {
// emit error
socket.emit("unknowCode");
return;
}
if (numClients > 1) {
// emit error
socket.emit("tooManyPlayers");
return;
}
clientRooms.forEach((x) => {
if (x.roomId == roomName) {
x.nameOfO = nameOfPlayer;
x.count = 2
}
});
console.log(clientRooms);
socket.join(roomName);
const instance = clientRooms.filter(x => x.roomId===roomName)[0]
io.in(roomName).emit("info", instance);
};
function receiveIndex(data) {
console.log(data);
socket.to(data.roomName).emit("move2", data);
}
});
app.get("/", (req, res) => {
res.send("hello moto");
});
server.listen(port, () => {
console.log(`Server is live at ${port} ✨`);
});