-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
537 lines (445 loc) · 17.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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
// socket.rooms // salas donde esta unido el socket.
// socket.rooms es un OBJETO. Los atributos son el nombre las salas, y contienen el nombre de la sala.
// io.sockets.adapter.rooms // salas creadas en el servidor.
// Cuidado: chequear siempre el socket.id antes de hacer algo con el, si no existe el server crashea. Esto aplica para las funciones que envien desde el cliente el socket.id
/* Optimizaciones:
No mandar el socket id desde el cliente. Usar algun atributo que probablemente tenga socket.io
Evitar usar self = this. Esto copiara toda la clase y no se utiliza toda, tratar de copiar solo lo necesario.
*/
// Socket and server settings.
const express = require('express');
const socketIO = require('socket.io');
//const HashMap = require('hashmap');
var app = express();
var server = app.listen(3000);
var io = socketIO(server);
//var map = new HashMap();
app.use(express.static('public'));
io.sockets.on('connection', newConnection);
var table = new Array();
var numbers = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
var suits = ['Spades', 'Clubs', 'Diamonds', 'Hearts'];
var decks = 1;
var deck = new Array();
var tables = new Array();
const players = 3;
const maximumRounds = 5;
const initialMoney = 500;
const playTimeoutTime = 30000;
const timeBetweenRounds = 5000;
const constantBet = 100;
const poolTimeout = 30000;
const pickSuitTimeout = 10000;
const pickSuitDelay = 5000;
class Card{
constructor(index, number, suit){
this.index = index;
this.number = number;
this.suit = suit;
if(this.suit == "Hearts" || this.suit == "Diamonds"){
this.color = true;
}
else{
this.color = false;
}
}
}
class Player{
constructor(socketId, money, playerIndex){
this.socketId = socketId;
this.money = money;
this.playerIndex = playerIndex;
}
add(money){
this.money += money;
}
substract(money){
this.money -= money;
}
}
class Table{
constructor(player, socketRoom, maximumPlayers, maximumRounds, initialMoney, playTimeoutTime, constantMoneyBet){
console.log('Se creo la mesa');
this.socketRoom = socketRoom;
this.initialMoney = initialMoney;
this.maximumPlayers = maximumPlayers;
this.maximumRounds = maximumRounds;
this.constantMoneyBet = constantMoneyBet;
//this.players = this.initiatePlayers(players, initialMoney);
this.players = new Array();
this.addPlayer(player);
//player es un ID.
//players es un arreglo de IDS.
this.suits = new Array();
this.pool = 0;
this.playTurn = 0;
this.round = 0;
this.readyAnswer = 0;
this.poolAccept = 0;
this.poolAnswer = 0;
this.playTimeoutTime = playTimeoutTime;
this.poolTimeoutVariable;
this.chooseFirstTimeoutVariable;
this.deck = this.shuffle(this.generateDeck());
this.colorBets = new Array();
}
addPlayer(player){
var self = this;
this.players.push(player);
console.log('jugador añadido');
io.sockets.sockets[player].on('ready', ready);
function ready(socketId){
io.sockets.sockets[socketId].removeListener('ready', ready);
if(++self.readyAnswer == self.maximumPlayers){
console.log('Iniciamos');
self.readyAnswer = 0;
self.chooseFirst();
}
}
if(this.players.length == this.maximumPlayers){
this.players = this.initiatePlayers(this.players, this.initialMoney);
console.log('Esperando por los ready');
}
}
initiatePlayers(playersId, initialMoney){
var temporalObjectArray = new Array();
for(var i = 0; i < playersId.length; i++){
temporalObjectArray[i] = new Player(playersId[i], initialMoney, i);
}
this.addChat(temporalObjectArray);
return temporalObjectArray;
}
addChat(players){
var self = this;
for(var i = 0; i < players.length; i++){
io.sockets.sockets[players[i].socketId].on('chat', chat);
}
function chat(message){
io.sockets.to(self.socketRoom).emit('chat', message);
}
}
generateDeck(){
var temporalArray = new Array();
for(var i = 0; i < decks; i++){
for(var j = 0; j < numbers.length; j++){
for(var k = 0; k < suits.length; k++){
temporalArray.push(new Card(j*4 + k, numbers[j], suits[k]));
}
}
}
return temporalArray;
}
dealCard(remove){
var random = Math.floor(Math.random() * this.deck.length);
var card = this.deck[random];
if(remove){
this.deck.splice(deck.indexOf(card), 1);
}
return card;
}
shuffle(array){
var newArray = array;
var arrayLength = array.length;
var randomNumber;
var temp;
while(arrayLength){
randomNumber = Math.floor(Math.random() * arrayLength--);
temp = newArray[arrayLength];
newArray[arrayLength] = newArray[randomNumber];
newArray[randomNumber] = temp;
}
return newArray;
}
begin(){
this.deck = this.shuffle(this.deck);
}
waitReady(){
}
chooseFirst(){
var self = this;
this.suits = new Array();
this.chooseFirstCounter = 0;
io.sockets.to(this.socketRoom).emit('suitRequest');
for(var i = 0; i < this.maximumPlayers; i++){ // Asignamos event listener a todos los usuarios.
io.sockets.sockets[this.players[i].socketId].on('suit', chooseFirstTurn);
}
function chooseFirstTurn(suit, socketId){
io.sockets.sockets[socketId].removeListener('suit', chooseFirstTurn); // Quitamos el listener del usuario que eligio.
console.log('picked: '+suit);
for(var i = 0; i < self.maximumPlayers; i++){
if(self.players[i].socketId == socketId){ // Revisamos que jugador lo hizo y guardamos la pinta (suit) en ese espacio del arreglo self.suits.
self.suits[i] = suit;
break;
}
}
io.sockets.to(self.socketRoom).emit('pickedSuit', suit); // Enviamos el arreglo con la pinta elegida por cada jugador. Mostrarlo en pantalla.
if(++self.chooseFirstCounter == self.maximumPlayers){ // Si ya todos eligieron, sacamos una carta y la enviamos al cliente.
var validSuit = true;
while(validSuit){
var card = self.dealCard(false);
for(var i = 0; i < self.maximumPlayers; i++){ // Revisamos que jugador gano.
if(self.suits[i] == card.suit){
self.playTurn = i; // Le decimos que el turno es el i. Tengo que revisar esto. Si comentas esta linea el va a arrancar en el jugador 1 siempre.
validSuit = false;
break;
}
}
}
io.sockets.to(self.socketRoom).emit('donePicking', card); // Enviamos el socket con la pinta de la carta.
var setTime = setTimeout(function(){ // En ciertos segundos inicia la partida normalmente.
self.start();
}, pickSuitDelay);
}
}
}
start(){
if(this.round < this.maximumRounds){
io.sockets.to(this.socketRoom).emit('round', ++this.round);
var betCounter = 0;
this.constantBet();
}
else{
this.end();
}
}
constantBet(){
//this.pool = 0; // Ahora se hace en sendreward.
var temporalArray = new Array();
for(var i = 0; i < this.maximumPlayers; i++){
this.players[i].substract(this.constantMoneyBet);
temporalArray.push(this.players[i].money);
this.pool += this.constantMoneyBet;
}
io.sockets.to(this.socketRoom).emit('substractConstantBet', temporalArray);
this.chooseColor();
}
chooseColor(){
var previousBetTurn = this.playTurn;
if(++this.playTurn >= this.maximumPlayers){
this.playTurn = 0;
}
this.play(previousBetTurn, 0);
}
bet(turn, betCounter){
var self = this;
var currentSocketId = this.players[turn].socketId;
io.sockets.sockets[currentSocketId].on('getBet', betFunction);
function betFunction(money){
clearTimeout(setTime);
io.sockets.sockets[currentSocketId].removeListener('getBet', betFunction);
io.sockets.to(self.socketRoom).emit('bettedMoney', money, turn);
self.players[turn].substract(money);
self.pool += money;
var temporalObject = {
counter: betCounter,
turn: turn
}
if(self.checkCounters(temporalObject, self.maximumPlayers)){
self.bet(temporalObject.turn, temporalObject.counter);
}
else{
self.chooseColor();
}
}
io.sockets.to(this.socketRoom).emit('bet', currentSocketId, turn);
var setTime = setTimeout(function(){
io.sockets.sockets[currentSocketId].removeListener('getBet', betFunction);
io.sockets.to(self.socketRoom).emit('timedOut', turn);
var temporalObject = {
counter: betCounter,
turn: turn
}
if(self.checkCounters(temporalObject, self.maximumPlayers)){
self.bet(temporalObject.turn, temporalObject.counter);
}
else{
self.chooseColor();
}
}, this.playTimeoutTime);
}
play(turn, playCounter){
var self = this;
var currentSocketId = this.players[turn].socketId;
io.sockets.sockets[currentSocketId].on('getPlay', playFunction);
function playFunction(color){
clearTimeout(setTime);
io.sockets.sockets[currentSocketId].removeListener('getPlay', playFunction);
io.sockets.to(self.socketRoom).emit('bettedColor', color, turn);
self.colorBets[turn] = color; // true: red, false: black.
var temporalObject = {
counter: playCounter,
turn: turn
}
if(self.checkCounters(temporalObject, self.maximumPlayers)){
self.play(temporalObject.turn, temporalObject.counter);
}
else{
//io.sockets.to(self.socketRoom).emit('play', currentSocketId, ++turn, true);
self.reward(self.colorBets);
}
}
//io.sockets.to(self.socketRoom).emit('play', currentSocketId, turn, false);
io.sockets.to(self.socketRoom).emit('play', currentSocketId, turn, this.playTimeoutTime);
var setTime = setTimeout(function(){
var randomPick = self.randomColor();
io.sockets.sockets[currentSocketId].removeListener('getPlay', playFunction);
io.sockets.to(self.socketRoom).emit('bettedColor', randomPick, turn);
io.sockets.to(self.socketRoom).emit('timedOut', turn);
self.colorBets[turn] = randomPick; // true: red, false: black.
var temporalObject = {
counter: playCounter,
turn: turn
}
if(self.checkCounters(temporalObject, self.maximumPlayers)){ // Dentro de checkcounters es que se suman los contadores.
self.play(temporalObject.turn, temporalObject.counter);
}
else{
self.reward(self.colorBets);
}
}, this.playTimeoutTime);
}
reward(colorArray){
var card = this.dealCard(true);
var counter = 0;
var self = this;
var balance = new Array();
io.sockets.to(this.socketRoom).emit('deal', card);
for(var i = 0; i < this.maximumPlayers; i++){
if(colorArray[i] == card.color){
counter++;
}
}
if(counter == 0){
// House won.
for(var i = 0; i < this.maximumPlayers; i++){
balance.push(this.players[i].money);
}
io.sockets.to(this.socketRoom).emit('reward', 0, 0, balance, 0, true);
this.pool = 0;
this.sendReward(0, 0, false, 0, 0);
}
else if(counter == this.maximumPlayers){
this.poolTimeoutVariable = setTimeout(function(){
poolAnswer(false, 0);
}, poolTimeout);
this.poolAnswer = 0;
for(var i = 0; i < this.maximumPlayers; i++){
io.sockets.sockets[this.players[i].socketId].on('getPoolAnswer', poolAnswer);//respuesta pool
}
io.sockets.to(this.socketRoom).emit('poolRequest');// solicitud para acumular
function poolAnswer(poolAnswerVar, socketId){
/*if(poolAnswerVar){
console.log('yes al pool');
self.poolAnswer++;
io.sockets.sockets[socketId].removeListener('getPoolAnswer', poolAnswer);
if(++self.poolAccept == self.maximumPlayers){ // Si todos dicen que si.
console.log('todos si');
self.sendReward(0, 0, false, 0, 0);
}
}
else if(++self.poolAnswer == self.maximumPlayers){ // Si uno se niega.
for(var i = 0; i < self.maximumPlayers; i++){ // Si alguien dice que no, quitamos los event listeners de todos y les hacemos reward.
io.sockets.sockets[self.players[i].socketId].removeListener('getPoolAnswer', poolAnswer);
}
self.sendReward(colorArray, counter, true, card, balance);
}*/
if(poolAnswerVar){
self.poolAccept++;
}
self.poolAnswer++;
if(self.poolAccept == self.maximumPlayers){ // Si todos dicen que si.
console.log('todos si');
self.sendReward(0, 0, false, 0, 0);
}
else if(self.poolAnswer == self.maximumPlayers){
console.log('Pool Negado');
for(var i = 0; i < self.maximumPlayers; i++){ // Si alguien dice que no, quitamos los event listeners de todos y les hacemos reward.
io.sockets.sockets[self.players[i].socketId].removeListener('getPoolAnswer', poolAnswer);
}
self.sendReward(colorArray, counter, true, card, balance);
}
}
}
else{
this.sendReward(colorArray, counter, true, card, balance);
}
}
sendReward(colorArray, counter, go, card, balance){
clearTimeout(this.poolTimeoutVariable);
var self = this;
if(go){
var prize = this.pool / counter;
var winningPlayers = new Array();
var ids = new Array();
for(var i = 0; i < this.maximumPlayers; i++){
if(colorArray[i] == card.color){
winningPlayers.push(i);
this.players[i].add(prize);
}
balance.push(this.players[i].money);
ids.push(this.players[i].socketId);
}
this.pool = 0;
io.sockets.to(this.socketRoom).emit('reward', winningPlayers, prize, balance, ids, false);
}
console.log('pool luego de sendreward: ' + this.pool);
setTimeout(function(){
self.start();
}, timeBetweenRounds);
}
checkCounters(object, maximumPlayers){
if(++object.counter < maximumPlayers){
if(++object.turn >= maximumPlayers){
object.turn = 0;
}
return true;
}
else{
return false;
}
}
end(){
console.log('Game Over');
tables.splice(tables.indexOf(this), 1);
io.sockets.to(this.socketRoom).emit('tableEnd');
io.sockets.adapter.rooms[this.socketRoom].started == false;
// Remover listeners de chat
// io.sockets.sockets[currentSocketId].removeListener('getChat', chat);
this.database();
}
database(){
// Escribir en la base de datos el dinero nuevo.
// Idea: Solo escribir en la base de datos cuando el usuario se descoencta / se va.
// Para esto se tendria que llevar el dinero de cada jugador en algun otro lado.
}
randomColor(){
if(Math.random() > 0.5){
return true;
}
else{
return false;
}
}
}
function newConnection(socket){
socket.on('join', function(room, roomCapacity){
socket.join(room);
console.log('Esto es table0: ' + table[0]);
if(table[0]){
table[1].addPlayer(socket.id);
console.log(socket.id + ' added');
}
else{
//io.sockets.adapter.rooms[room].sockets
table[0] = true;
table[1] = new Table(socket.id, room,
players, maximumRounds, initialMoney, playTimeoutTime, constantBet);
table[1].begin();
console.log('Table created');
console.log(socket.id + ' added');
}
});
socket.emit('menu');
socket.on('disconnect', function(){
});
}