-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (70 loc) · 2.18 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
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const cors = require("cors");
const app = express();
const server = http.createServer(app);
const io = socketIO(server, {
cors: {
origin: "*",
},
});
const PORT = process.env.PORT || 3000;
app.use(cors({ origin: "*" }));
const questions = require("./questions.js");
let currentQuestionIndex = 0;
let leaderboard = [];
let timerInterval;
let timeLeft = 10;
io.on("connection", (socket) => {
console.log("A user connected");
socket.emit("newQuestion", questions[currentQuestionIndex]);
socket.on("join", ({ username }) => {
console.log(`${username} joined the quiz`);
socket.username = username;
leaderboard.push({ username, score: 0 });
updateLeaderboard();
});
socket.on("submitAnswer", ({ selectedOptionIndex }) => {
if (currentQuestionIndex < questions.length) {
const currentQuestion = questions[currentQuestionIndex];
if (selectedOptionIndex === currentQuestion.correctIndex) {
const userIndex = leaderboard.findIndex(
(entry) => entry.username === socket.username
);
if (userIndex !== -1) {
leaderboard[userIndex].score++;
updateLeaderboard();
}
}
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
io.emit("newQuestion", questions[currentQuestionIndex]);
} else {
io.emit("updateLeaderboard", leaderboard);
}
}
});
socket.on("disconnect", () => {
console.log(`${socket.username} disconnected`);
leaderboard = leaderboard.filter(
(entry) => entry.username !== socket.username
);
updateLeaderboard();
});
socket.on("noAnswerSelected", () => {
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
io.emit("newQuestion", questions[currentQuestionIndex]);
} else {
io.emit("updateLeaderboard", leaderboard);
}
});
function updateLeaderboard() {
leaderboard.sort((a, b) => b.score - a.score);
io.emit("updateLeaderboard", leaderboard);
}
});
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});