-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
521 lines (454 loc) · 15.8 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 12345;
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
http.listen(port, () => console.log('listening on port ' + port));
const numRooms = 5;
const maxPeople = 10;
let deck = Array.apply(null, Array(112)).map(function (_, i) {return i;});
deck.splice(56, 1); //56
deck.splice(69, 1); //70
deck.splice(82, 1); //84
deck.splice(95, 1); //98
let new_color;
let data = [];
for (let i = 1; i <= numRooms; i++) {
let room = [];
room['timeout'] = [];
room['timeout']['id'] = 0;
room['timeout']['s'] = 10;
room['deck'] = [];
room['reverse'] = 0;
room['turn'] = 0;
room['cardOnBoard'] = 0;
room['people'] = 0;
let players = [];
for (let j = 0; j < maxPeople; j++) {
let p = [];
p['id'] = 0;
p['name'] = "";
p['hand'] = [];
players[j] = p;
}
room['players'] = players;
data['Room_'+i] = room;
}
/**
* Shuffles all elements in array
* @function
* @param {Array} a Array to shuffle
*/
function shuffle(a) {
let j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
}
/**
* Given a card number, returns its color
* @function
* @param {Number} num Number of the card position in deck
* @return {String} Card color. Either black, red, yellow, green or blue.
*/
function cardColor(num) {
let color;
if (num % 14 === 13) {
console.log("black card")
return 'black';
}
switch (Math.floor(num / 14)) {
case 0:
case 4:
color = 'red';
break;
case 1:
case 5:
color = 'yellow';
break;
case 2:
case 6:
color = 'green';
break;
case 3:
case 7:
color = 'blue';
break;
}
return color;
}
/**
* Given a card number, returns its type
* @function
* @param {Number} num Number of the card position in deck
* @return {String} Card type. Either skip, reverse, draw2, draw4, wild or number.
*/
function cardType(num) {
switch (num % 14) {
case 10: //Skip
return 'Skip';
case 11: //Reverse
return 'Reverse';
case 12: //Draw 2
return 'Draw2';
case 13: //Wild or Wild Draw 4
if (Math.floor(num / 14) >= 4) {
return 'Draw4';
} else {
return 'Wild';
}
default:
return 'Number ' + (num % 14);
}
}
/**
* Given a card number, returns its scoring
* @function
* @param {Number} num Number of the card position in deck
* @return {Number} Points value.
*/
function cardScore(num) {
let points;
switch (num % 14) {
case 10: //Skip
case 11: //Reverse
case 12: //Draw 2
points = 20;
break;
case 13: //Wild or Wild Draw 4
points = 50;
break;
default:
points = num % 14;
break;
}
return points;
}
/**
* Starts a countdown for start a game on a room
* @function
* @param {String} name Room name
*/
function startingCountdown(name) {
let countDown = data[name]['timeout']['s']--;
io.to(name).emit('countDown', countDown);
console.log('>> ' + name + ': Starting in ' + countDown);
if (countDown <= 0) {
clearInterval(data[name]['timeout']['id']);
startGame(name);
}
}
/**
* Request for start the game.
* @param {String} name Room name
*/
function startGame(name) {
console.log('>> ' + name + ': Requesting game...');
let people;
try {
people = io.sockets.adapter.rooms[name].length;
} catch (e) {
console.log('>> ' + name + ': No people here...');
return;
}
if (people >= 2) {
console.log('>> ' + name + ': Starting');
let sockets_ids = Object.keys(io.sockets.adapter.rooms[name].sockets);
for (let i = 0; i < people; i++) {
data[name]['players'][i]['id'] = sockets_ids[i];
let playerName = io.sockets.sockets[sockets_ids[i]].playerName;
data[name]['players'][i]['name'] = playerName;
console.log('>> ' + name + ': ' + playerName +
' (' + sockets_ids[i] + ') is Player ' + i);
}
data[name]['people'] = people;
//Shuffle a copy of a new deck
let newDeck = [...deck];
shuffle(newDeck);
data[name]['deck'] = newDeck;
console.log('>> ' + name + ': Shuffling deck');
//Every player draws a card.
//Player with the highest point value is the dealer.
let scores = new Array(people);
do {
console.log('>> ' + name + ': Deciding dealer');
for (let i = 0, card = 0, score = 0; i < people; i++) {
card = parseInt(newDeck.shift());
newDeck.push(card);
score = cardScore(card);
console.log('>> ' + name + ': Player ' + i + ' draws ' + cardType(card) +
' ' + cardColor(card) + ' and gets ' + score + ' points');
scores[i] = score;
}
} while (new Set(scores).size !== scores.length);
let dealer = scores.indexOf(Math.max(...scores));
console.log('>> ' + name + ': The dealer is Player ' + dealer);
//Each player is dealt 7 cards
for (let i = 0, card = 0; i < people * 7; i++) {
let player = (i + dealer + 1) % people;
card = parseInt(newDeck.shift());
data[name]['players'][player]['hand'].push(card);
console.log('>> ' + name + ': Player ' + player + ' draws '
+ cardType(card) + ' ' + cardColor(card));
}
let cardOnBoard;
console.log("IN\n")
do {
console.log("IN dowhile\n")
cardOnBoard = parseInt(newDeck.shift());
console.log('>> ' + name + ': Card on board ' +
cardType(cardOnBoard) + ' ' + cardColor(cardOnBoard));
if (cardColor(cardOnBoard) === 'black') {
console.log("black card spotted")
newDeck.push(cardOnBoard);
console.log('>> ' + name + ': Replacing for another card');
} else {
break;
}
} while (true);
console.log(data)
data[name]['cardOnBoard'] = cardOnBoard;
data[name]['turn'] = (dealer + 1) % people;
data[name]['reverse'] = 0;
console.log("cardOnboard:" + cardOnBoard);
if (cardType(cardOnBoard) === 'Draw2') {
card = parseInt(newDeck.shift());
data[name]['players'][(data[name]['turn'])]['hand'].push(card);
console.log('>> ' + name + ': Player ' + (dealer + 1 % people) +
' draws ' + cardType(card) + ' ' + cardColor(card));
card = parseInt(newDeck.shift());
data[name]['players'][(data[name]['turn'])]['hand'].push(card);
console.log('>> ' + name + ': Player ' + (dealer + 1 % people) +
' draws ' + cardType(card) + ' ' + cardColor(card));
data[name]['turn'] = (dealer + 2) % people;
} else if (cardType(cardOnBoard) === 'Reverse') {
data[name]['turn'] = Math.abs(dealer - 1) % people;
data[name]['reverse'] = 1;
} else if (cardType(cardOnBoard) === 'Skip') {
data[name]['turn'] = (dealer + 2) % people;
}
console.log('>> ' + name + ': Turn is for ' + data[name]['players'][(data[name]['turn'])]['name']);
console.log('>> ' + name + ': Reverse (' + (!!data[name]['reverse']) + ')');
for (let i = 0; i < people; i++) {
io.to(data[name]['players'][i]['id']).emit('haveCard', data[name]['players'][i]['hand']);
console.log("this is it : "+data[name]['players'][i]['hand'])
}
io.to(name).emit('turnPlayer', data[name]['players'][(data[name]['turn'])]['id']);
console.log("final : "+data[name]["cardOnBoard"]);
io.to(name).emit('sendCard', data[name]['cardOnBoard']);
} else {
console.log('>> ' + name + ': Not enough people...');
}
}
/**
* Whenever a client connects
* @function
* @param {Socket} socket Client socket
*/
function onConnection(socket) {
/**
* Whenever a room is requested, looks for a slot for the player,
* upto 10 players in a room, maxRooms and started games are respected.
* @method
* @param {String} playerName Player name
* @return responseRoom with name of the room, otherwise error.
*/
socket.on('requestRoom', function(playerName) {
socket.playerName = playerName;
for (let i = 1; i <= numRooms; i++) {
let name = 'Room_' + i;
let people;
try {
people = io.sockets.adapter.rooms[name].length;
} catch (e) {
people = 0;
}
//Reconnect
/*
for (let i = 0; i < data[name]['people']; i++) {
if (data[name]['players'][i]['name'] === socket.playerName) {
socket.join(name);
io.to(socket.id).emit('haveCard', data[name]['players'][i]['hand']);
io.to(socket.id).emit('sendCard', data[name]['cardOnBoard']);
io.to(socket.id).emit('turnPlayer', data[name]['players'][(data[name]['turn'])]['id']);
console.log('>> Reconnect');
return;
}
}*/
if (people < maxPeople && data[name]['timeout']['s'] > 0) {
socket.join(name);
console.log('>> User ' + socket.playerName +
' connected on ' + name + ' (' + (people + 1) + '/' + maxPeople + ')');
io.to(name).emit('responseRoom', [name, people + 1, maxPeople]);
if (people + 1 >= 2) {
clearInterval(data[name]['timeout']['id']);
data[name]['timeout']['s'] = 10;
data[name]['timeout']['id'] = setInterval(function() {
startingCountdown(name);
}, 1000);
}
return;
}
}
io.to(socket.id).emit('responseRoom', 'error');
console.log('>> Rooms exceeded');
});
/**
* Whenever someone is performing a disconnection,
* leave its room and notify to the rest
* @method
*/
//// TODO: Empty a room
socket.on('disconnecting', function() {
room = Object.keys(io.sockets.adapter.sids[socket.id])[1];
if (room !== undefined) {
clearInterval(data[room]['timeout']['id']);
io.to(room).emit('playerDisconnect', room);
console.log('>> ' + room + ': Player ' + socket.playerName + ' ('+
socket.id + ') leaves the room');
}
});
/**
* Whenever disconnection is completed
* @method
*/
socket.on('disconnect', function() {
console.log('>> Player ' + socket.playerName + ' ('+
socket.id + ') disconnected');
});
socket.on('drawCard', function(res) {
let numPlayer = data[res[1]]['turn'];
let idPlayer = data[res[1]]['players'][numPlayer]['id'];
let namePlayer = data[res[1]]['players']['name'];
let handPlayer = data[res[1]]['players'][numPlayer]['hand'];
let deck = data[res[1]]['deck'];
if (idPlayer === socket.id) {
let card = parseInt(deck.shift());
handPlayer.push(card);
io.to(idPlayer).emit('haveCard', handPlayer);
//deck.push(card);
// TODO: Check playable card
//Next turn
numPlayer = Math.abs(numPlayer + (-1) ** data[res[1]]['reverse']) % data[res[1]]['people'];
data[res[1]]['turn'] = numPlayer;
io.to(res[1]).emit('turnPlayer', data[res[1]]['players'][numPlayer]['id']);
}
});
socket.on('Draw4', function(ch) {
new_color = ch;
});
socket.on('playCard', function(res) {
let numPlayer = data[res[1]]['turn'];
let idPlayer = data[res[1]]['players'][numPlayer]['id'];
let namePlayer = data[res[1]]['players']['name'];
let handPlayer = data[res[1]]['players'][numPlayer]['hand'];
let deck = data[res[1]]['deck'];
let reverse = data[res[1]['reverse']];
let flag;
if (idPlayer === socket.id) {
let playedColor = cardColor(res[0]);
let playedNumber = res[0] % 14;
let boardColor = cardColor(data[res[1]]['cardOnBoard']);
if (boardColor === "black"){
let t = boardColor;
boardColor = new_color;
}
console.log("cardonboard color : "+ boardColor);
let boardNumber = data[res[1]]['cardOnBoard'] % 14;
if (playedColor === 'black'){
flag=true;
}
else{
flag=false;
}
while (playedColor==="black" && flag === true ){
io.to(res[1]).emit("sendCard", res[0]);
data[res[1]]['cardOnBoard'] = res[0];
console.log("res" + res);
let cardPos = handPlayer.indexOf(res[0]);
console.log(cardPos)
if (cardPos > -1) {
console.log(data[res[1]]['players'][numPlayer]['hand'])
data[res[1]]['players'][numPlayer]['hand'].splice(cardPos, 1);
io.to(idPlayer).emit('haveCard', data[res[1]]['players'][(data[res[1]]['turn'])]['hand']);
}
io.to(idPlayer).emit('colorDraw', res);
if (cardType(res[0])==="Wild"){
numPlayer = (numPlayer +1) % data[res[1]]['people'];
data[res[1]]['turn'] = numPlayer;
io.to(res[1]).emit('turnPlayer',data[res[1]]['players'][numPlayer]['id']);
break;
}
let card1 = parseInt(deck.shift());
let card2 = parseInt(deck.shift());
let card3 = parseInt(deck.shift());
let card4 = parseInt(deck.shift());
numPlayer = (numPlayer +1) % data[res[1]]['people'];
data[res[1]]['turn'] = numPlayer;
console.log(data[res[1]]['players'][(data[res[1]]['turn'])]);
console.log("numPlayer = "+numPlayer);
data[res[1]]['players'][(data[res[1]]['turn'])]['hand'].push(card1);
data[res[1]]['players'][(data[res[1]]['turn'])]['hand'].push(card2);
data[res[1]]['players'][(data[res[1]]['turn'])]['hand'].push(card3);
data[res[1]]['players'][(data[res[1]]['turn'])]['hand'].push(card4);
console.log("Players = "+data[res[1]]['players']);
console.log("array = "+data[res[1]]['players'][(data[res[1]]['turn'])]['hand']);
io.to(data[res[1]]['players'][numPlayer]['id']).emit('haveCard', data[res[1]]['players'][(data[res[1]]['turn'])]['hand']);
numPlayer = (numPlayer +1) % data[res[1]]['people'];
data[res[1]]['turn'] = numPlayer;
io.to(res[1]).emit('turnPlayer',data[res[1]]['players'][numPlayer]['id']);
flag = false;
}
if ( playedColor === boardColor || playedNumber === boardNumber) {
// Play card
io.to(res[1]).emit('sendCard', res[0]);
data[res[1]]['cardOnBoard'] = res[0];
// Remove card
let cardPos = handPlayer.indexOf(res[0]);
if (cardPos > -1) {
handPlayer.splice(cardPos, 1);
}
io.to(idPlayer).emit('haveCard', handPlayer);
console.log("handplayer : "+ handPlayer);
if (handPlayer.length === 0){
io.to(idPlayer).emit("win", namePlayer);
}
let card1 = parseInt(deck.shift());
let card2 = parseInt(deck.shift());
// Next turn
let skip = 0;
console.log("reverse start = "+data[res[1]]['reverse']);
console.log(res);
if (cardType(res[0]) === 'Skip') {
skip += 1;
} else if (cardType(res[0]) === 'Reverse') {
data[res[1]]['reverse'] = (data[res[1]]['reverse'] + 1) % 2;
} else if (cardType(res[0]) === 'Draw2') {
numPlayer = (numPlayer +1) % data[res[1]]['people'];
data[res[1]]['turn'] = numPlayer;
data[res[1]]['players'][(data[res[1]]['turn'])]['hand'].push(card1);
data[res[1]]['players'][(data[res[1]]['turn'])]['hand'].push(card2);
io.to(data[res[1]]['players'][numPlayer]['id']).emit('haveCard', data[res[1]]['players'][(data[res[1]]['turn'])]['hand']);
}
console.log("numplayer_start : "+ numPlayer);
console.log("reverse end = "+data[res[1]]['reverse']);
if (numPlayer === 0 && data[res[1]]['reverse'] === 1 && skip === 1){
numPlayer = (data[res[1]]['people'] -1);
data[res[1]]['turn'] = numPlayer;
}
else {
numPlayer = Math.abs(numPlayer + (-1) ** data[res[1]]['reverse'] * (1 + skip)) % data[res[1]]['people'];
data[res[1]]['turn'] = numPlayer;
//}
console.log("numplayer_end : "+ numPlayer);
}
io.to(res[1]).emit('turnPlayer', data[res[1]]['players'][numPlayer]['id']);
}
}
});
}