-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
123 lines (91 loc) · 2.7 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
const express = require("express");
const http = require("http");
const port = process.env.PORT || 8080;
const app = express();
const root = require('path').join(__dirname, 'client/public')
app.use(express.static(root));
app.get("/", (req, res) => {
res.sendFile('index.html', { root });
})
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
},
pingTimeout: 15000
});
class Member {
constructor(socketID, name) {
this.socketID = socketID;
this.name = name;
this.currentScore = 0;
this.totalScore = 0;
}
}
let updateScoreboardInterval;
let members = new Map()
io.on("connection", (socket) => {
console.log("New client connected");
socket.on("disconnect", (reason) => {
//When the member leaves, we want to update all the users
members.forEach(member => {
if (member.socketID === socket.id) {
delete members[member.name]
}
})
console.log("Client disconnected for:", reason);
var newList = [...members.values()]
io.emit("updateLeaderboard",newList)
});
socket.on("newScore", (socketID, name, score ) => {
if (members.has(name)) {
members.get(name).currentScore += score;
} else {
console.log("error trying to get: " + name);
}
})
// called every 5 seconds
const updateScoreboard = () => {
const sortedListOfMembers = [...members.values()].sort((a, b) => b.currentScore - a.currentScore);
sortedListOfMembers[0].totalScore += 10;
// sortedListOfMembers[1].totalScore += 50;
// sortedListOfMembers[2].totalScore += 25;
// reset members to 0
for (let member of sortedListOfMembers) {
member.currentScore = 0;
}
refreshLeaderboard();
}
socket.on('start', () => {
console.log("starting game");
updateScoreboardInterval = setInterval(updateScoreboard,3000);
io.emit('gameStarted');
})
socket.on('restart', () => {
members.clear();
clearInterval(updateScoreboardInterval);
refreshLeaderboard();
})
socket.on('pause', () => {
clearInterval(updateScoreboardInterval);
io.emit('gamePaused');
})
socket.on('clear', () => {
members.forEach(member => {
member.currentScore = 0;
member.totalScore = 0;
})
refreshLeaderboard();
})
socket.on("newMember", (socketID, name) => {
// socketId: {name: name, score:score}
members.set(name, new Member(socketID, name))
//Once the dictionary is updated, emit to all connected memebrs
refreshLeaderboard();
})
const refreshLeaderboard = () => {
var newList = [...members.values()]
io.emit("updateLeaderboard",newList)
}
});
server.listen(port, () => console.log(`Listening on port ${port}`));