-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
439 lines (390 loc) · 15.2 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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require("socket.io")(http)
const port = process.env.PORT || 3000;
users = {}
// Lobby Id
lobbies = {}
lobbyPasswords = {}
globalLobby = 'Global'
lobbies[globalLobby] = []
readyInformation = {}
readyNumber = {}
lobbyStatus = {}
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on("connection", socket => {
console.log("New User Connection")
socket.join(globalLobby)
if (lobbies[globalLobby] == null) {
lobbies[globalLobby] = []
}
lobbies[globalLobby].push(socket.id)
socket.on('send-chat-message', data=>{
socket.to(data.lobbyName).emit('chat-message', data)
console.log(`${data.name} sent ${data.message} to lobby: ${data.lobbyName}`)
})
socket.on('new-member', name=>{
users[socket.id] = name
socket.to(globalLobby).emit('user-connected', name)
})
socket.on('new-name', name=>{
users[socket.id] = name
})
socket.on('disconnect', ()=>{
leaveLobby(socket.id)
delete users[socket.id]
socket.leaveAll()
})
socket.on('leave-lobby', lobbyName=>{
leaveLobby(socket.id)
socket.leave(lobbyName)
})
function leaveLobby(userId){
const lobbyKeys = Object.keys(lobbies)
var userIndex
// Removes user from the Lobby list
for (var key of lobbyKeys){
console.log(key)
userIndex = lobbies[key].indexOf(userId)
if (userIndex >= 0){
lobbies[key].splice(userIndex, 1)
// Also remove ready information about person
let userReadied = 0
if (readyInformation[key] != null) {
if (readyInformation[key][userId] != null &&
readyInformation[key][userId]) {
userReadied = 1
}
delete readyInformation[key][userId]
}
if (readyNumber[key] != null) {
if (userReadied) {
readyNumber[key]--
}
console.log("New count for " + key + " is " + readyNumber[key])
}
break
}
}
if (lobbies[key].length == 0 && key != globalLobby){
delete lobbies[key]
}
socket.to(key).emit('user-disconnected', users[userId])
console.log(`${users[userId]} left the lobby: ${key}`)
}
//Joining lobbies
socket.on('check-lobby-exist', (data)=>{
console.log(`Check lobby exists. Action: ${data.action}`)
let passwordProtected = data.lobbyName in lobbyPasswords
if (data.lobbyName in lobbies){
if (lobbyStatus[data.lobbyName]) {
console.log('start?')
data.action = 'started'
}
socket.emit('lobby-exists', {lobbyName: data.lobbyName, action: data.action, passwordProtected})
}
else{
socket.emit('lobby-no-exist', {lobbyName: data.lobbyName, action: data.action})
}
})
socket.on('set-lobby-password', data=>{
console.log(`Set ${data.lobbyName} password to: ${data.password}`)
lobbyPasswords[data.lobbyName] = data.password
})
socket.on('enter-password', data=>{
console.log(`Entered: ${data.password}, Correct: ${lobbyPasswords[data.lobbyName]}`)
if (data.password == lobbyPasswords[data.lobbyName]){
console.log('Password is correct')
socket.emit('password-correct')
} else{
console.log('Password is incorrect')
socket.emit('password-incorrect')
}
})
socket.on('join-lobby', (data)=>{
console.log(`${users[socket.id]} Joined ${data.newLobbyName}`)
userStatus[socket.id] = false
socket.leave(data.lobbyName)
// Deleting infomation in lobbies and readyInformation for old lobby
userIndex = lobbies[data.lobbyName].indexOf(socket.id)
if (userIndex >= 0) {
lobbies[data.lobbyName].splice(userIndex, 1)
}
if (!(data.newLobbyName in lobbies)){
lobbies[data.newLobbyName] = []
lobbyStatus[data.newLobbyName] = false
}
lobbies[data.newLobbyName].push(socket.id)
socket.join(data.newLobbyName)
socket.to(data.newLobbyName).emit('user-joined-lobby', users[socket.id])
userChainedData[socket.id] = []
userTotalData[socket.id] = []
if (readyInformation[data.newLobbyName] == null) {
readyInformation[data.newLobbyName] = {}
readyInformation[data.newLobbyName][socket.id] = false
readyNumber[data.newLobbyName] = 0
console.log("Initialized information about " + data.newLobbyName)
} else {
readyInformation[data.newLobbyName][socket.id] = false
}
})
// Current Members
socket.on('get-lobby-members', lobbyName=>{
//var lobbyInfo = io.sockets.adapter.rooms[lobbyName]
var names = []
let number = 0
//var userIds = Object.keys(lobbyInfo.sockets)
if (lobbies[lobbyName] != null) {
number = lobbies[lobbyName].length
}
for (var i = 0; i < number ; i++){
if (i < lobbies[lobbyName].length - 1){
userNextPlayer[lobbies[lobbyName][i]] = lobbies[lobbyName][i+1]
}
else{
userNextPlayer[lobbies[lobbyName][i]] = lobbies[lobbyName][0]
}
names.push(users[lobbies[lobbyName][i]])
}
io.in(lobbyName).emit('current-lobby-members', names)
})
socket.on('get-numbers', name=>{
let saveNum = 0
if (lobbies[name] != null) {
saveNum = lobbies[name].length
}
returnObj = {readied: readyNumber[name], members: saveNum}
socket.emit('get-number-return', returnObj)
})
// Start Game
// We can maybe collapse these down later on...
userNextPlayer = {} // stores key: player id, value: next player id
userCurrentData = {} // stores key: player id, value: current drawing/guessed word
userPreviousData = {} // stores key: player id, value: word if no one wrote anything
tempPreviousData = {} // stores key: player id, value: word if no one wrote anything (but inbetween rounds)
userTotalData = {} // stores key: player id, value: previous drawings/guessed words
userChainedData = {} // stores key:player id, value: chain of drawings and guessed words
userStatus = {} // stores key: player id, value: boolean if done task
socket.on('start-game', lobbyName=>{
io.in(lobbyName).emit('game-starting')
console.log(`Game starting in ${lobbyName}`)
lobbyStatus[lobbyName] = true
// Resetting the ready/totalData information
readyNumber[lobbyName] = 0
for (let player of lobbies[lobbyName]){
readyInformation[lobbyName][player] = false
userTotalData[player] = []
}
/*
let number = 0
if (lobbies[lobbyName] != null) {
number = lobbies[lobbyName].length
}
for (let i = 0; i < number; i++) {
let userId = lobbies[lobbyName][i]
userTotalData[userId] = []
}
*/
})
socket.on('picked-word', word=>{
console.log(`${users[socket.id]} picked ${word}`)
userCurrentData[socket.id] = word
userChainedData[socket.id] = []
userChainedData[socket.id].push(word)
let nextPlayer = userNextPlayer[socket.id]
tempPreviousData[nextPlayer] = word
//socket.emit('word-chosen', word)
})
socket.on('finished-game', lobbyName=>{
lobbyStatus[lobbyName] = false
})
socket.on('finished-event', data=>{
console.log(`${users[socket.id]} finished ${data.event}`)
var everybodyDone = true
userStatus[socket.id] = true
for (var userId of lobbies[data.lobbyName]){
if (userStatus[userId] == false){
everybodyDone = false
break
}
}
if (everybodyDone){
console.log(`Everyone is done ${data.event}`)
var nextEvent = ''
if (userTotalData[socket.id].length >= lobbies[data.lobbyName].length){
compute_chain(data.lobbyName)
nextEvent = 'game-finished'
}
else if (data.event == 'drawing'){
nextEvent = 'start-guessing'
}
else if (data.event == 'picking-word'){
if (readyNumber[data.lobbyName] == lobbies[data.lobbyName].length){
nextEvent = 'start-drawing'
let number = 0
if (lobbies[data.lobbyName] != null) {
number = lobbies[data.lobbyName].length
}
for (let i = 0; i < number; i++){
let userId = lobbies[data.lobbyName][i]
userPreviousData[userId] = tempPreviousData[userId]
tempPreviousData[userId] = ''
}
}
}
else if (data.event == 'guessing'){
nextEvent = 'start-drawing'
let number = 0
if (lobbies[data.lobbyName] != null) {
number = lobbies[data.lobbyName].length
}
for (let i = 0; i < number; i++){
let userId = lobbies[data.lobbyName][i]
userPreviousData[userId] = tempPreviousData[userId]
tempPreviousData[userId] = ''
}
}
else{}
console.log(`Everyone is ${nextEvent}`)
if (nextEvent == 'game-finished'){
let allChainedData = []
let allPlayerList = []
for (var userId of lobbies[data.lobbyName]){
allChainedData.push(userChainedData[userId])
allPlayerList.push(users[userId])
userStatus[userId] = false
}
io.in(data.lobbyName).emit('game-finished', {allChainedData, allPlayerList})
}
else{
for (var userId of lobbies[data.lobbyName]){
let senderObj = {reciever: userId, eventName: nextEvent, curWord: userCurrentData[userId]}
io.in(data.lobbyName).emit('next-match', senderObj)
userStatus[userId] = false
}
}
}
})
socket.on('ready-up', (sender)=> {
console.log("Player Attempting to Ready")
if (readyInformation[sender.lobby][sender.userId] == null ||
!readyInformation[sender.lobby][sender.userId]) {
readyInformation[sender.lobby][sender.userId] = true
readyNumber[sender.lobby]++
io.in(sender.lobby).emit('someone-readied')
}
})
// Call this function when the round is over and
// userTotalData[] is full so that it can accurately
// create userChainedData
function compute_chain(lobbyName) {
let number = 0
if (lobbies[lobbyName] != null) {
number = lobbies[lobbyName].length
}
for (let i = 0; i < number; i++) {
let index = 0
let initialId = lobbies[lobbyName][i]
let userId = lobbies[lobbyName][i]
do {
userChainedData[initialId].push(userTotalData[userId][index])
userId = userNextPlayer[userId]
index++
} while(userId != initialId);
}
}
/*
socket.on('ready-down', (sender)=> {
console.log("Player Attempting to Unready")
if (readyInformation[sender.lobby][sender.userId] == null ||
!readyInformation[sender.lobby][sender.userId]) {
console.log("Warning: Code should not be going here")
console.log("Server is attempting to unready a player that isn't ready")
}
else {
readyInformation[sender.lobby][sender.userId] = false
readyNumber[sender.lobby]--
io.in(sender.lobby).emit('someone-readied')
}
})
*/
// Determines if a given lobby should start
socket.on('should-start', (lobbyName)=> {
console.log("Determining if " + lobbyName + " should start")
console.log(`${readyNumber[lobbyName]} ready of ${lobbies[lobbyName].length}`)
if (readyInformation[lobbyName] != null && readyNumber[lobbyName] != null) {
if (readyNumber[lobbyName] == lobbies[lobbyName].length) {
socket.emit('should-start-return', true)
} else {
socket.emit('should-start-return', false)
}
}
})
// The reason this function exists is because i need to call
// the code from 'guessed-word' and 'getsend-prev-data'
function doGuess(guessedWord) {
var nextPlayer = userNextPlayer[socket.id]
let nextNextPlayer = userNextPlayer[nextPlayer]
tempPreviousData[nextNextPlayer] = guessedWord
userCurrentData[nextPlayer] = guessedWord
userTotalData[socket.id].push(guessedWord)
console.log(`${users[socket.id]} sent ${users[nextPlayer]} the word ${guessedWord}`)
socket.emit('sent-info', 'guessing')
}
socket.on('guessed-word', (guessedWord)=>{
doGuess(guessedWord)
})
socket.on('send-drawing', drawing=> {
var nextPlayer = userNextPlayer[socket.id]
userCurrentData[nextPlayer] = drawing
userTotalData[socket.id].push(drawing)
socket.emit('sent-info', 'drawing')
})
function wordScramble(word) {
console.log("Word is: " + word)
word = word.toLowerCase()
let visited = new Array(word.length)
let finalWord = ''
for (let i = 0; i < word.length; i++) {
let number = Math.floor(Math.random() * (word.length - i))
let currentValue = 0
for (let z = 0; z < word.length; z++) {
if (number > 0) {
if (visited[z] == undefined) {
number--
}
} else {
if (visited[z] == undefined) {
currentValue = z
break;
}
}
}
visited[currentValue] = true
let theChar = word.charAt(currentValue)
if (i == 0){
theChar = theChar.toUpperCase()
}
finalWord = finalWord + theChar
}
return finalWord
}
socket.on('getsend-prev-data', userId =>{
console.log(userId +" Attempting to get previous data " + userPreviousData[userId])
doGuess(wordScramble(userPreviousData[userId]))
})
socket.on('play-again', lobbyName=>{
userCurrentData[socket.id] = null
userPreviousData[socket.id] = ''
tempPreviousData[socket.id] = ''
userTotalData[socket.id] = []
userChainedData[socket.id] = []
})
})
http.listen(port, () => {
console.log('Listening on port: ', + port);
})