-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
292 lines (265 loc) · 8.07 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
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
292
const { createServer } = require("http");
const { Server } = require("socket.io");
const express = require("express");
const cors = require("cors");
const axios = require("axios");
const { v4: uuidv4 } = require("uuid");
const app = express();
// if we don't run this we get a CORS error
const localUrl = "http://localhost:3000";
const deployedUrl = "https://browserparty.netlify.app";
// LOCAL
// app.use(
// cors()
// );
// DEPLOYED
app.use(
cors({
origin: deployedUrl,
})
);
const PORT = process.env.PORT || 4000;
// for now, take this as boilerplate
const theServer = createServer();
const io = new Server(theServer, {
cors: {
// Check local vs deployed
origin: deployedUrl,
credentials: true,
},
});
let rooms = {};
const preRoundLength = 6; // in seconds (how long we show scoreboard/instructions between rounds)
const generateTrivia = async (category, socket, roomName, time) => {
console.log("trivia");
if (category === "geography") {
categoryCode = 22;
} else if ((category = "general")) {
categoryCode = 9;
}
let response = await axios({
method: "get",
url: `https://opentdb.com/api.php?amount=1&category=${categoryCode}&difficulty=medium&type=multiple`,
});
const results = response.data.results[0];
const triviaObj = {
question: results.question,
correct_answer: results.correct_answer,
incorrect_answers: results.incorrect_answers,
category: results.category,
difficulty: results.difficulty,
};
io.emit(`start-trivia-${roomName}`, triviaObj, time);
};
const joinRoom = (socket, room) => {
room.sockets.push(socket);
socket.join(room.name);
// store the room id in the socket for future use
socket.roomId = room.name;
console.log(socket.id, "Joined", room.name);
};
const leaveRooms = (socket) => {
const roomsToDelete = [];
for (const key in rooms) {
const room = rooms[key];
if (room.sockets.includes(socket)) {
socket.leave(key);
// remove the socket from the room object
room.sockets = room.sockets.filter((item) => item !== socket);
}
// Prepare to delete any rooms that are now empty
if (room.sockets.length == 0) {
roomsToDelete.push(room.name);
endGame(socket, room.name);
} else {
updatePlayers(socket, room);
}
}
// Delete all the empty rooms that we found earlier
roomsToDelete.forEach((element) => {
delete rooms[element];
});
};
const updatePlayers = (socket, room) => {
const players = [];
room.sockets.forEach((element) => {
const player = {
id: element.id,
roomName: element.roomId,
username: element.username,
score: element.score,
};
players.push(player);
});
io.emit(`update-players-${room.name}`, players);
};
const setRound = (socket, roomName, round) => {
console.log(`set round in room ${roomName} to ${round}`);
io.in(roomName).emit(`set-round-${roomName}`, round);
};
const showScoreboard = (socket, room) => {
io.emit(`scoreboard-${room}`, true);
setTimeout(() => {
io.emit(`scoreboard-${room}`, false);
}, preRoundLength * 1000);
};
const showCountdown = (socket, room) => {
io.emit(`countdown-${room}`, true);
setTimeout(() => {
io.emit(`countdown-${room}`, false);
}, 5000);
};
const wait = (timeToDelay) =>
new Promise((resolve) => setTimeout(resolve, timeToDelay));
const runGame = async (
socket,
room,
includeTrivia,
includeWhack,
includeMemory,
includeSnake
) => {
if (includeTrivia) {
await runRound(socket, room, "trivia1", 20);
}
if (includeWhack) {
await runRound(socket, room, "whack", 30);
}
if (includeMemory) {
await runRound(socket, room, "memory", 30);
}
if (includeSnake) {
await runRound(socket, room, "whack", 30);
}
if (includeTrivia) {
await runRound(socket, room, "trivia2", 20);
}
endGame(socket, room.name);
};
const runRound = async (socket, room, round, time) => {
setRound(socket, room.name, round);
showScoreboard(socket, room.name);
await wait(preRoundLength * 1000);
showCountdown(socket, room.name);
await wait(5000);
if (round === "trivia1") {
generateTrivia("geography", socket, room.name, time * 1000);
} else if (round === "trivia2") {
generateTrivia("general", socket, room.name, time * 1000);
} else {
io.emit(`start-${round}-${room.name}`, time * 1000);
}
await wait((time + 3) * 1000);
updatePlayers(socket, room);
};
const endGame = (socket, roomName) => {
io.in(roomName).emit(`end-game`);
};
io.on("connection", (socket) => {
// when a user connects
console.log(
"You are now connected. This socket ID is unique everytime: " +
socket.id
);
socket.on("join-room", (roomName, username, callback) => {
if (rooms[roomName]) {
callback({
status: "ok",
});
socket.username = username;
socket.score = 0;
console.log(`attempting to join room ${roomName}`);
const room = rooms[roomName];
joinRoom(socket, room);
updatePlayers(socket, room);
} else {
callback({
status: "bad",
});
return;
}
});
socket.on("create-room", (roomName, username, callback) => {
if (rooms[roomName]) {
callback({
status: "bad",
});
return;
} else {
console.log("room good");
callback({
status: "ok",
});
socket.username = username;
socket.isHost = roomName;
socket.score = 0;
const room = {
// id: uuidv4(), // generate a unique id for the new room, that way we don't need to deal with duplicates.
name: roomName,
sockets: [],
messages: [
{
username: "BrowserParty",
content:
"Use this space to say hi to your opponents! Or talk trash and throw them off their game...",
id: 0,
},
],
};
rooms[roomName] = room;
// have the socket join the room they've just created.
joinRoom(socket, room);
console.log(room);
updatePlayers(socket, room);
}
});
socket.on("leave-room", (roomName, username) => {
const room = rooms[roomName];
leaveRooms(socket, room);
console.log(`${username} left room ${room}`);
});
socket.on("disconnect", () => {
leaveRooms(socket);
});
socket.on(
"start-game",
(
roomName,
includeTrivia,
includeWhack,
includeMemory,
includeSnake
) => {
const room = rooms[roomName];
runGame(
socket,
room,
includeTrivia,
includeWhack,
includeMemory,
includeSnake
);
}
);
socket.on("send-score", (roundScore) => {
socket.score = socket.score + roundScore;
});
socket.on("send-new-message", (data, roomName, count) => {
// we tell the client to execute 'new message'
const room = rooms[roomName];
console.log(room.messages);
const messageObj = {
username: socket.username,
content: data,
id: count,
};
if (room.messages[room.messages.length - 1] != messageObj) {
room.messages.push(messageObj);
console.log(room.messages);
io.in(roomName).emit("add-new-message", room.messages);
}
});
});
theServer.listen(PORT, function () {
console.log(`listening on port number ${PORT}`);
});