-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (81 loc) · 1.92 KB
/
server.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
81
82
83
84
85
86
87
88
89
90
91
92
const io = require("socket.io")(process.env.PORT || 3001, {
cors: {
origin: ["http://localhost:3000", "https://ttt.hazim.tech"],
},
});
const rooms = [];
io.on("connection", (socket) => {
// socket.disconnect();
// return;
let started = false;
let currentRoom = "";
socket.on("hover", (hover, room) => {
socket.to(room).emit("hover", hover);
});
socket.on("turn", (board, turn, room) => {
if (room) {
let found = false;
rooms.forEach((v) => {
if (v.name === room) {
v.users.forEach((usr) => {
if (usr.id === socket.id) {
found = true;
}
});
}
});
if (found) socket.to(room).except(socket.id).emit("turn", board, turn);
}
});
socket.on("join-room", (room, callback) => {
let found = null;
rooms.forEach((r) => {
if (r.name === room) {
found = r;
}
});
if (found) {
found.users.forEach((user) => {
if (user.id == socket.id) return;
});
if (found.users.length < 2) {
found.users.push({ id: socket.id, val: 1 });
socket.join(room);
currentRoom = room;
started = true;
callback(started, 1);
socket.to(room).emit("start");
} else {
socket.send("full");
}
} else {
rooms.push({
name: room,
users: [
{
id: socket.id,
val: 0,
},
],
});
socket.join(room);
currentRoom = room;
callback(started, 0);
}
// console.log(rooms);
});
socket.on("restart", (room) => {
socket.to(room).emit("restart");
});
socket.on("disconnect", () => {
rooms.forEach((room, i) => {
if (room.name === currentRoom) {
rooms.splice(i, 1);
}
});
socket.to(currentRoom).emit("leave");
});
socket.on("ping", (cb) => {
if (typeof cb === "function") cb();
});
});