-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgameLogic.go
991 lines (810 loc) · 27.6 KB
/
gameLogic.go
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
package main
import (
"fmt"
"log"
"math"
"math/rand"
"sort"
"strings"
"time"
"github.com/ericcarrgh/cardrank"
"github.com/mitchellh/hashstructure/v2"
"golang.org/x/exp/slices"
)
/*
5 Card Stud Rules below to serve as guideline.
The logic to support below is not all implemented, and will be done as time allows.
Rules - Assume Limit betting: Anti 1, Bringin 2, Low 5, High 10
Suit Rank (for comparing first to act): S,H,D,C
Winning hands - tied hands split the pot, remainder is discarded
1. All players anti (e.g.) 1
2. First round
- Player with lowest card goes first, with a mandatory bring in of 2. Option to make full bet (5)
- Play moves Clockwise
- Subsequent player can call 2 (assuming no full bet yet) or full bet 5
- Subsequent Raises are inrecements of the highest bet (5 first round, or of the highest bet in later rounds)
- Raises capped at 3 (e.g. max 20 = 5 + 3*5 round 1)
3. Remaining rounds
- Player with highest ranked visible hand goes first
- 3rd Street - 5, or if a pair is showing: 10, so max is 5*4 20 or 10*4 40
- 4th street+ - 10
*/
const ANTE = 1
const BRINGIN = 2
const LOW = 5
const HIGH = 10
const STARTING_PURSE = 200
const MOVE_TIME_GRACE_SECONDS = 4
const BOT_TIME_LIMIT = time.Second * time.Duration(3)
const PLAYER_TIME_LIMIT = time.Second * time.Duration(39)
const ENDGAME_TIME_LIMIT = time.Second * time.Duration(12)
const NEW_ROUND_FIRST_PLAYER_BUFFER = time.Second * time.Duration(1)
// Drop players who do not make a move in 5 minutes
const PLAYER_PING_TIMEOUT = time.Minute * time.Duration(-5)
const WAITING_MESSAGE = "Waiting for more players"
var suitLookup = []string{"C", "D", "H", "S"}
var valueLookup = []string{"", "", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"}
var moveLookup = map[string]string{
"FO": "FOLD",
"CH": "CHECK",
"BB": "POST",
"BL": "BET", // BET LOW (e.g. 5 of 5/10, or 2 of 2/5 first round)
"BH": "BET", // BET HIGH (e.g. 10)
"CA": "CALL",
"RA": "RAISE",
}
var botNames = []string{"Clyd", "Jim", "Kirk", "Hulk", "Fry", "Meg", "Grif", "GPT"}
// For simplicity on the 8bit side (using switch statement), using a single character for each key.
// DOUBLE CHECK that letter isn't already in use on the object!
// Double characters are used for the list objects (validMoves and players)
type validMove struct {
Move string `json:"m"`
Name string `json:"n"`
}
type card struct {
value int
suit int
}
type Status int64
const (
STATUS_WAITING Status = 0
STATUS_PLAYING Status = 1
STATUS_FOLDED Status = 2
STATUS_LEFT Status = 3
)
type Player struct {
Name string `json:"n"`
Status Status `json:"s"`
Bet int `json:"b"`
Move string `json:"m"`
Purse int `json:"p"`
Hand string `json:"h"`
// Internal
isBot bool
cards []card
lastPing time.Time
}
type GameState struct {
// External (JSON)
LastResult string `json:"l"`
Round int `json:"r"`
Pot int `json:"p"`
ActivePlayer int `json:"a"`
MoveTime int `json:"m"`
Viewing int `json:"v"`
ValidMoves []validMove `json:"vm"`
Players []Player `json:"pl"`
// Internal
deck []card
deckIndex int
currentBet int
gameOver bool
clientPlayer int
table string
wonByFolds bool
moveExpires time.Time
serverName string
raiseCount int
raiseAmount int
registerLobby bool
hash string // `json:"z"` // external later
}
// Used to send a list of available tables
type GameTable struct {
Table string `json:"t"`
Name string `json:"n"`
CurPlayers int `json:"p"`
MaxPlayers int `json:"m"`
}
func initializeGameServer() {
// Append BOT to botNames array
for i := 0; i < len(botNames); i++ {
botNames[i] = botNames[i] + " BOT"
}
}
func createGameState(playerCount int, registerLobby bool) *GameState {
deck := []card{}
// Create deck of 52 cards
for suit := 0; suit < 4; suit++ {
for value := 2; value < 15; value++ {
card := card{value: value, suit: suit}
deck = append(deck, card)
}
}
state := GameState{}
state.deck = deck
state.Round = 0
state.ActivePlayer = -1
state.registerLobby = registerLobby
// Pre-populate player pool with bots
for i := 0; i < playerCount; i++ {
state.addPlayer(botNames[i], true)
}
if playerCount < 2 {
state.LastResult = WAITING_MESSAGE
}
return &state
}
func (state *GameState) newRound() {
// Drop any players that left last round
state.dropInactivePlayers(true, false)
// Check if multiple players are still playing
if state.Round > 0 {
playersLeft := 0
for _, player := range state.Players {
if player.Status == STATUS_PLAYING {
playersLeft++
}
}
if playersLeft < 2 {
state.endGame(false)
return
}
} else {
if len(state.Players) < 2 {
return
}
}
state.Round++
// Clear pot at start so players can anti
if state.Round == 1 {
state.Pot = 0
state.gameOver = false
}
// Reset players for this round
for i := 0; i < len(state.Players); i++ {
// Get pointer to player
player := &state.Players[i]
if state.Round > 1 {
// If not the first round, add any bets into the pot
state.Pot += player.Bet
} else {
// First round of a new game
// A bot will leave if it has under 25 chips, another will take their place
if player.isBot && player.Purse < 25 {
player.Purse = STARTING_PURSE
for j := 0; j < len(botNames); j++ {
botNameUsed := false
for k := 0; k < len(state.Players); k++ {
if strings.EqualFold(botNames[j], state.Players[k].Name) {
botNameUsed = true
break
}
}
if !botNameUsed {
player.Name = botNames[j]
break
}
}
}
// Reset player status and take the ANTI
if player.Purse > 2 {
player.Status = STATUS_PLAYING
player.Purse -= ANTE
state.Pot += ANTE
} else {
// Player doesn't have enough money to play
player.Status = STATUS_WAITING
}
player.cards = []card{}
}
// Reset player's last move/bet for this round
player.Move = ""
player.Bet = 0
}
state.currentBet = 0
state.raiseCount = 0
state.raiseAmount = 0
// First round of a new game? Shuffle the cards and deal an extra card
if state.Round == 1 {
// Shuffle the deck 7 times :)
for shuffle := 0; shuffle < 7; shuffle++ {
rand.Shuffle(len(state.deck), func(i, j int) { state.deck[i], state.deck[j] = state.deck[j], state.deck[i] })
}
state.deckIndex = 0
state.dealCards()
if state.LastResult == WAITING_MESSAGE {
state.LastResult = ""
}
}
state.dealCards()
state.ActivePlayer = state.getPlayerWithBestVisibleHand(state.Round > 1)
state.resetPlayerTimer(true)
}
func (state *GameState) getPlayerWithBestVisibleHand(highHand bool) int {
ranks := [][]int{}
for i := 0; i < len(state.Players); i++ {
player := &state.Players[i]
if player.Status == STATUS_PLAYING {
rank := getRank(player.cards[1:len(player.cards)])
// Add player number to start of rank to hold on to when sorting
rank = append([]int{i}, rank...)
ranks = append(ranks, rank)
}
}
// Sort the ranks by value first, the breaking tie by suit
sort.SliceStable(ranks, func(i, j int) bool {
for k := 1; k < 9; k++ {
if ranks[i][k] != ranks[j][k] {
return ranks[i][k] < ranks[j][k]
}
}
return false
})
// Return player with highest (or lowest) hand
result := 0
if highHand {
result = ranks[0][0]
} else {
result = ranks[len(ranks)-1][0]
}
// If something goes amiss, just select the first player
if result < 0 {
result = 0
}
return result
}
func (state *GameState) dealCards() {
for i, player := range state.Players {
if player.Status == STATUS_PLAYING {
player.cards = append(player.cards, state.deck[state.deckIndex])
state.Players[i] = player
state.deckIndex++
}
}
}
func (state *GameState) addPlayer(playerName string, isBot bool) {
newPlayer := Player{
Name: playerName,
Status: 0,
Purse: STARTING_PURSE,
cards: []card{},
isBot: isBot,
}
state.Players = append(state.Players, newPlayer)
}
func (state *GameState) setClientPlayerByName(playerName string) {
// If no player name was passed, simply return. This is an anonymous viewer.
if len(playerName) == 0 {
state.clientPlayer = -1
return
}
state.clientPlayer = slices.IndexFunc(state.Players, func(p Player) bool { return strings.EqualFold(p.Name, playerName) })
// If a new player is joining, remove any old players that timed out to make space
if state.clientPlayer < 0 {
// Drop any players that left to make space
state.dropInactivePlayers(false, true)
}
// Add new player if there is room
if state.clientPlayer < 0 && len(state.Players) < 8 {
state.addPlayer(playerName, false)
state.clientPlayer = len(state.Players) - 1
// Set the ping for this player so they are counted as active when updating the lobby
state.playerPing()
// Update the lobby with the new state (new player joined)
state.updateLobby()
}
// Extra logic if a player is requesting
if state.clientPlayer > 0 {
// In case a player returns while they are still in the "LEFT" status (before the current game ended), add them back in as waiting
if state.Players[state.clientPlayer].Status == STATUS_LEFT {
state.Players[state.clientPlayer].Status = STATUS_WAITING
}
}
}
func (state *GameState) endGame(abortGame bool) {
// The next request for /state will start a new game
// Hand rank details
// Rank: SF, 4K, FH, F, S, 3K, 2P, 1P, HC
state.gameOver = true
state.ActivePlayer = -1
state.Round = 5
remainingPlayers := []int{}
pockets := [][]cardrank.Card{}
for index, player := range state.Players {
state.Pot += player.Bet
if !abortGame && player.Status == STATUS_PLAYING {
remainingPlayers = append(remainingPlayers, index)
hand := ""
// Loop through and build hand string
for _, card := range player.cards {
hand += valueLookup[card.value] + suitLookup[card.suit]
}
pockets = append(pockets, cardrank.Must(hand))
}
}
evs := cardrank.StudFive.EvalPockets(pockets, nil)
order, pivot := cardrank.Order(evs, false)
if pivot == 0 {
// If nobody won, the game was aborted. Display the waiting message if this
// server does not contains bots.
humanAvailSlots, _ := state.getHumanPlayerCountInfo()
if humanAvailSlots == 8 {
state.LastResult = WAITING_MESSAGE
state.moveExpires = time.Now().Add(ENDGAME_TIME_LIMIT)
} else {
state.moveExpires = time.Now()
}
return
}
// Int divide, so "house" takes remainder
perPlayerWinnings := state.Pot / pivot
result := ""
for i := 0; i < pivot; i++ {
player := &state.Players[remainingPlayers[order[i]]]
// Award winnings to player's purse
player.Purse += int(perPlayerWinnings)
// Add player's name to result
if result != "" {
result += " and "
}
result += player.Name
}
if len(remainingPlayers) > 1 {
state.wonByFolds = false
result += strings.Join(strings.Split(strings.Split(fmt.Sprintf(" won with %s", evs[order[0]]), " [")[0], ",")[0:2], ",")
result = strings.ReplaceAll(result, "kickers", "kicker")
} else {
state.wonByFolds = true
result += " won by default"
}
state.LastResult = result
state.moveExpires = time.Now().Add(ENDGAME_TIME_LIMIT)
log.Println(result)
}
// Emulates simplified player/logic for 5 card stud
func (state *GameState) runGameLogic() {
state.playerPing()
// We can't play a game until there are at least 2 players
if len(state.Players) < 2 {
// Reset the round to 0 so the client knows there is no active game being run
state.Round = 0
state.Pot = 0
state.ActivePlayer = -1
return
}
// Very first call of state? Initialize first round but do not play for any BOTs
if state.Round == 0 {
state.newRound()
return
}
//isHumanPlayer := state.ActivePlayer == state.clientPlayer
if state.gameOver {
// Create a new game if the end game delay is past
if int(time.Until(state.moveExpires).Seconds()) < 0 {
state.dropInactivePlayers(false, false)
state.Round = 0
state.Pot = 0
state.gameOver = false
state.newRound()
}
return
}
// Check if only one player is left
playersLeft := 0
for _, player := range state.Players {
if player.Status == STATUS_PLAYING {
playersLeft++
}
}
// If only one player is left, just end the game now
if playersLeft == 1 {
state.endGame(false)
return
}
// Check if we should start the next round. One of the following must be true
// 1. We got back to the player who made the most recent bet/raise
// 2. There were checks/folds around the table
if state.ActivePlayer > -1 {
if (state.currentBet > 0 && state.Players[state.ActivePlayer].Bet == state.currentBet) ||
(state.currentBet == 0 && state.Players[state.ActivePlayer].Move != "") {
if state.Round == 4 {
state.endGame(false)
} else {
state.newRound()
}
return
}
}
// Return if the move timer has not expired
// Check timer if no active player, or the active player hasn't already left
if state.ActivePlayer == -1 || state.Players[state.ActivePlayer].Status != STATUS_LEFT {
moveTimeRemaining := int(time.Until(state.moveExpires).Seconds())
if moveTimeRemaining > 0 {
return
}
}
// If there is no active player, we are done
if state.ActivePlayer < 0 {
return
}
// Edge cases
// - player leaves when it is their move - skip over them
// - player's turn but they are waiting (out of this hand)
if state.Players[state.ActivePlayer].Status == STATUS_LEFT ||
state.Players[state.ActivePlayer].Status == STATUS_WAITING {
state.nextValidPlayer()
return
}
// Force a move for this player or BOT if they are in the game and have not folded
if state.Players[state.ActivePlayer].Status == STATUS_PLAYING {
cards := state.Players[state.ActivePlayer].cards
moves := state.getValidMoves()
// Default to FOLD
choice := 0
// Never fold if CHECK is an option. This applies to forced player moves as well as bots
if len(moves) > 1 && moves[1].Move == "CH" {
choice = 1
}
// If this is a bot, pick the best move using some simple logic (sometimes random)
if state.Players[state.ActivePlayer].isBot {
// Potential TODO: If on round 5 and check is not an option, fold if there is a visible hand that beats the bot's hand.
//if len(cards) == 5 && len(moves) > 1 && moves[1].Move == "CH" {}
// Hardly ever fold early if a BOT has an jack or higher.
if state.Round < 3 && len(moves) > 1 && rand.Intn(3) > 0 && slices.ContainsFunc(cards, func(c card) bool { return c.value > 10 }) {
choice = 1
}
// Likely don't fold if BOT has a pair or better
rank := getRank(cards)
if rank[0] < 300 && rand.Intn(20) > 0 {
choice = 1
}
// Don't fold if BOT has a 2 pair or better
if rank[0] < 200 {
choice = 1
}
// Raise the bet if three of a kind or better
if len(moves) > 2 && rank[0] < 312 && state.currentBet < LOW {
choice = 2
} else if len(moves) > 2 && state.getPlayerWithBestVisibleHand(true) == state.ActivePlayer && state.currentBet < HIGH && (rank[0] < 306) {
choice = len(moves) - 1
} else {
// Consider bet/call/raise most of the time
if len(moves) > 1 && rand.Intn(3) > 0 && (len(cards) > 2 ||
cards[0].value == cards[1].value ||
math.Abs(float64(cards[1].value-cards[0].value)) < 3 ||
cards[0].value > 8 ||
cards[1].value > 5) {
// Avoid endless raises
if state.currentBet >= 20 || rand.Intn(3) > 0 {
choice = 1
} else {
choice = rand.Intn(len(moves)-1) + 1
}
}
}
}
// Bounds check - clamp the move to the end of the array if a higher move is desired.
// This may occur if a bot wants to call, but cannot, due to limited funds.
if choice > len(moves)-1 {
choice = len(moves) - 1
}
move := moves[choice]
state.performMove(move.Move, true)
}
}
// Drop players that left or have not pinged within the expected timeout
func (state *GameState) dropInactivePlayers(inMiddleOfGame bool, dropForNewPlayer bool) {
cutoff := time.Now().Add(PLAYER_PING_TIMEOUT)
players := []Player{}
currentPlayerName := ""
if state.clientPlayer > -1 {
currentPlayerName = state.Players[state.clientPlayer].Name
}
for _, player := range state.Players {
if len(state.Players) > 0 && player.Status != STATUS_LEFT && (inMiddleOfGame || player.isBot || player.lastPing.Compare(cutoff) > 0) {
players = append(players, player)
}
}
// If one player is left, don't drop them within the round, let the normal game end take care of it
if inMiddleOfGame && len(players) == 1 {
return
}
// Store if players were dropped, before updating the state player array
playersWereDropped := len(state.Players) != len(players)
if playersWereDropped {
state.Players = players
}
// If a new player is joining, don't bother updating anything else
if dropForNewPlayer {
return
}
// Update the client player index in case it changed due to players being dropped
if len(players) > 0 {
state.clientPlayer = slices.IndexFunc(players, func(p Player) bool { return strings.EqualFold(p.Name, currentPlayerName) })
}
// If only one player is left, we are waiting for more
if len(state.Players) < 2 {
state.LastResult = WAITING_MESSAGE
}
// If any player state changed, update the lobby
if playersWereDropped {
state.updateLobby()
}
}
func (state *GameState) clientLeave() {
if state.clientPlayer < 0 {
return
}
player := &state.Players[state.clientPlayer]
player.Status = STATUS_LEFT
player.Move = "LEFT"
// Check if no human players are playing. If so, end the game
playersLeft := 0
for _, player := range state.Players {
if player.Status == STATUS_PLAYING && !player.isBot {
playersLeft++
}
}
// If the last player dropped, stop the game and update the lobby
if playersLeft == 0 {
state.endGame(true)
state.dropInactivePlayers(false, false)
return
}
}
// Update player's ping timestamp. If a player doesn't ping in a certain amount of time, they will be dropped from the server.
func (state *GameState) playerPing() {
state.Players[state.clientPlayer].lastPing = time.Now()
}
// Performs the requested move for the active player, and returns true if successful
func (state *GameState) performMove(move string, internalCall ...bool) bool {
if len(internalCall) == 0 || !internalCall[0] {
state.playerPing()
}
// Get pointer to player
player := &state.Players[state.ActivePlayer]
// Sanity check if player is still in the game. Unless there is a bug, they should never be active if their status is != PLAYING
if player.Status != STATUS_PLAYING {
return false
}
// Only perform move if it is a valid move for this player
if !slices.ContainsFunc(state.getValidMoves(), func(m validMove) bool { return m.Move == move }) {
return false
}
if move == "FO" { // FOLD
player.Status = STATUS_FOLDED
} else if move != "CH" { // Not Checking
// Default raise to 0 (effectively a CALL)
raise := 0
if move == "RA" {
raise = state.raiseAmount
state.raiseCount++
} else if move == "BH" {
raise = HIGH
state.raiseAmount = HIGH
} else if move == "BL" {
raise = LOW
state.raiseAmount = LOW
// If betting LOW the very first time and the pot is BRINGIN
// just make their bet enough to make the total bet LOW
if state.currentBet == BRINGIN {
raise -= BRINGIN
}
} else if move == "BB" {
raise = BRINGIN
}
// Place the bet
delta := state.currentBet + raise - player.Bet
state.currentBet += raise
player.Bet += delta
player.Purse -= delta
}
player.Move = moveLookup[move]
state.nextValidPlayer()
return true
}
func (state *GameState) resetPlayerTimer(newRound bool) {
timeLimit := PLAYER_TIME_LIMIT
if state.Players[state.ActivePlayer].isBot {
timeLimit = BOT_TIME_LIMIT
}
if newRound {
timeLimit += NEW_ROUND_FIRST_PLAYER_BUFFER
}
state.moveExpires = time.Now().Add(timeLimit)
}
func (state *GameState) nextValidPlayer() {
// Move to next player
state.ActivePlayer = (state.ActivePlayer + 1) % len(state.Players)
// Skip over player if not in this game (joined late / folded)
for state.Players[state.ActivePlayer].Status != STATUS_PLAYING {
state.ActivePlayer = (state.ActivePlayer + 1) % len(state.Players)
}
state.resetPlayerTimer(false)
}
func (state *GameState) getValidMoves() []validMove {
moves := []validMove{}
// Any player after the bring-in player may fold
if state.currentBet > 0 || state.Round > 1 {
moves = append(moves, validMove{Move: "FO", Name: "Fold"})
}
player := state.Players[state.ActivePlayer]
// First check options if there is no BET yet (a BRINGIN is not considered a BET)
if state.currentBet < LOW {
// If nothing has been bet, force BET BRINGIN (2) on round 1
// otherwise a CHECK.
// If there is a bet, allow for a CALL
if state.currentBet == 0 {
if state.Round == 1 {
moves = append(moves, validMove{Move: "BB", Name: fmt.Sprint("Post ", BRINGIN)})
} else {
moves = append(moves, validMove{Move: "CH", Name: "Check"})
}
} else if player.Purse >= state.currentBet-player.Bet {
moves = append(moves, validMove{Move: "CA", Name: "Call"})
}
// Allow LOW bet on 2nd and 3rd street
if player.Purse >= LOW && state.Round < 3 {
moves = append(moves, validMove{Move: "BL", Name: fmt.Sprint("Bet ", LOW)})
}
// Allow HIGH bet if on 4th or 5th street, or 3rd street + pair showing
if player.Purse >= HIGH && (state.Round >= 3 ||
(state.Round == 2 && slices.IndexFunc(state.Players, func(p Player) bool {
return p.Status == STATUS_PLAYING && p.cards[1].value == p.cards[2].value
}) >= 0)) {
moves = append(moves, validMove{Move: "BH", Name: fmt.Sprint("Bet ", HIGH)})
}
} else {
// A bet as already been made. Allow a call
if player.Purse >= state.currentBet-player.Bet {
moves = append(moves, validMove{Move: "CA", Name: "Call"})
}
// Allow a raise if max number of rounds for the round has not been met
if state.Players[state.ActivePlayer].Purse >= state.currentBet-player.Bet+state.raiseAmount && state.raiseCount < 3 {
moves = append(moves, validMove{Move: "RA", Name: fmt.Sprint("Raise ", state.raiseAmount)})
}
}
return moves
}
// Creates a copy of the state and modifies it to be from the
// perspective of this client (e.g. player array, visible cards)
func (state *GameState) createClientState() *GameState {
stateCopy := *state
setActivePlayer := false
// Check if:
// 1. The game is over,
// 2. Only one player is left (waiting for another player to join)
// 3. We are at the end of a round, where the active player has moved
// This lets the client perform end of round/game tasks/animation
if state.gameOver ||
len(stateCopy.Players) < 2 ||
(stateCopy.ActivePlayer > -1 && ((state.currentBet > 0 && state.Players[state.ActivePlayer].Bet == state.currentBet) ||
(state.currentBet == 0 && state.Players[state.ActivePlayer].Move != ""))) {
stateCopy.ActivePlayer = -1
setActivePlayer = true
}
// Now, store a copy of state players, then loop
// through and add to the state copy, starting
// with this player first
statePlayers := stateCopy.Players
stateCopy.Players = []Player{}
// When on observer is viewing the game, the clientPlayer will be -1, so just start at 0
// Also, set flag to let client know they are not actively part of the game
start := state.clientPlayer
if start < 0 {
start = 0
stateCopy.Viewing = 1
} else {
stateCopy.Viewing = 0
}
// Loop through each player and create the hand, starting at this player, so all clients see the same order regardless of starting player
for i := start; i < start+len(statePlayers); i++ {
// Wrap around to beginning of playar array when needed
playerIndex := i % len(statePlayers)
// Update the ActivePlayer to be client relative
if !setActivePlayer && playerIndex == stateCopy.ActivePlayer {
setActivePlayer = true
stateCopy.ActivePlayer = i - start
}
player := statePlayers[playerIndex]
player.Hand = ""
switch player.Status {
case STATUS_PLAYING:
// Loop through and build hand string, taking
// care to not disclose the first card of a hand to other players
for cardIndex, card := range player.cards {
if cardIndex > 0 || playerIndex == state.clientPlayer || (state.Round == 5 && !state.wonByFolds) {
player.Hand += valueLookup[card.value] + suitLookup[card.suit]
} else {
player.Hand += "??"
}
}
case STATUS_FOLDED:
player.Hand = "??"
}
// Add this player to the copy of the state going out
stateCopy.Players = append(stateCopy.Players, player)
}
// Determine valid moves for this player (if their turn)
if stateCopy.ActivePlayer == 0 {
stateCopy.ValidMoves = state.getValidMoves()
}
// Determine the move time left. Reduce the number by the grace period, to allow for plenty of time for a response to be sent back and accepted
stateCopy.MoveTime = int(time.Until(stateCopy.moveExpires).Seconds())
if stateCopy.ActivePlayer > -1 {
stateCopy.MoveTime -= MOVE_TIME_GRACE_SECONDS
}
// No need to send move time if the calling player isn't the active player
if stateCopy.MoveTime < 0 || stateCopy.ActivePlayer != 0 {
stateCopy.MoveTime = 0
}
// Compute hash - this will be compared with an incoming hash. If the same, the entire state does not
// need to be sent back. This speeds up checks for change in state
stateCopy.hash = "0"
hash, _ := hashstructure.Hash(stateCopy, hashstructure.FormatV2, nil)
stateCopy.hash = fmt.Sprintf("%d", hash)
return &stateCopy
}
func (state *GameState) updateLobby() {
if !state.registerLobby {
return
}
humanPlayerSlots, humanPlayerCount := state.getHumanPlayerCountInfo()
// Send the total human slots / players to the Lobby
sendStateToLobby(humanPlayerSlots, humanPlayerCount, true, state.serverName, "?table="+state.table)
}
// Return number of active human players in the table, for the lobby
func (state *GameState) getHumanPlayerCountInfo() (int, int) {
humanAvailSlots := 8
humanPlayerCount := 0
cutoff := time.Now().Add(PLAYER_PING_TIMEOUT)
for _, player := range state.Players {
if player.isBot {
humanAvailSlots--
} else if player.Status != STATUS_LEFT && player.lastPing.Compare(cutoff) > 0 {
humanPlayerCount++
}
}
return humanAvailSlots, humanPlayerCount
}
// Ranks hand as an array of large to small values representing sets of 4 or less. Intended for 4 visible cards or simple AI
func getRank(cards []card) []int {
rank := []int{}
rankSuit := []int{}
sets := map[int]int{}
// Loop through hand once to create sets (cards of the same value)
for i := 0; i < len(cards); i++ {
sets[cards[i].value]++
}
// Loop through a second time to add the rank of each set (or single card)
for i := 0; i < len(cards); i++ {
val := cards[i].value
set := sets[val]
// Ranking highest value the lowest so ascending sort can be used
rank = append(rank, 100*(5-set)-val)
// Ranking with suit as a tie breaker
rankSuit = append(rankSuit, 100*(5-set)-(val*4+cards[i].suit))
}
sort.Ints(rank)
// Fill out empty 999s to make a 4 length to avoid bounds checks
for len(rank) < 4 {
rank = append(rank, 999)
}
sort.Ints(rankSuit)
rank = append(rank, rankSuit...)
for len(rank) < 8 {
rank = append(rank, 999)
}
return rank
}