-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
291 lines (202 loc) · 7.45 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import "dotenv/config"
import express from "express"
import { createServer } from "http"
import { Server } from "socket.io";
import { generateAndMatch, pointUsers, getLeaderboardsSorted } from "./lib.js"
import connectDB from "./config/db.js"
const app = express()
const httpServer = createServer(app)
const io = new Server(httpServer, {
cors: {
origin: process.env.CLIENT_ORIGIN
}
})
let rooms = []
const USER_LIMIT = 4
connectDB(process.env.MONGO_URI)
app.get("/", (req, res) => {
console.log("TEST")
res.send(`socket.io started on PORT: ${process.env.PORT}`)
})
app.get("/room/:id", (req, res) => {
const { id } = req.params
res.redirect(`moneif://game/room/${id}`);
})
io.on("connection", socket => {
console.log(`${socket.id} connected...`)
socket.on("configure-user", (user, callback) => {
if (socket.user) {
callback(socket.user)
return
}
socket.user = {
...user,
id: socket.id
}
callback(socket.user)
console.log(`------------->Saved ${user.name} for socket: ${socket.id}.`)
})
socket.use(([event], next) => {
if (event === "configure-user") return next()
if (!socket.user) {
return socket.emit("give-user", () => {
next()
})
}
next()
})
socket.on("generate-room", callback => {
const id = generateAndMatch(rooms)
socket.join(id)
let roomData = {
id,
users: [socket.user],
leader: socket.user,
game: {},
userWords: []
}
rooms.push(roomData)
callback(roomData)
})
socket.on("play-again", async (id, callback) => {
const match = rooms.findIndex(room => room.id === id)
let roomData = {
id,
users: [socket.user],
leader: socket.user,
game: {},
userWords: []
}
if (match !== -1) {
rooms.splice(match, 1);
}
const sockets = await socket.in(id).fetchSockets()
const users = sockets.map(socket => socket.user)
roomData.users = [socket.user, ...users]
rooms.push(roomData)
socket.broadcast.to(id).emit("join-play-again", roomData)
callback(roomData)
})
socket.on("join-room", async (id, callback) => {
const match = rooms.findIndex(room => room.id === id)
if (match === -1) return callback({ msg: "Room doesn't exist" }, null)
const sockets = await socket.in(id).fetchSockets()
const users = sockets.map(socket => socket.user)
if (rooms[match].started) return callback({ msg: "Game has already started" }, null)
if (users.length >= USER_LIMIT) return callback({ msg: "Room is full" }, null)
rooms[match] = {
...rooms[match],
users: [...rooms[match].users, socket.user]
}
socket.join(id)
callback(null, rooms[match])
socket.broadcast.to(id).emit("user-joined", socket.user)
})
socket.on("start-game", ({ roomId, game }, callback) => {
const match = rooms.findIndex(room => room.id === roomId)
rooms[match] = {
...rooms[match],
started: true,
game
}
socket.broadcast.to(roomId).emit("emit-start-game", game)
callback()
})
socket.on("submit-game", ({ roomId, roundWords }, callback) => {
const match = rooms.findIndex(room => room.id === roomId)
rooms[match] = {
...rooms[match],
userWords: [...rooms[match].userWords, { words: roundWords, user: socket.user }]
}
if (!rooms[match].game.isCountdown) {
rooms[match].game.isCountdown = true
socket.broadcast.to(roomId).emit("start-countdown")
}
if (rooms[match].userWords.length === rooms[match].users.length) {
rooms[match].game.submited = true
io.to(rooms[match].leader.id).emit("leaderboard-submit", rooms[match].userWords);
}
callback()
})
socket.on("submit-results", async ({ userWords, results: checkingResults, roomId }, callback) => {
try {
let results = await pointUsers(userWords, checkingResults)
callback(results, null)
socket.broadcast.to(roomId).emit("show-results", results)
} catch (err) {
console.log(err)
callback([], true)
}
})
socket.on("leave-room", (id, callback) => {
socket.leave(id)
if (callback) callback()
})
socket.on("get-leaderboards", async (callback) => {
const leaderboards = await getLeaderboardsSorted()
callback(leaderboards)
})
})
io.of("/").adapter.on("delete-room", roomId => {
console.log(`Deleted Room: ${roomId}`)
rooms = rooms.filter(room => room.id !== roomId)
});
io.of("/").adapter.on("leave-room", (roomId, socketId) => {
const match = rooms.findIndex(room => room.id === roomId)
if (match === -1) return;
// if the user that is leaving is the last user
if (rooms[match].users.length === 1) return rooms.splice(match, 1);
if (rooms[match].game.submited === true && rooms[match].leader.id === socketId) {
let filterdUsers = rooms[match].users.filter(roomUser => roomUser.id !== socketId)
let newLeader = rooms[match].users[1]
rooms[match] = {
...rooms[match],
leader: newLeader,
users: filterdUsers
}
return io.sockets.to(newLeader.id).emit("transfer-results", { room: rooms[match], userWords: rooms[match].userWords })
}
// preventing the deletion of the room if the countdown is started
if (rooms[match].game.isCountdown && rooms[match].leader.id !== socketId) {
const matchUserSubmited = rooms[match].userWords.findIndex(userSubmission => userSubmission.user.id === socketId)
if (matchUserSubmited !== -1) {
return;
}
if (rooms[match].users.length - 1 === 1) {
rooms[match].game.submited = true
io.to(rooms[match].leader.id).emit("leaderboard-submit", rooms[match].userWords);
}
}
// if there will only be one user while game has strted
if (rooms[match].users.length - 1 === 1 && rooms[match].started && !rooms[match].game.isCountdown) {
io.sockets.to(roomId).emit("game-ended", {})
return rooms.splice(match, 1);
}
let filterdUsers = rooms[match].users.filter(roomUser => roomUser.id !== socketId)
if (rooms[match].leader.id !== socketId) {
rooms[match] = {
...rooms[match],
users: filterdUsers
}
return io.sockets.to(roomId).emit("user-left", { roomData: rooms[match] })
}
console.log(`Transferd leader from to ${rooms[match].users[1].name}`)
// if the user that is leaving is the leader
rooms[match] = {
...rooms[match],
leader: rooms[match].users[1],
users: filterdUsers
}
io.sockets.to(roomId).emit("user-left", { roomData: rooms[match] })
console.log(`${socketId} left room: ${roomId}`)
})
io.of("/").adapter.on("create-room", (room) => {
console.log(`room ${room} was created`);
});
io.of("/").adapter.on("join-room", (room, id) => {
console.log(`socket ${id} has joined room ${room}`);
});
httpServer.listen(process.env.PORT || 8000, () => {
console.log("Server is running...")
})
// app.listen(1234)