-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (56 loc) · 1.4 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
const app = require("express")();
const http = require("http").createServer(app);
const io = require("socket.io")(http, {
cors: {
origin: "*",
},
});
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
const SOCKET_PORT = process.env.PORT || 3005;
let connectedUsers = 0;
io.on("connection", (socket) => {
console.log("first time",connectedUsers);
if (connectedUsers >= 2) {
console.log("returning rfom here");
return null;
}
console.log("one of the users");
connectedUsers += 1;
console.log(connectedUsers);
if (connectedUsers === 1) {
socket.emit("setPlayerTwo");
}
function getGameRandomNumber() {
let randomNumber = parseInt(Math.random() * 100, 10);
if (randomNumber < 2) this.getGameRandomNumber();
else return randomNumber;
}
if (connectedUsers === 2) {
console.log(connectedUsers);
socket.emit("setPlayerOne");
io.emit("action", {
isGameStart: true,
turnArray: [
{
id: 0,
player: "playerOne",
value: getGameRandomNumber(),
},
],
turnCount: 0,
});
}
socket.on("action", (action) => {
io.emit("action", action);
});
socket.on("disconnect", () => {
connectedUsers -= 1;
console.log("user disconnected");
console.log(connectedUsers);
});
});
http.listen(SOCKET_PORT, () => {
console.log("listening on *:" + SOCKET_PORT);
});