-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
275 lines (198 loc) · 6.75 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
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const compression = require('compression');
const minify = require('express-minify');
const { createRoom, getRoom, userJoin, getRoomUsers, userLeave, updateRoomCanvas, getRooms, getUserFromRoom, resetRoomCanvas, lockRoom, updateCanvasBG, startGame, nextRound, votePlayer, userSetAudio, setGameMode, updateName, userSetMute} = require("./utils/rooms");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const maxRoomLimit = 10;
app.use(compression());
app.use(minify());
// Set static folder
app.use(express.static(path.join(__dirname, 'public'), { extensions: ['html'] }));
io.on('connection', (socket) => {
let uid;
let rid;
socket.on("joinRoom", (data) => {
let {room, userName} = data;
if(getRoom(room.id) === undefined){ // if a room doesn't exist, we make a new one
room = createRoom(room)
} else{
room = getRoom(room.id)
}
rid = room.id;
if(room.locked){
socket.emit("joinFail", "Room is locked")
return;
} else if(room.users.length+1 > maxRoomLimit){
socket.emit("joinFail", "Room is full with 10 players. Try later :)")
return;
}
socket.join(room.id)
// random color
let rc = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});
let user = userJoin(socket.id, userName, rc, 0, 0, 0, 0, room, false, false)
uid = socket.id;
socket.emit("newId", {user, room: getRoom(room.id)}) // tell user about their updated details
io.to(room.id).emit("newUser", user) // tell everyone except user about the new player
// send players and room info
io.to(room.id).emit("roomUsers", getRoomUsers(room.id))
notifyOpenRooms()
})
socket.on('drawing', (data) => {
let updatedUserPositions = updateRoomCanvas(rid, data)
let currentUser = getUserFromRoom(rid, uid)
if(currentUser){
checkCollisions(currentUser, updatedUserPositions)
}
socket.broadcast.to(rid).emit('drawing', data)
});
socket.on('userMoving', (data) => {
socket.broadcast.to(rid).emit('userMoving', data)
});
socket.on("clearCanvas", (user) => {
let room = resetRoomCanvas(rid)
io.to(rid).emit('clearCanvas', {room, user})
})
socket.on("canvasColorChange", (color) => {
updateCanvasBG(rid, color)
socket.broadcast.to(rid).emit('canvasColorChange', color)
})
socket.on("lockRoom", (user) => {
let status = lockRoom(rid)
notifyOpenRooms();
io.to(rid).emit("lockRoom", {user, status})
})
socket.on("chatMessage", (message) => {
io.to(rid).emit("rcvMessage", message)
})
socket.on("joinGame", (restart=false) => {
let room = getRoom(rid)
let game = room.game;
if(game.round === 0 || restart){
game = startGame(rid)
socket.emit("joinGame", game)
} else{
socket.emit("joinGame", game)
}
})
socket.on("requestFinish", () => {
let room = getRoom(rid);
socket.emit("gameFinish", room.game)
})
socket.on("nextRound", () => {
let room = getRoom(rid);
let game = room.game;
let timer = Math.abs(Date.now()-game.timer) / 1000
if(timer < 60){
socket.emit("joinGame", game)
return;
}
// if(game.round === 5){
// io.to(rid).emit("gameFinish", game)
// return;
// }
io.to(rid).emit('clearCanvas', {room, user: {userName: "the game"}})
let newRound = nextRound(rid);
socket.emit("joinGame", newRound)
})
socket.on("reloadGame", () => io.to(rid).emit("reloadGame"))
socket.on("getPlayerList", () => {
let {users, game} = getRoom(rid);
socket.emit("playersList", {users, ranks: game.ranks})
})
socket.on("votePlayer", vote => {
votePlayer(rid, vote.playerId, vote.round);
// let votesForThisRound = getGameVotesPerRound(rid, vote.round);
// let {users} = getRoom(rid);
// if(votesForThisRound === users.length){
// io.to(rid).emit("skipRoundWait")
// }
})
socket.on("justDraw", (mode) => {
setGameMode(rid, mode)
})
socket.on("updateName", (newName) => {
let data = updateName(uid, rid, newName)
io.to(rid).emit("updatedUserName", data)
})
socket.on("loadOpenRooms", () => {
notifyOpenRooms()
})
function notifyOpenRooms(){
let rooms = getRooms();
rooms = rooms.filter(room => room.locked === false)
io.emit("openRooms", rooms)
}
socket.on("disconnect", () => {
const user = userLeave(uid, rid)
if(!user){
return;
}
socket.broadcast.emit("playerDisconnect", user)
// send players and room info
io.to(rid).emit("roomUsers", getRoomUsers(rid))
notifyOpenRooms()
})
socket.on("joinAudio", () => {
userSetAudio(rid, uid, true)
io.to(rid).emit("loadExistingAudios", getRoomUsers(rid))
io.to(rid).emit("roomUsers", getRoomUsers(rid))
})
socket.on("leaveAudio", () => {
let usersStillInRoom = userSetAudio(rid, uid, false)
socket.broadcast.to(rid).emit("participantLeft", {uid, usersStillInRoom})
})
socket.on("setMute", (status) => {
userSetMute(rid, uid, status)
io.to(rid).emit("updateParticipantMute", {uid, status})
})
socket.on("sendSig", payload => {
io.to(payload.userToSignal).emit('userJoinedAudio', { signal: payload.signal, callerID: payload.callerID });
});
socket.on("returnSig", payload => {
io.to(payload.callerID).emit('rcvSig', { signal: payload.signal, id: socket.id });
});
function checkCollisions(currentUser, updatedUserPositions){
// collision grace for everyone in general
let {lastCollision} = getRoom(rid)
let timeNow = Date.now();
let lastCollDiff = Math.abs(timeNow-lastCollision) / 1000
if(lastCollDiff < 5){
return;
}
// if there's not been a collision in the last 5 seconds
// we start collision detection
let ldP1 = currentUser.lastDraw;
for(user in updatedUserPositions){
user = updatedUserPositions[user];
if(user.id !== currentUser.id){
let dx = currentUser.x - user.x;
let dy = currentUser.y - user.y;
let distance = Math.sqrt((dx * dx) + (dy * dy));
let ldP2 = user.lastDraw;
let timeDiff = Math.abs(ldP2-ldP1) / 1000
if (distance < 8 && timeDiff < 2) {
let room = resetRoomCanvas(rid, Date.now())
let collision = {
p1: currentUser,
p2: user,
distance,
dx,
dy,
bg: room.bg
}
io.to(rid).emit("collided", collision)
}
}
}
}
});
app.get("*", (req, res) => {
res.redirect("/")
})
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));