-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
721 lines (637 loc) · 16.8 KB
/
main.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
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
)
var debugMode bool = false
type Char byte
type CommunityCards struct {
Cards []Card
}
// Tells you the status of the game
func (t *CommunityCards) status() int {
switch len(t.Cards) {
case 0: // pre-flop
return 0
case 3: //flop
return 1
case 4: // turn
return 2
case 5: // river
return 3
default:
panic("There is an unexpected number of cards on the table")
}
}
type Combinations struct {
StraightFlush int8
Poker int8
FullHouse int8
Flush int8
Straight int8
Trips int8
TwoPairs int8
OnePair int8
HighCard int8
}
type Card struct {
Number int8
Suit Char
}
type PlayerCombination struct {
CombinationID int8
Data []int8
Kickers []Card
}
// Formats the players hand
func (combo PlayerCombination) print() string {
if len(combo.Kickers) == 0 {
return fmt.Sprintf("%v with cards %v\n", getCombinationName(combo.CombinationID), combo.Data)
}
return fmt.Sprintf("%v with cards %v and with kickers %v\n", getCombinationName(combo.CombinationID), combo.Data, combo.Kickers)
}
// ByNumber Type used for sorting a group of cards by the face numbers (From 2 to the Ace).
type ByNumber []Card
// Len Sort interface
func (a ByNumber) Len() int {
return len(a)
}
// Less Sort interface
func (a ByNumber) Less(i, j int) bool {
// Ace is 1, so first check that.
if a[i].Number == 1 {
return false
} else if a[j].Number == 1 {
return true
}
// If there are no aces involved, do a simple comparison.
return int(a[i].Number) < int(a[j].Number)
}
// Swap Sort interface
func (a ByNumber) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
type Hand struct {
Cards [2]Card
}
type Game struct {
Table CommunityCards
Hands []Hand
Deck []Card
}
func (s Char) String() string {
return fmt.Sprintf("%c", s)
}
func getAllNumbers(doubleAce bool) []int8 {
cards := []int8{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
}
if doubleAce {
cards = append(cards, 14)
}
return cards
}
func getAllSuits() []Char {
return []Char{
'H', 'D', 'C', 'S',
}
}
// Creates a 52 cards deck
func createDeck() []Card {
var deck []Card
for _, s := range getAllSuits() {
for _, n := range getAllNumbers(false) {
deck = append(deck, Card{n, s})
}
}
return deck
}
// Removes one card from the passed deck of cards
func removeCardFromSlice(s *[]Card, i int) {
(*s)[i] = (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
}
// Takes the 2 player cards out of the deck
func addHandToTable(hand Hand, deck *[]Card, hands *[]Hand) {
*hands = append(*hands, hand)
for _, card := range hand.Cards {
addCardToTable(card, deck)
}
}
func addCardToTable(card Card, deck *[]Card) {
for i, deck_card := range *deck {
if card == deck_card {
removeCardFromSlice(deck, i)
}
}
}
// Extracts n amount of cards from the deck
func getRandomCardsFromDeck(deck *[]Card, nr int) []Card {
var cards []Card
for i := 0; i < nr; i++ {
deckLen := len(*deck)
pick := rand.Intn(deckLen)
crd := (*deck)[pick]
removeCardFromSlice(deck, pick)
cards = append(cards, crd)
}
return cards
}
// Gets a human-readable combination name
func getCombinationName(input int8) string {
combos := getCombinations()
mapping := map[int8]string{
combos.StraightFlush: "Straight Flush",
combos.Poker: "Poker",
combos.FullHouse: "Full House",
combos.Flush: "Flush",
combos.Straight: "Straight",
combos.Trips: "Trips",
combos.TwoPairs: "Two Pairs",
combos.OnePair: "One Pair",
combos.HighCard: "High Card",
}
return mapping[input]
}
func getCombinations() Combinations {
return Combinations{
StraightFlush: 1,
Poker: 2,
FullHouse: 3,
Flush: 4,
Straight: 5,
Trips: 6,
TwoPairs: 7,
OnePair: 8,
HighCard: 9,
}
}
// Checks if the deck has duplicate cards
func checkDeckHealth(deck []Card) {
store := make(map[Card]int)
for _, crd := range deck {
store[crd]++
if store[crd] > 1 {
panic("Deck has duplicate cards")
}
}
}
// Tells you how many community cards we still need to pull from deck
func getStatusMap() map[int]int {
mapping := make(map[int]int)
mapping[0] = 5
mapping[1] = 2
mapping[2] = 1
mapping[3] = 0
return mapping
}
// find 2, 3, or 4 of the same numbers on a slice of cards
func findMultipleSameNumbers(cards []Card, nr int) (map[int8]int8, bool) {
store := make(map[int8]int8)
for _, card := range cards {
store[card.Number]++
}
for i, count := range store {
if count != int8(nr) {
delete(store, i)
}
}
found := false
if len(store) > 0 {
found = true
}
return store, found
}
// Check if [nr] cards with the same value are in the input slice
func checkMultiples(cards []Card, nr int, kickerNr int) (int8, []Card) {
var kickers []Card
values, found := findMultipleSameNumbers(cards, nr)
if !found {
return 0, kickers
}
// Only keep the highest pair
var max int8 = 0
for i, _ := range values {
if (i > max && max != 1) || i == 1 {
max = i
}
}
// Return kickers
for _, c := range cards {
if c.Number != max {
kickers = append(kickers, c)
}
}
// Order kickers descending
sort.Sort(sort.Reverse(ByNumber(kickers)))
// Return the leftover cards
kickers = kickers[:kickerNr]
return max, kickers
}
// Tries to find two pairs
func checkTwoPairs(cards []Card) ([]int8, []Card) {
kickerNr := len(cards) - 2
twoPairs := []int8{}
found, kickers := checkMultiples(cards, 2, kickerNr)
if found == 0 {
return twoPairs, kickers
}
secondFound, kickers := checkMultiples(kickers, 2, 1)
if secondFound == 0 {
return twoPairs, kickers
}
twoPairs = append(twoPairs, found, secondFound)
return twoPairs, kickers
}
func checkOnePair(cards []Card) (int8, []Card) {
result, kickers := checkMultiples(cards, 2, 3)
return result, kickers
}
func checkTrips(cards []Card) (int8, []Card) {
result, kickers := checkMultiples(cards, 3, 2)
return result, kickers
}
func checkPoker(cards []Card) (int8, []Card) {
result, kickers := checkMultiples(cards, 4, 1)
return result, kickers
}
func checkStraight(cards []Card) int8 {
store := make(map[int8]int8)
for _, card := range cards {
store[card.Number]++
if card.Number == 1 { // An ace also counts as last card
store[int8(14)]++
}
}
var consecutive, found int8 = 0, 0
for _, nr := range getAllNumbers(true) {
if _, ok := store[nr]; ok {
consecutive++
if consecutive >= 5 {
found = nr
}
} else {
consecutive = 0
}
}
return found
}
func checkFullHouse(cards []Card) []int8 {
trips, kickers := checkTrips(cards)
if trips > 0 {
pair, _ := checkMultiples(kickers, 2, 0)
if pair > 0 {
return []int8{trips, pair}
}
}
return []int8{}
}
func checkStraightFlush(cards []Card) int8 {
highValue := checkStraight(cards)
if highValue == 0 {
return 0
}
// Keep only cards which are in the straight range
var keepCards []Card
for i := 6; i >= 0; i-- {
card := cards[i]
if (card.Number >= (highValue-4) && card.Number <= highValue) || (highValue == 14 && card.Number == 1) {
keepCards = append(keepCards, card)
}
}
foundFlush := checkFlush(keepCards)
if len(foundFlush) > 1 {
return highValue
}
return 0
}
func checkFlush(cards []Card) []int8 {
store := make(map[Char][]int8)
for _, card := range cards {
store[card.Suit] = append(store[card.Suit], card.Number)
}
var found []int8
for i, item := range store {
if len(item) >= 5 {
for _, nr := range store[i] {
found = append(found, nr)
}
}
}
if len(found) == 0 {
var emptyResult []int8
return emptyResult
}
// Sort ascending, but take into account the ace
sort.Slice(found, func(i, j int) bool {
return (found[i] < found[j] && found[i] > 1)
})
// Keep only the 5 highest ones
found = found[len(found)-5:]
return found
}
type Outcome struct {
Win int
Tie int
Lose int
}
func getOutcomes() Outcome {
return Outcome{1, 2, 3}
}
func greaterEqualOrLower(c1 int8, c2 int8) int {
outcomes := getOutcomes()
if c1 == c2 {
return outcomes.Tie // equal
} else if c1 == 1 {
return outcomes.Win // greater
} else if c2 == 1 {
return outcomes.Lose // greater
} else if c1 > c2 {
return outcomes.Win // greater
}
return outcomes.Lose // lower
}
// Values coming into this function should already be sorted by strength
func numberCompare(k1, k2 []int8) int {
outcomes := getOutcomes()
if len(k1) != len(k2) {
panic("Kicker length should be the same")
}
for i, _ := range k1 {
result := greaterEqualOrLower(k1[i], k2[i])
if result != outcomes.Tie {
return result
}
}
return outcomes.Tie
}
func kickerCompare(k1, k2 []Card) int {
var k1n, k2n []int8
for _, v := range k1 {
k1n = append(k1n, v.Number)
}
for _, v := range k2 {
k2n = append(k2n, v.Number)
}
return numberCompare(k1n, k2n)
}
// Registers a players best hand and determines if it beats the previous best
func registerPlayerHand(id int, candidate PlayerCombination, lastBest *PlayerCombination, winners *int) {
if debugMode {
fmt.Printf("Player %v has: %v", id, candidate.print())
}
// If there is not previous hand, this hand wins automatically
// If this hand has the better combinations, it wins
if (*lastBest).CombinationID == 0 || candidate.CombinationID < (*lastBest).CombinationID {
// clear win for the candidate
*lastBest = candidate
*winners = id
return
} else if candidate.CombinationID > (*lastBest).CombinationID {
// Loss for the candidate
return
}
// From here down, the previous best and the candidate have the best combination
// We need to compare in more detail
outcomes := getOutcomes()
var outcome int
combos := getCombinations()
switch candidate.CombinationID {
case combos.StraightFlush, combos.Straight, combos.FullHouse, combos.Flush:
outcome = numberCompare(candidate.Data, (*lastBest).Data)
case combos.Poker, combos.Trips, combos.TwoPairs, combos.OnePair:
outcome = numberCompare(candidate.Data, (*lastBest).Data)
if outcome == outcomes.Tie {
outcome = kickerCompare(candidate.Kickers, (*lastBest).Kickers)
}
case combos.HighCard:
outcome = kickerCompare(candidate.Kickers, (*lastBest).Kickers)
default:
outcome = outcomes.Tie
}
if outcome == outcomes.Win {
// we have a clear winner
*winners = id
*lastBest = candidate
} else if outcome == outcomes.Tie {
// Of there is a tie, we don't have a current single winner
*winners = -1
} else if outcome == 0 {
panic("Outcome hasn't been asserted")
}
}
// Retrieves scenarios from the job queue and crunches them
func casinoWorker(results chan<- int, jobs <-chan Game) {
if debugMode {
fmt.Println("Starting worker")
}
combos := getCombinations()
// Retrieve a single job (= one game)
for work := range jobs {
communityCards := work.Table.Cards
tableStatus := work.Table.status()
mapping := getStatusMap()
deck := work.Deck
cardsLeftToPull := mapping[tableStatus]
cardsPulled := getRandomCardsFromDeck(&deck, cardsLeftToPull)
communityCards = append(communityCards, cardsPulled...)
lastBest := PlayerCombination{}
var weHaveAWinner int = -1
// Calculate the best combination each player holds
for playerIndex, hand := range work.Hands {
var playerCardPool []Card = communityCards
playerCardPool = append(playerCardPool, hand.Cards[:]...)
var foundInt int8
var foundSlice []int8
var kickers []Card
if len(playerCardPool) != 7 {
panic("Player should have 7 cards available in total")
}
checkDeckHealth(append(deck, communityCards...))
// The best hand rank returns the lower value
foundInt = checkStraightFlush(playerCardPool)
if foundInt > 0 {
combo := PlayerCombination{combos.StraightFlush, []int8{foundInt}, kickers}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundInt, kickers = checkPoker(playerCardPool)
if foundInt > 0 {
combo := PlayerCombination{combos.Poker, []int8{foundInt}, kickers}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundSlice = checkFullHouse(playerCardPool)
if len(foundSlice) > 0 {
combo := PlayerCombination{combos.FullHouse, foundSlice, []Card{}}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundSlice = checkFlush(playerCardPool)
if len(foundSlice) > 0 {
combo := PlayerCombination{combos.Flush, foundSlice, []Card{}}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundInt = checkStraight(playerCardPool)
if foundInt > 0 {
combo := PlayerCombination{combos.Straight, []int8{foundInt}, []Card{}}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundInt, kickers = checkTrips(playerCardPool)
if foundInt > 0 {
combo := PlayerCombination{combos.Trips, []int8{foundInt}, kickers}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundSlice, kickers = checkTwoPairs(playerCardPool)
if len(foundSlice) == 2 {
combo := PlayerCombination{combos.TwoPairs, foundSlice, kickers}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
foundInt, kickers = checkOnePair(playerCardPool)
if foundInt > 0 {
combo := PlayerCombination{combos.OnePair, []int8{foundInt}, kickers}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
continue
}
sort.Sort(sort.Reverse(ByNumber(playerCardPool)))
playerCardPool = playerCardPool[:5]
combo := PlayerCombination{combos.HighCard, []int8{}, playerCardPool}
registerPlayerHand(playerIndex, combo, &lastBest, &weHaveAWinner)
}
if debugMode {
if weHaveAWinner >= 0 {
fmt.Printf("Player %v wins\n\n", weHaveAWinner)
} else {
fmt.Println("No winner")
}
}
results <- weHaveAWinner
}
if debugMode {
fmt.Println("Worker done")
}
}
func main() {
deck := createDeck()
var hands []Hand
reader := bufio.NewReader(os.Stdin)
fmt.Println("\nWelcome!\n ")
fmt.Println("Please enter the players hands, one hand line")
fmt.Println("Ace=1, Jack=11, Queen=12, King=13")
fmt.Println("Example: 7H 11S")
fmt.Println("Press enter after you entered the last player")
fmt.Println("\n ")
playerNr := 0
for {
fmt.Printf("Player %v -> ", playerNr)
text, _ := reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
// Break when a blank enter is pressed
if strings.Compare("", text) == 0 {
break
}
spacePos := strings.Index(text, " ")
positions := []int{spacePos, len(text)}
hand := Hand{}
// Loop the two cards
for i, pos := range positions {
startI := 0
if i == 1{
startI = spacePos+1
}
numberInt, _ := strconv.Atoi(text[startI:pos-1])
hand.Cards[i].Number = int8(numberInt)
oba := []byte(text[pos-1:pos])
hand.Cards[i].Suit = Char(oba[0])
}
addHandToTable(hand, &deck, &hands)
playerNr++
}
table := CommunityCards{
[]Card{},
}
fmt.Println("\nEnter the community cards on the table")
fmt.Println("Flop Example: 13S 7S 1H")
fmt.Println("Press enter if it's preflop\n ")
fmt.Print("Table -> ")
tableInput, _ := reader.ReadString('\n')
tableInput = strings.Replace(tableInput, "\n", "", -1) + " "
cardPositions := []int{0}
for i, ch := range tableInput {
if strings.Compare(" ", string(ch)) == 0 {
cardPositions = append(cardPositions, i+1)
}
}
for i, pos := range cardPositions[:len(cardPositions)-1] {
nextPos := cardPositions[i+1]
if (nextPos - pos) <= 1 {
break
}
numberInt, _ := strconv.Atoi(tableInput[pos:nextPos-2])
oba := []byte(tableInput[nextPos-2:nextPos-1])
crd := Card{
Number: int8(numberInt),
Suit: Char(oba[0]),
}
table.Cards = append(table.Cards, crd)
addCardToTable(crd, &deck)
}
var workers, simulations int
for workers == 0 {
fmt.Print("\nNumber of goroutines to use: ")
fmt.Scanf("%d", &workers)
}
for simulations == 0 {
fmt.Print("Number of simulated games to run: ")
fmt.Scanf("%d", &simulations)
}
start := time.Now()
resultsChannel := make(chan int, simulations)
jobsChannel := make(chan Game, simulations)
for i := 0; i < workers; i++ {
go casinoWorker(resultsChannel, jobsChannel)
}
for i := 0; i < simulations; i++ {
// Make a new deck slice for each worker
deckDestination := make([]Card, len(deck))
copy(deckDestination, deck)
setting := Game{
Table: table,
Hands: hands,
Deck: deckDestination,
}
jobsChannel <- setting
}
close(jobsChannel)
results := make(map[int]int)
winCount := 0
for i := 0; i < simulations; i++ {
winner := <-resultsChannel
if winner >= 0 {
results[winner]++
winCount++
}
}
fmt.Println("\n-------\n ")
simulationsF := float64(simulations)
for i:=0; i<len(hands); i++ {
wins := results[i]
winProbability := float64(wins) / simulationsF * 100
fmt.Printf("Player ID %v win probability: %f%% \n", i, winProbability)
}
splitProbability := (simulationsF - float64(winCount)) / simulationsF * 100
fmt.Printf("Split probability: %f%% \n\n", splitProbability)
elapsed := time.Since(start)
log.Printf("Program took %s", elapsed)
}