-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgame.js
1457 lines (1316 loc) · 37.8 KB
/
game.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// loaded modules
var utils = require('./utils.js');
var PokerEvaluator = require('poker-evaluator');
/**
* Player object to send down in an event
*
* @typedef {String} eventPlayer - username
*
*/
/*
*
* Betting Object Type Declaration
*
* @typedef {Object} eventBet
*
* @property {Number} amount - number of coins to bet
* @property {eventPlayer} player - the player that bet
*/
// events
/**
* Event for users connecting to the socketio socket
*
* @event connection
*/
var connection = 'connection';
/**
* Event for ANOTHER user joining our game
*
* @event playerSatDown
* @type {eventPlayer}
*/
var playerSatDown = 'playerSatDown';
/**
* Event to tell who needs to ante
*
* @event playersNeedToAnte
*
* @type {Player[]}
*/
var playersNeedToAnte = 'playersNeedToAnte';
/**
* Event to tell the room that a player has anted
*
* @event playerPaidAnte
*
* @type {Player}
*/
var playerPaidAnte = 'playerPaidAnte';
/**
* Event to tell the room that the dealer has dealt hole cards to every player
*
* @event dealerDealtHoleCards
* @type {String[]}
*/
var dealerDealtHoleCards = 'dealerDealtHoleCards';
/**
* Event to tell the room a player has bet
*
* @event playerBet
*
* @type {eventBet}
*/
var playerBet = 'playerBet';
/**
* Event to tell the room who has to bet next
*
* @event playerNeedsToBet
*
* @type {eventBet}
*/
var playerNeedsToBet = 'playerNeedsToBet';
/**
* Event to tell the room the dealer dealt the community cards
*
* @event dealerDealtCommunityCards
*
* @type {String[]}
*/
var dealerDealtCommunityCards = 'dealerDealtCommunityCards';
/**
* Event to tell the room which player won
*
* @event playerWon
*
* @type {eventPlayer}
*/
var playerWon = 'playerWon';
/**
* Event to tell the board the game has been reset
*
* @event dealerResetGame
*
*/
var dealerResetGame = 'dealerResetGame';
/**
* Event to broadcast that a player has quit
*
* @event playerLeft
*
* @type {eventPlayer}
*/
var playerLeft = 'playerLeft';
/**
* Event to tell update a player about what's going on in the game when they joined
*
* @event youSatDown
*
* @type {eventPlayer[]}
*/
var youSatDown = 'youSatDown';
/**
* Event to tell the server you're joining our fun game
*
* @event iSatDown
*/
var iSatDown = 'iSatDown';
/**
* Event to tell the server a player has bet
*
* @event iBet
*
* @type {Number} - amount
*/
var iBet = 'iBet';
/**
* Event to tell the player I left the game
*
* @event iLeft
*/
var iLeft = 'disconnect';
/**
* Max number of players that can sit down at a table. Others will be watchers
*
* @const {number}
*/
var MAX_PLAYERS = 10;
/**
* Mininum number of players to start a game
* @const {number}
*/
var MIN_PLAYERS_TO_START = 1;
/**
* The longest time we can possibly wait for a player to reconnect
*
* @const {number}
*/
var RECONNET_TIMEOUT_MS = 30 * 1000;
// Globals
/**
* Hashmap holding all of the rooms currently active
*
* @type {Object.<number, Table>}
*/
var rooms = {};
/**
* Adds a bunch of events to the socketio object
*
* @param {SocketIO} socketio
* @param {Sequelize} db
*/
var game = function(socketio, db) {
/**
* Event for users connecting to the socketio socket
*
* @listens connection
*/
socketio.on(
connection,
/**
* Callback for when a user connects
*
* @param {SocketIO} userSocket -- connected user socket
*/
function (userSocket) {
console.log("Listened to a connection event");
/**
* The current table
*
* @type {Table}
*/
var table = null;
/**
* The currently connected user as a player
* @type {Player}
*/
var player;
// user-specific handlers
/**
* Event for when a user joins a specific room
*
* @listens iSatDown
*/
userSocket.on(
iSatDown,
/**
* Callback for a user joining a specific room
*
* @param {number} roomID the id of the room we are joining
*/
function (roomID) {
console.log("Listened to a iSatDown event");
// get the Room object first...
db.Room.findById(roomID.roomID).exec(
/**
* Function to run when we get our room object back
*
* @param {db.Room} room - room with roomID
*/
function (err, room) {
if (err) {
throw err;
}
// instantiate our user now
player = new Player(userSocket, userSocket.handshake.user, parseInt(room.buyin));
userSocket.join(room.id);
/**
* @fires playerSatDown
*/
userSocket.broadcast.to(room.id).emit(playerSatDown, player.playerModel.username);
// if we haven't instantiated anything yet...
if (!(room.id in rooms)) {
rooms[room.id] = new Table(room);
}
table = rooms[room.id];
// add our user if we are not full to the table
if (table.players.length < MAX_PLAYERS) {
console.log("adding player to table");
table.players.push(player);
}
userSocket.emit(
youSatDown,
{
players: table.players.map(function (player) { return player.playerModel.username; }),
ante: table.ante
}
);
// Now that we have the room...
/**
* Handle disconnects
*
* @listens iLeft
*/
userSocket.on(
iLeft,
function () {
// TODO give money back to user!
console.log("Listened to a disconnect event");
// TODO reconnect stuff here
for (var i = 0; i < table.players.length; i++) {
if (table.players[i].socket === userSocket) {
// remove this player
table.players.slice(i, 1);
}
}
userSocket.broadcast.to(room.id).emit(
playerLeft,
player.playerModel.username
);
}
);
/**
* Event for when a player readys-up
*
* @listens iBet
*/
userSocket.on(
iBet,
/**
* Function to be run when a player bet
*
* @param {Number} amount - amount bet
*/
function (amount) {
console.log("Listened to a bet event");
// only bet ante if the player hasn't, is in the table, and the game isn't started
if (!table.isGameBeingPlayed() && !player.isReady && table.players.indexOf(player) !== -1) {
// this must be an ante!
table.bet(player, amount);
var x = table.continue();
if (x) {
table.players.forEach(
/**
* For every player, let them know their cards
*/
function (player) {
/**
* @fires dealerDealtHoleCards
*/
player.socket.emit(
dealerDealtHoleCards,
table.cardsCensored(player)
);
}
);
} else {
// TODO replace with an Array.prototype.filter we should create
var missingAntiedPlayers = [];
for (var i = 0; i < table.players.length; i++) {
if (!table.players[i].isReady) {
missingAntiedPlayers.push(table.players[i].playerModel.username);
}
}
userSocket.broadcast.to(room.id).emit(playersNeedToAnte, missingAntiedPlayers);
userSocket.emit(playersNeedToAnte, missingAntiedPlayers);
}
} else {
// this is not an ante!
var isContinued = false;
var newCommunityCardsObject = null;
console.log("Listened to a bet event");
console.log(amount);
if (table.canBet(player)) {
console.log("doing bet");
table.bet(player, amount);
// let the game know this player has bet
userSocket.broadcast.to(room.id).emit(
playerBet,
{
player: player.playerModel.username,
amount: amount
}
);
userSocket.emit(
playerBet,
{
player: player.playerModel.username,
amount: amount
}
);
// let the game know who is the next better... if there is one
var nextBet = table.playerBetManager.nextBetter();
if (nextBet) {
userSocket.broadcast.to(room.id).emit(
playerNeedsToBet,
{
player: nextBet.player.playerModel.username,
amount: nextBet.amount
}
);
userSocket.emit(
playerNeedsToBet,
{
player: nextBet.player.playerModel.username,
amount: nextBet.amount
}
);
}
isContinued = table.continue();
if (isContinued && Table.stages.FLOP <= table.lastStage <= Table.stages.RIVER) {
// tell the entire room cards have been dealt
userSocket.broadcast.to(room.id).emit(
dealerDealtCommunityCards,
table.getNewCommunityCards()
);
userSocket.emit(
dealerDealtCommunityCards,
table.getNewCommunityCards()
);
} else if (Table.stages.WINNER) {
// TODO deal with winners here
userSocket.broadcast.to(room.id).emit(
playerWon,
table.winner.playerModel.username
);
userSocket.emit(
playerWon,
table.winner.playerModel.username
);
table.winner.coin += table.pot;
table.reset();
userSocket.broadcast.to(room.id).emit(dealerResetGame);
userSocket.emit(dealerResetGame);
}
}
}
}
);
}
);
}
);
}
);
};
/**
* Creates a new specific card
*
* @constructor
* @param {(number|char)} rank - the rank, 2-9 or T,J,Q,K,A
* @param {char} suit - from Card.*
*/
var Card = function(rank, suit) {
this.rank = null;
this.suit = null;
// make sure rank is correct
if (!((2 <= rank <= 9) || rank === 'T' || rank === 'J' || rank === 'Q' || rank === 'K' || rank === 'A' )) {
console.log(rank);
throw "Incorrect rank";
}
// make sure the suit is correct
switch (suit) {
case Card.DIAMONDS:
case Card.CLUBS:
case Card.SPADES:
case Card.HEARTS:
// everything is fine!
break;
default:
console.log(suit);
throw "Incorrect suit";
}
this.rank = rank;
this.suit = suit;
};
/**
* The Suit of our card
*
* @memberof! Card
* @instance
* @type {char}
*/
Card.prototype.suit = Card.DIAMONDS;
/**
* The Rank of our card
*
* @memberof! Card
* @instance
* @type {(number|char)}
*/
Card.prototype.rank = 2;
/**
* Return a string representation of this card
*
* @memberof Card
* @instance
* @method toString
* @returns {string} String Representation
*/
Card.prototype.toString = function() {
return [this.rank, this.suit].join('');
};
/**
* Return a json representation of this card
*
* @method toJSON
* @instance
* @memberof Card
* @returns {string} String Representation
*/
Card.prototype.toJSON = function () {
return [this.rank, this.suit];
}
/**
* @memberof! Card
* @static
*/
Card.DIAMONDS = 'd';
/**
* @memberof! Card
* @static
*/
Card.CLUBS = 'c';
/**
* @memberof! Card
* @static
*/
Card.SPADES = 's';
/**
* @memberof! Card
* @static
*/
Card.HEARTS = 'h';
/**
* @memberof! Card
* @static
*/
Card.JACK = 'J';
/**
* @memberof! Card
* @static
*/
Card.QUEEN = 'Q';
/**
* @memberof! Card
* @static
*/
Card.KING = 'K';
/**
* @memberof! Card
* @static
*/
Card.ACE = 'A';
/**
* @memberof! Card
* @static
*/
Card.RANKS = [2, 3, 4, 5, 6, 7, 8, 9, 'T', Card.JACK, Card.QUEEN, Card.KING, Card.ACE];
/**
* @memberof! Card
* @static
*/
Card.SUITS = [Card.HEARTS, Card.SPADES, Card.CLUBS, Card.DIAMONDS];
/**
* @memberof! Card
* @function
* @static
* @param {Card} card -- the card to test
*/
Card.isActuallyACard = function (card) {
return card.hasOwnProperty('rank') && card.hasOwnProperty('suit');
};
/**
* Hand object
*
* @constructor
* @param {Card[]} cards - list of cards
*/
var Hand = function(cards) {
this.cards = [];
// Check that we are in fact, cards
if (!utils.all(Card.isActuallyACard, cards)) {
throw "Not all items in hand are cards";
}
this.cards = cards;
};
/**
* List of cards
*
* @memberof! Hand
* @instance
* @type {Card[]}
*/
Hand.prototype.cards = [];
/**
* Get the evaluated hand representation
*
* @memberof Hand
* @instance
* @method
* @returns {object}
*/
Hand.prototype.getEval = function () {
// TODO create a better representation
return PokerEvaluator.evalHand(this.cards.map(function (x) { return x.toJSON(); }));
};
/**
* Gets a JSONic representation of this hand
*
* @memberof Hand
* @instance
* @method
* @returns {object}
*/
Hand.prototype.toJSON = function () {
var obj = {};
obj.cards = this.cards.map(function (x) { return x.toJSON(); });
// PokerHand.evaluator will fail on cards.length === 2
if (this.cards.length === 3 || this.cards.length === 5 || this.cards.length === 7) {
obj.stats = this.getEval();
}
return obj;
};
/**
* Deck object that holds many cards
* @constructor
* @param {Card[]} cards - list of cards in the deck
*/
var Deck = function(cards) {
this.cards = [];
// Check that we are in fact, cards
if (!utils.all(Card.isActuallyACard, cards)) {
throw "Not all items in hand are cards";
}
this.cards = cards;
};
/**
* @memberof! Deck
* @instance
* @type {Card[]}
*/
Deck.prototype.cards = [];
/**
* Gets a JSONic representation of this deck
*
* @memberof Deck
* @instance
* @method
* @returns {object}
*/
Deck.prototype.toJSON = function () {
return this.cards.map(
function (card) {
return card.toJSON();
}
);
};
/**
* Gets a string representation of this deck
*
* @memberof Deck
* @instance
* @method
* @returns {string}
*/
Deck.prototype.toString = function () {
return this.cards.join(',');
};
/**
* Shuffles the deck of cards
*
* @memberof Deck
* @method
*/
Deck.prototype.shuffle = function () {
// Fischer-Yates Shuffle
for (var i = this.cards.length -1; i--; i <= 1) {
var j = Math.round(Math.random() * i);
var temp = this.cards[i];
this.cards[i] = this.cards[j];
this.cards[j] = temp;
}
};
/**
* Gets one card from the top of the deck
*
* @memberof Deck
* @method
*/
Deck.prototype.pop = function () {
return this.cards.pop();
};
/**
* Builds a deck suitable for playing poker
*
* @returns{Deck} - deck with your ordinary French Deck 52 cards
*/
var PokerDeck = function() {
// have a place to store all 52 cards
var cards = [];
// Create all 52 cards, and fill cards
Card.SUITS.forEach(
function (suit) {
Card.RANKS.forEach(
function (rank) {
cards.push(new Card(rank, suit));
}
);
}
);
// build a deck with these cards, and use it as the return value
return new Deck(cards);
};
/**
* Player object
*
* @constructor
* @param {SocketIO} socket - socket for the specific user
* @param {number} coin - how much money they are playing with
*/
var Player = function(socket, playerModel, coin) {
this.socket = null;
this.coin = 0;
this.hand = null;
this.isReady = false;
this.playerModel = null;
this.socket = socket;
this.playerModel = playerModel;
this.coin = coin;
};
/**
* The mongoose model for this particular player
*
* @type {db.Player}
*/
Player.prototype.playerModel = null;
// TODO actually sit here and think about this instead of coming up with a 5s hack
Player.usedUsernames = [];
Player.usernames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
Player.getRandomUserName = function () {
var username = Player.usernames[Math.floor(Math.random() * Player.usernames.length)];
if (Player.usedUsernames.indexOf(username) != -1) {
// try again
return Player.getRandomUserName();
}
return username;
};
/**
* Handle of the user's socket
*
* @memberof! Player
* @instance
* @type {SocketIO}
*/
Player.prototype.socket = null;
/**
* The amount of money the player has to play with
*
* @memberof! Player
* @instance
* @type {number}
*/
Player.prototype.coin = 0;
/**
* The player's current two-card hand
*
* @memberof! Player
* @instance
* @type {Hand}
*/
Player.prototype.hand = null;
/**
* Did this player ready-up?
*
* @memberof! Player
* @instance
* @type {bool}
*/
Player.prototype.isReady = false;
/**
* Player's username
*
* @memberof! Player
* @instance
* @type {String}
*/
Player.prototype.username = '';
/**
* Table of a poker room
*
* @constructor
* @param {db.Room} room - one specific room that we will update with our info
*/
var Table = function(room) {
this.room = null;
this.players = [];
this.pot = 0;
this.lastStage = Table.stages.LOADED;
this.cards = null;
this.playerBetManager = new PlayerBetManager([]);
this.winner = null;
// we need the full DB object
// deal a new deck
this.deck = PokerDeck();
this.deck.shuffle();
this.room = room;
this.playerBetManager = new PlayerBetManager([]);
// TODO get ante from room
this.ante = 0;
};
/**
* Different stages that we could be in
*
* @enum {number}
* @readonly
* @memberof! Table
* @static
*/
Table.stages = {
LOADED: 0,
DEALT_HOLE_CARDS: 1,
FLOP: 2,
TURN: 3,
RIVER: 4,
WINNER: 5
};
/**
* Room Object
*
* @memberof! Table
* @instance
* @type {Room}
*/
Table.prototype.room = null;
Table.prototype.ante = 0;
/**
* Players of a particular table
* @memberof! Table
* @instance
* @type {Player[]}
*/
Table.prototype.players = [];
/**
* The cash money in the pot
*
* @memberof! Table
* @instance
* @type {number}
*/
Table.prototype.pot = 0;
/**
* The last stage we completed
*
* @memberof! Table
* @instance
* @type {number}
*/
Table.prototype.lastStage = Table.stages.LOADED;
/**
* Current cards on the table
* @memberof! Table
* @instance
* @type {Card[]}
*/
Table.prototype.cards = null;
/**
* player bet manager obj
*
* @memberof! Table
* @instance
* @type {PlayerBetManager}
*/
Table.prototype.playerBetManager = null;
/**
* Winner of the game
*
* @memberof! Table
* @instance
* @type {Player}
*/
Table.prototype.winner = null;
/**
* Get the latest dealt community cards
*/
Table.prototype.getNewCommunityCards = function () {
var cardArray = [];
console.log(this.cards);
switch (this.lastStage) {
case Table.stages.FLOP:
cardArray = [this.cards.cards[0], this.cards.cards[1], this.cards.cards[2]];
break;
case Table.stages.TURN:
cardArray = [this.cards.cards[3]];
break;
case Table.stages.RIVER:
cardArray = [this.cards.cards[4]];
break;
}
console.log(cardArray);
console.log(cardArray.map(function (card) { return card.toString(); }));
return cardArray.map(function (card) { return card.toString(); });
};
/**
* Get the next betting player
*
* @memberof Table
* @instance
* @method
* returns {Player}
*/
Table.prototype.getNextBetter = function () {
return this.playerBetManager.nextBetter().player;
};
/**
* Deal hole cards to players
*
* @memberof Table
* @instance
* @method
*/
Table.prototype.dealToPlayers = function () {
// We will create players.length piles of two cards, to simulate real dealing
// Rather than popping two cards off at a time for a player
var piles = [];
var deck = this.deck;
var players = this.players;
// make sure piles is full of arrays
for (var i = 0; i < players.length; i++) {
piles[i] = [];
}
// do this twice
for (i = 0; i <= 1; i++) {
// for as many players as we have
for (var j = 0; j < players.length; j++) {
piles[j].push(deck.pop());
}
}
// and... make hands out of'em to the dealer
for (i = 0; i < players.length; i++) {
players[i].hand = new Hand(piles[i]);
}
// and finally, save the (changed) deck object into the room
this.deck = deck;
this.room.save();
};
/**
* @type {Deck}
*/
Table.prototype.deck = PokerDeck();
/**
* Deal the flop to the table
*
* @memberof Table
* @instance
* @method
* @todo do it
*/
Table.prototype.dealFlop = function () {
var cards = [];
var deck = this.deck;
for (var i = 0; i < 3; i ++) {