-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserver.js
384 lines (331 loc) · 12.6 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
require('dotenv').config({path: __dirname + '/.env'});
const mongoose = require('mongoose');
const cors = require('cors');
var app = require('express')();
const bodyParser = require('body-parser');
app.use(cors());
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const router = require('./router');
const {shuffle, Game} = require('./helpers.js');
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB...'))
.catch((err) => console.error('Failed to connect to MongoDB...', err));
var rooms = {};
app.use(bodyParser.json());
app.use('/', router);
const MAX_PLAYERS = 8;
// when a user hits the /game path, start the websocket connection
io.on("connection", function (socket) {
socket.on("join room", function ({roomId, myName}) {
// If there's more than MAX_PLAYERS, then just disconnect any others
// just kidding, this causes an infinite loops since we refresh the page when someone disconnects
// this may not be necessary to handle?
// if (rooms[roomId] && rooms[roomId].players.length === MAX_PLAYERS) {
// console.log('Disconnected...');
// // socket.disconnect();
// return;
// }
// if the room doesnt already exist, add to the rooms object
if (!rooms[roomId]) {
rooms[roomId] = new Game();
}
// Add roomId to socket object
socket.roomId = roomId;
console.log('joined room!', socket.roomId, 'socket.id: ', socket.id);
// join the room
socket.join(roomId);
// let everyone know that a new player has connected
io.to(socket.roomId).emit('user connected', {
players: rooms[socket.roomId].players,
});
if (rooms[socket.roomId].players.length < MAX_PLAYERS) {
rooms[socket.roomId].players.push({ id: socket.id, name: myName || "NEW USER" });
}
io.to(socket.roomId).emit('new connection', {
whiteCards: rooms[socket.roomId].whiteCards,
blackCards: rooms[socket.roomId].blackCards,
players: rooms[socket.roomId].players,
submittedCards: rooms[socket.roomId].submittedCards,
socketId: socket.id,
});
io.to(socket.roomId).emit('joined a room', roomId);
});
socket.on('set game as private', function () {
rooms[socket.roomId].isPrivate = true;
console.log('set game as private, rooms: ', rooms);
});
// first player to join game hits the getInitialCards endpoint and sets the initial cards for the game
socket.on('set initialCards for game', function ({
whiteCards: newWhiteCards,
blackCards: newBlackCards,
}) {
rooms[socket.roomId].whiteCards = newWhiteCards;
rooms[socket.roomId].blackCards = newBlackCards;
io.to(socket.roomId).emit('get initialCards for game', {
whiteCards: rooms[socket.roomId].whiteCards,
blackCards: rooms[socket.roomId].blackCards,
});
});
// update the whiteCards on the server
socket.on('update whiteCards', function ({
whiteCards: newWhiteCards,
players: newPlayers,
}) {
rooms[socket.roomId].whiteCards = newWhiteCards;
rooms[socket.roomId].players = newPlayers;
io.to(socket.roomId).emit('update players', rooms[socket.roomId].players);
});
// update the submittedCards when someone discards a card
socket.on('update submittedCards', function (passedInCard) {
// remove passedInCard from submittedCards
const passedInCardIndex = rooms[socket.roomId].submittedCards.findIndex(
(card) => card.text === passedInCard.text
);
rooms[socket.roomId].submittedCards.splice(passedInCardIndex, 1);
// let EVERYONE know including the client that triggered this
io.to(socket.roomId).emit(
'update submittedCards',
rooms[socket.roomId].submittedCards
);
});
// update the whiteCards on the server
socket.on('submitted a card', function ({
socketId,
passedInCard,
newMyCards,
}) {
// 2020-06-30T14:08:31.086551+00:00 app[web.1]: /app/server.js:109
// 2020-06-30T14:08:31.086569+00:00 app[web.1]: rooms[socket.roomId].submittedCards.push(passedInCard);
// 2020-06-30T14:08:31.086570+00:00 app[web.1]: ^
// 2020-06-30T14:08:31.086571+00:00 app[web.1]:
// 2020-06-30T14:08:31.086571+00:00 app[web.1]: TypeError: Cannot read property 'submittedCards' of undefined
if (!rooms[socket.roomId]) {
console.log(
'Warning: rooms[socket.roomId] is undefined. ',
`socket.roomId: ${socket.roomId}`,
`typeof socket.roomId ${typeof socket.roomId}`,
'rooms: ',
Object.keys(rooms)
);
}
rooms[socket.roomId].submittedCards.push(passedInCard);
// randomize the submittedCards when a new one is submitted
rooms[socket.roomId].submittedCards = shuffle(
rooms[socket.roomId].submittedCards
);
// find current player from players and update whiteCards property to be newMyCards
const playerIndex = rooms[socket.roomId].players.findIndex(
(player) => player.id === socketId
);
// prevent user error: TypeError: Cannot set property 'whiteCards' of undefined
if (rooms[socket.roomId].players[playerIndex]) {
rooms[socket.roomId].players[playerIndex].whiteCards = newMyCards;
} else {
console.log(
"Warning: Player that submitted card doesn't exist. players: ",
rooms[socket.roomId].players,
'socketId: ',
socketId,
' index: ',
playerIndex
);
}
// let EVERYONE know including the client that triggered this
io.to(socket.roomId).emit('submitted a card', {
submittedCards: rooms[socket.roomId].submittedCards,
players: rooms[socket.roomId].players,
passedInCard,
});
});
// update the blackCards on the server
socket.on('update blackCards', function (newBlackCards) {
rooms[socket.roomId].blackCards = newBlackCards;
});
// when someone drops a white card into their deck
socket.on('dropped in my cards', function ({passedInCard, socketId}) {
const indexOfPassedInCard = rooms[socket.roomId].whiteCards.findIndex(
(whiteCard) => whiteCard === passedInCard.text
);
rooms[socket.roomId].whiteCards.splice(indexOfPassedInCard, 1);
// update player whiteCards property
const newPlayers = rooms[socket.roomId].players.map((player) => {
if (player.id === socketId) {
player.whiteCards = [
...(player.whiteCards ? player.whiteCards : []),
passedInCard,
];
}
return player;
});
rooms[socket.roomId].players = newPlayers;
io.to(socket.roomId).emit('dropped in my cards', {
players: rooms[socket.roomId].players,
whiteCards: rooms[socket.roomId].whiteCards,
});
});
// when someone drops a black card into a player drop
socket.on('dropped in player drop', function ({
players: newPlayers,
blackCards: newBlackCards,
}) {
rooms[socket.roomId].players = newPlayers;
rooms[socket.roomId].blackCards = newBlackCards;
console.log({blackCards: rooms[socket.roomId].blackCards.length});
this.broadcast.to(socket.roomId).emit('dropped in player drop', {
players: rooms[socket.roomId].players,
blackCards: rooms[socket.roomId].blackCards,
});
});
// get the mouse coordinates from the client
socket.on('dragged card', function ({type, text, x, y}) {
// send the coordinates to everyone but client that sent it
this.broadcast.to(socket.roomId).emit('dragged card', {type, text, x, y});
});
// get the mouse coordinates from the client
socket.on('let go card', function ({type, text}) {
// send the coordinates to everyone but client that sent it
this.broadcast.to(socket.roomId).emit('let go card', {type, text});
});
socket.on('card is flipped', function ({isFlipped, text}) {
this.broadcast.to(socket.roomId).emit('card is flipped', {isFlipped, text});
});
// when someone changes their player name,
// update players name property and emit back
socket.on('name change', function ({id, name}) {
if (!socket.roomId && !rooms[socket.roomId]) {
return;
}
if (
rooms[socket.roomId].players.length <= MAX_PLAYERS &&
rooms[socket.roomId].players.find((player) => player.id === id)
) {
rooms[socket.roomId].players.find(
(player) => player.id === id
).name = name;
io.to(socket.roomId).emit('name change', rooms[socket.roomId].players);
}
});
socket.on('name submit', function ({players: newPlayers, myName, id}) {
if (!socket.roomId && !rooms[socket.roomId]) {
return;
}
const matchedPlayerThatLeft = rooms[socket.roomId].playersThatLeft.find(
(player) => player.name === myName
);
if (myName !== 'NEW USER' && matchedPlayerThatLeft) {
const playerIndex = rooms[socket.roomId].players.findIndex(
(player) => player.id === id
);
rooms[socket.roomId].players[playerIndex] = matchedPlayerThatLeft;
rooms[socket.roomId].players[playerIndex].id = id;
io.to(socket.roomId).emit('player rejoins', rooms[socket.roomId].players);
} else {
rooms[socket.roomId].players = newPlayers;
io.to(socket.roomId).emit('update players', rooms[socket.roomId].players);
// grab (and remove) seven white cards when showNamePopup goes away
const sevenWhiteCards = rooms[socket.roomId].whiteCards.splice(0, 7);
// modify the seven white cards so that they have the right shape
const modifiedSevenWhiteCards = sevenWhiteCards.map((text, index) => ({
bgColor: '#fff',
color: '#000',
id: index,
isFlipped: false,
text,
type: 'whiteCard',
}));
// add seven white cards to a users deck once they submit a name
const playerThatJoined = rooms[socket.roomId].players.find(
(player) => player.id === id
);
playerThatJoined.whiteCards = modifiedSevenWhiteCards;
// emit update back to clients
io.to(socket.roomId).emit('draw seven white cards update', {
players: rooms[socket.roomId].players,
whiteCards: rooms[socket.roomId].whiteCards,
sevenWhiteCards: modifiedSevenWhiteCards,
socketId: id,
});
}
});
socket.on('sent message to chat', function ({msg, from}) {
this.broadcast
.to(socket.roomId)
.emit('receive message from chat', {msg, from});
});
// when a specific player disconnects
socket.on('disconnect', function () {
// If everyone leaves, destroy the room
if (rooms[socket.roomId] && rooms[socket.roomId].players.length <= 1) {
clearTimeout(rooms[socket.roomId].timer);
delete rooms[socket.roomId];
return;
}
// if the room doesn't exist anymore, because the server restarted, just bail.
if (!rooms[socket.roomId]) {
return;
}
// reset the timer before you start it again
if (rooms[socket.roomId] && rooms[socket.roomId].timer) {
clearTimeout(rooms[socket.roomId].timer);
}
if (rooms[socket.roomId] && rooms[socket.roomId].playersThatLeft) {
rooms[socket.roomId].timer = setTimeout(() => {
rooms[socket.roomId].playersThatLeft.length = 0;
console.log(
'cleared playersThatLeft ',
rooms[socket.roomId].playersThatLeft
);
}, 600000);
}
const playerThatLeft = rooms[socket.roomId].players.find(
(user) => user.id === socket.id
);
if (playerThatLeft) {
// find the player that lefts index by the name
const playerThatLeftIndex = rooms[
socket.roomId
].playersThatLeft.findIndex((player) => {
return player.id === playerThatLeft.id;
});
// if the player that left already left before, remove them from playersThatLeft
if (
rooms[socket.roomId].playersThatLeft.find(
(player) => player.id === playerThatLeft.id
)
) {
rooms[socket.roomId].playersThatLeft.splice(playerThatLeftIndex, 1);
}
// track the new player that left
rooms[socket.roomId].playersThatLeft.push(playerThatLeft);
// update global players variable
rooms[socket.roomId].players.splice(
rooms[socket.roomId].players.findIndex((user) => user.id === socket.id),
1
);
}
io.to(socket.roomId).emit(
'user disconnected',
rooms[socket.roomId].players
);
console.log('user disconnected: ', socket.id);
if (
rooms[socket.roomId] &&
rooms[socket.roomId].players &&
rooms[socket.roomId].playersThatLeft
) {
console.log({
players: rooms[socket.roomId].players,
playersThatLeft: rooms[socket.roomId].playersThatLeft,
});
}
});
});
http.listen(process.env.PORT, function () {
console.log(`listening on port ${process.env.PORT}`);
});
module.exports.rooms = rooms;