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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
use std::collections::{HashMap, HashSet};
use serde::{Serialize, Deserialize};
use crate::action::Action;
use crate::card::Card;
use crate::deck::Deck;
use crate::player::Player;
use crate::rules::{GameRules, GameVariant};
use crate::evaluation::{find_best_hand, find_best_omaha_hand, HandEvaluation};
/// Result of multiple runs of the remaining cards
#[derive(Debug, Clone)]
pub struct MultiRunResult {
pub runs: Vec<RunResult>,
pub win_counts: HashMap<usize, u32>, // Player ID -> number of runs won
}
/// Result of a single run
#[derive(Debug, Clone)]
pub struct RunResult {
pub community_cards: Vec<Card>,
pub winning_player_indices: Vec<usize>,
pub winning_hands: HashMap<usize, Vec<Card>>, // Player ID -> best hand
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum GameStage {
Preflop,
Flop,
Turn,
River,
Showdown,
}
/// Snapshot of a game's state that can be serialized and stored
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GameSnapshot {
pub rules: GameRules,
pub players: Vec<PlayerSnapshot>,
pub community_cards: Vec<Card>,
pub pot: u32,
pub current_bet: u32,
pub dealer_position: usize,
pub current_position: usize,
pub stage: GameStage,
pub side_pots: Vec<(u32, Vec<usize>)>,
pub deck_state: Vec<Card>, // Current state of the deck
}
/// Snapshot of a player's state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlayerSnapshot {
pub id: usize,
pub name: String,
pub chips: u32,
pub seat_position: usize,
pub hand: Vec<Card>,
pub is_dealer: bool,
pub is_folded: bool,
pub is_all_in: bool,
pub bet_amount: u32,
}
#[derive(Debug)]
pub struct Game {
pub rules: GameRules,
pub deck: Deck,
pub players: Vec<Player>,
pub occupied_seats: HashSet<usize>, // Track which seats are taken
pub community_cards: Vec<Card>,
pub pot: u32,
pub current_bet: u32,
pub dealer_position: usize,
pub current_position: usize,
pub stage: GameStage,
pub active_player_count: usize,
pub side_pots: Vec<(u32, Vec<usize>)>, // (amount, eligible player indices)
pub multi_run_results: Option<MultiRunResult>, // Results when running it multiple times
pub players_acted: HashSet<usize>, // Track which players have acted in the current betting round
}
impl Game {
pub fn new(rules: GameRules) -> Self {
Self {
rules,
deck: Deck::new(),
players: Vec::new(),
occupied_seats: HashSet::new(),
community_cards: Vec::new(),
pot: 0,
current_bet: 0,
dealer_position: 0,
current_position: 0,
stage: GameStage::Preflop,
active_player_count: 0,
side_pots: Vec::new(),
multi_run_results: None,
players_acted: HashSet::new(),
}
}
/// Add a player to a specific seat
pub fn add_player_to_seat(&mut self, name: String, chips: u32, seat: usize) -> Result<usize, &'static str> {
if self.players.len() >= self.rules.max_players {
return Err("Maximum player count reached");
}
if seat >= self.rules.max_players {
return Err("Invalid seat number");
}
if self.occupied_seats.contains(&seat) {
return Err("Seat already taken");
}
let player_id = self.players.len();
let player = Player::new(player_id, name, chips, seat);
self.players.push(player);
self.occupied_seats.insert(seat);
Ok(player_id)
}
/// Add a player to the first available seat (for backward compatibility)
pub fn add_player(&mut self, name: String, chips: u32) -> Result<usize, &'static str> {
if self.players.len() >= self.rules.max_players {
return Err("Maximum player count reached");
}
// Find the first available seat
let available_seat = (0..self.rules.max_players)
.find(|&seat| !self.occupied_seats.contains(&seat))
.ok_or("No available seats")?;
self.add_player_to_seat(name, chips, available_seat)
}
/// Get list of available seats
pub fn get_available_seats(&self) -> Vec<usize> {
(0..self.rules.max_players)
.filter(|seat| !self.occupied_seats.contains(seat))
.collect()
}
/// Remove a player by ID
pub fn remove_player(&mut self, player_id: usize) -> Result<(), &'static str> {
let player_idx = self.players.iter().position(|p| p.id == player_id)
.ok_or("Player not found")?;
let seat = self.players[player_idx].seat_position;
self.occupied_seats.remove(&seat);
self.players.remove(player_idx);
Ok(())
}
pub fn start_hand(&mut self) -> Result<(), &'static str> {
if self.players.len() < self.rules.min_players {
return Err("Not enough players to start a hand");
}
// Sort players by seat position for dealing cards properly
self.players.sort_by_key(|player| player.seat_position);
// Reset game state
self.deck = Deck::new();
self.deck.shuffle();
self.community_cards.clear();
self.pot = 0;
self.current_bet = 0;
self.stage = GameStage::Preflop;
self.side_pots.clear();
self.players_acted.clear(); // Clear the players who have acted
// Reset players for new hand
for player in &mut self.players {
player.reset_for_new_hand();
}
// Count active players (those with chips)
self.active_player_count = self.players.iter().filter(|p| p.chips > 0).count();
// Move dealer button
self.dealer_position = (self.dealer_position + 1) % self.players.len();
self.players[self.dealer_position].is_dealer = true;
// Deal cards to players (specific to game variant)
self.deal_hole_cards();
// Post blinds
self.post_blinds()?;
// Set starting position (typically UTG - first player after big blind)
self.current_position = (self.get_big_blind_position() + 1) % self.players.len();
Ok(())
}
fn deal_hole_cards(&mut self) {
let num_cards = self.rules.hole_cards;
// Deal cards to each player in turn (poker dealing convention)
for _ in 0..num_cards {
for player_idx in 0..self.players.len() {
// Start dealing from player after the dealer
let pos = (self.dealer_position + 1 + player_idx) % self.players.len();
if let Some(card) = self.deck.deal() {
self.players[pos].receive_card(card);
}
}
}
}
fn post_blinds(&mut self) -> Result<(), &'static str> {
// Post small blind
let sb_pos = self.get_small_blind_position();
let sb_amount = self.rules.small_blind.min(self.players[sb_pos].chips);
if sb_amount > 0 {
let amount = self.players[sb_pos].bet(sb_amount);
self.pot += amount;
self.current_bet = amount;
}
// Post big blind
let bb_pos = self.get_big_blind_position();
let bb_amount = self.rules.big_blind.min(self.players[bb_pos].chips);
if bb_amount > 0 {
let amount = self.players[bb_pos].bet(bb_amount);
self.pot += amount;
self.current_bet = amount;
}
// Post antes if required
if self.rules.ante > 0 {
for player in &mut self.players {
if player.chips > 0 {
let ante = self.rules.ante.min(player.chips);
let amount = player.bet(ante);
self.pot += amount;
}
}
}
Ok(())
}
fn get_small_blind_position(&self) -> usize {
// In heads-up play (2 players), dealer posts small blind
if self.players.len() == 2 {
return self.dealer_position;
}
// In normal play, small blind is to the left of dealer
(self.dealer_position + 1) % self.players.len()
}
fn get_big_blind_position(&self) -> usize {
// Big blind is typically to the left of small blind
(self.get_small_blind_position() + 1) % self.players.len()
}
pub fn next_street(&mut self) -> Result<GameStage, &'static str> {
// Update betting rounds and deal community cards
match self.stage {
GameStage::Preflop => {
// Deal the flop
if let (Some(card1), Some(card2), Some(card3)) = (
self.deck.deal(),
self.deck.deal(),
self.deck.deal()
) {
self.community_cards.push(card1);
self.community_cards.push(card2);
self.community_cards.push(card3);
self.stage = GameStage::Flop;
self.reset_betting_round();
} else {
return Err("Not enough cards in deck");
}
},
GameStage::Flop => {
// Deal the turn
if let Some(card) = self.deck.deal() {
self.community_cards.push(card);
self.stage = GameStage::Turn;
self.reset_betting_round();
} else {
return Err("Not enough cards in deck");
}
},
GameStage::Turn => {
// Deal the river
if let Some(card) = self.deck.deal() {
self.community_cards.push(card);
self.stage = GameStage::River;
}
// Move to showdown after dealing river
self.stage = GameStage::Showdown;
},
GameStage::River => {
// Move to showdown
self.stage = GameStage::Showdown;
self.evaluate_winner();
},
GameStage::Showdown => {
return Err("Hand is already at showdown");
}
}
Ok(self.stage)
}
fn reset_betting_round(&mut self) {
// Reset bet-related state for a new betting round
self.current_bet = 0;
for player in &mut self.players {
player.bet_amount = 0;
}
// Clear the set of players who have acted
self.players_acted.clear();
// Set starting position (first active player after dealer)
let mut pos = (self.dealer_position + 1) % self.players.len();
while self.players[pos].is_folded || self.players[pos].is_all_in || self.players[pos].chips == 0 {
pos = (pos + 1) % self.players.len();
// If we've gone full circle, there's not enough players for a betting round
if pos == self.dealer_position + 1 {
break;
}
}
self.current_position = pos;
}
pub fn is_round_complete(&self) -> bool {
// Check if all active players have had a chance to act and
// all active players have matched the current bet or folded
// If only one player is left, the round is complete
if self.active_player_count <= 1 {
return true;
}
// If all players are all-in, the round is complete
if self.players.iter().all(|p| p.is_folded || p.is_all_in || p.chips == 0) {
return true;
}
// Check if all-in showdown condition: at most one player not all-in
// Count non-folded and non-all-in players
let active_not_all_in = self.players.iter()
.filter(|p| !p.is_folded && !p.is_all_in && p.chips > 0)
.count();
// If there's at most one player not all-in, and all bets are matched, round is complete
if active_not_all_in <= 1 {
let current_bet = self.current_bet;
let all_matched = self.players.iter()
.filter(|p| !p.is_folded && !p.is_all_in && p.chips > 0)
.all(|p| p.bet_amount == current_bet);
if all_matched {
return true;
}
}
// Get active players (not folded, not all-in, have chips)
let active_players: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded && !p.is_all_in && p.chips > 0)
.map(|(i, _)| i)
.collect();
// Check if all active players have acted
let all_active_acted = active_players.iter()
.all(|pos| self.players_acted.contains(pos));
// Check if all active players have matched the current bet
let all_bet_matched = active_players.iter()
.all(|pos| self.players[*pos].bet_amount == self.current_bet);
// The round is complete if everyone has acted and all bets are matched
all_active_acted && all_bet_matched
}
pub fn handle_action(&mut self, action: Action) -> Result<(), &'static str> {
// Get the current player's position
let current_position = self.current_position;
// Special case for all-in action - players can always bet all their chips
let is_all_in = if let Action::Bet(amount) = &action {
*amount == self.players[current_position].chips && *amount > 0
} else {
false
};
// Handle fold or check/call/raise
match action {
Action::Fold => {
if self.players[current_position].is_folded || self.players[current_position].is_all_in {
return Err("Player cannot fold");
}
self.players[current_position].fold();
self.active_player_count -= 1;
// Check if only one player remains (immediately after fold)
if self.active_player_count == 1 {
// Find the last active player
let winner_idx = self.players.iter()
.enumerate()
.find(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.unwrap_or(0); // Default to 0 if none found (shouldn't happen)
// Award the pot to the last active player
self.players[winner_idx].collect_winnings(self.pot);
self.pot = 0;
self.stage = GameStage::Showdown;
return Ok(());
}
},
Action::Bet(bet_amount) => {
// Check basic constraints
let player = &self.players[current_position];
// Check if player can perform the action
if player.is_folded || player.is_all_in {
return Err("Player cannot bet");
}
// Checking - bet 0 when no bet to call
if bet_amount == 0 {
if player.bet_amount != self.current_bet {
return Err("Cannot check when there is a bet to call");
}
// Check is just a no-op
}
// All-in bet
else if is_all_in {
// Players can always go all-in, even if they can't match the current bet
let player = &mut self.players[current_position];
let amount = player.bet(bet_amount);
self.pot += amount;
}
// Regular bet/call/raise
else {
let current_player_bet = self.players[current_position].bet_amount;
// Validate raises
if current_player_bet + bet_amount > self.current_bet {
// This is a raise - validate based on betting structure
// In No Limit, minimum raise is BB or the previous raise amount
let _min_raise = self.rules.min_raise();
// If there's already been a bet and this is an increase
if self.current_bet > 0 {
// Special case: if responding to an all-in that's less than a min-raise,
// player can match the all-in without meeting min-raise requirements
// Check for all-in players before getting the mutable reference
let is_responding_to_allin = self.players.iter()
.any(|p| p.is_all_in && p.bet_amount == self.current_bet);
// Only require minimum raise in standard situations
if !is_responding_to_allin && !self.rules.is_valid_raise(
self.current_bet,
current_player_bet + bet_amount,
self.pot
) {
return Err("Invalid raise amount");
}
}
// In case of first bet, it must be at least the big blind
else if bet_amount < self.rules.big_blind {
return Err("Bet must be at least the big blind");
}
}
// Calling but not matching the current bet (unless all-in)
else if current_player_bet + bet_amount < self.current_bet {
return Err("Must call the current bet or go all-in");
}
// Now we can safely process the bet
let player = &mut self.players[current_position];
let amount = player.bet(bet_amount);
self.pot += amount;
}
// Update current bet if this bet is the highest now
let player_bet_amount = self.players[current_position].bet_amount;
if player_bet_amount > self.current_bet {
self.current_bet = player_bet_amount;
}
},
Action::Post(amount) => {
let posted = self.players[current_position].bet(amount);
self.pot += posted;
if self.players[current_position].bet_amount > self.current_bet {
self.current_bet = self.players[current_position].bet_amount;
}
}
}
// Mark the current player as having acted
self.players_acted.insert(current_position);
// Move to next player
self.next_player();
// Check if round is complete
if self.is_round_complete() {
if self.active_player_count <= 1 {
// Only one player left, go to showdown
self.stage = GameStage::Showdown;
self.evaluate_winner();
} else if self.stage != GameStage::Showdown {
// Create side pots if players are all-in
self.calculate_side_pots();
// Check if we're in an all-in situation and should proceed to showdown
let active_not_all_in = self.players.iter()
.filter(|p| !p.is_folded && !p.is_all_in && p.chips > 0)
.count();
if active_not_all_in <= 1 {
// At most one player not all-in, we should proceed to showdown
// Deal remaining cards based on current stage
while self.stage != GameStage::Showdown && self.stage != GameStage::River {
self.next_street().expect("Failed to deal next street");
}
if self.stage == GameStage::River {
self.stage = GameStage::Showdown;
self.evaluate_winner();
}
}
}
}
Ok(())
}
fn next_player(&mut self) {
// Find the next player who can act
let mut next_position = (self.current_position + 1) % self.players.len();
while self.players[next_position].is_folded ||
self.players[next_position].is_all_in ||
self.players[next_position].chips == 0 {
next_position = (next_position + 1) % self.players.len();
// If we've gone full circle, there's no more decisions to make
if next_position == self.current_position {
break;
}
}
self.current_position = next_position;
}
/// Calculate side pots for all-in players
pub fn calculate_side_pots(&mut self) {
// Create side pots for all-in players
let mut all_in_amounts: Vec<(usize, u32)> = self.players.iter()
.enumerate()
.filter(|(_, p)| p.is_all_in && !p.is_folded)
.map(|(i, p)| (i, p.bet_amount))
.collect();
if all_in_amounts.is_empty() {
return;
}
// Sort by bet amount (smallest first)
all_in_amounts.sort_by_key(|&(_, amount)| amount);
// Calculate side pots
self.side_pots.clear();
let mut prev_amount = 0;
let mut total_side_pot_amount = 0;
// For each all-in player, create a side pot
for (_, amount) in all_in_amounts {
let pot_contribution = amount - prev_amount;
// Who's eligible for this side pot?
let eligible: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded && p.bet_amount >= amount)
.map(|(i, _)| i)
.collect();
if eligible.len() > 1 {
// Calculate side pot: each player contributes (all-in amount - previous all-in amount)
let mut pot_size = 0;
for &player_idx in &eligible {
// Each eligible player contributes to this level
let player = &self.players[player_idx];
// Players who bet more contribute exactly the pot_contribution
if player.bet_amount >= amount {
pot_size += pot_contribution;
}
}
self.side_pots.push((pot_size, eligible));
total_side_pot_amount += pot_size;
}
prev_amount = amount;
}
// Calculate the main pot
let main_pot_eligible: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
// Only create main pot if we have more than one eligible player
if main_pot_eligible.len() > 1 {
// Main pot is total pot minus all side pots
// If there's money left for the main pot
if self.pot > total_side_pot_amount {
let main_pot = self.pot - total_side_pot_amount;
self.side_pots.push((main_pot, main_pot_eligible));
}
}
}
/// Evaluate winners and distribute pot
pub fn evaluate_winner(&mut self) {
// If only one player remains, they win the pot
let active_players: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
if active_players.len() == 1 {
let winner_idx = active_players[0];
self.players[winner_idx].collect_winnings(self.pot);
self.pot = 0; // Clear the pot after distribution
return;
}
// Evaluate hands for each active player
let mut player_hands: HashMap<usize, (Vec<Card>, HandEvaluation)> = HashMap::new();
for &player_idx in &active_players {
let player = &self.players[player_idx];
let hole_cards = player.hand.cards();
let (best_hand, evaluation) = match self.rules.variant {
GameVariant::TexasHoldem => {
// For NLHE, use standard 5-card evaluation
find_best_hand(hole_cards, &self.community_cards)
},
GameVariant::OmahaHoldem4 |
GameVariant::OmahaHoldem5 |
GameVariant::OmahaHoldem6 => {
// For all Omaha variants, player must use exactly 2 hole cards
// and 3 community cards
find_best_omaha_hand(hole_cards, &self.community_cards)
}
};
player_hands.insert(player_idx, (best_hand, evaluation));
}
// Determine winners for each pot
let initial_pot = self.pot; // Save the initial pot value
// Calculate side pots if they haven't been calculated yet
if self.side_pots.is_empty() {
self.calculate_side_pots();
}
if self.side_pots.is_empty() {
// No side pots, just evaluate the main pot
let main_pot_eligible: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
self.award_pot(self.pot, &main_pot_eligible, &player_hands);
} else {
// Award each side pot to its winners
// Clone the data to avoid borrowing issues
let side_pots = self.side_pots.clone();
for (pot_amount, eligible) in side_pots {
self.award_pot(pot_amount, &eligible, &player_hands);
}
}
// Reset pot to 0 after distribution
self.pot = 0;
// Clear side pots
self.side_pots.clear();
}
fn award_pot(
&mut self,
pot_amount: u32,
eligible: &[usize],
player_hands: &HashMap<usize, (Vec<Card>, HandEvaluation)>
) {
// Find the best hand among eligible players
let mut best_eval = None;
let mut winners = Vec::new();
for &player_idx in eligible {
if let Some((_, eval)) = player_hands.get(&player_idx) {
match best_eval {
None => {
best_eval = Some(eval);
winners = vec![player_idx];
},
Some(best) => {
match eval.cmp(best) {
std::cmp::Ordering::Greater => {
best_eval = Some(eval);
winners = vec![player_idx];
},
std::cmp::Ordering::Equal => {
winners.push(player_idx);
},
std::cmp::Ordering::Less => {
// Not a winner
}
}
}
}
}
}
// If no winners, return early
if winners.is_empty() {
return;
}
// Split pot among winners
let winner_count = winners.len() as u32;
let base_amount = pot_amount / winner_count;
let mut remainder = pot_amount % winner_count;
// Distribute base amount to each winner
for &winner_idx in &winners {
let mut amount = base_amount;
// Distribute leftover chips (1 chip per player, starting from earliest position)
if remainder > 0 {
amount += 1;
remainder -= 1;
}
self.players[winner_idx].collect_winnings(amount);
}
// If there's still a remainder (shouldn't happen), give it to the first winner
if remainder > 0 {
self.players[winners[0]].collect_winnings(remainder);
}
}
/// Run the board multiple times (2 or 3 times) from the current stage
/// Returns the winners for each run
pub fn run_multiple_times(&mut self, run_count: u32) -> Result<MultiRunResult, &'static str> {
if run_count < 2 || run_count > 3 {
return Err("Run count must be 2 or 3");
}
if self.stage == GameStage::Showdown {
return Err("Hand is already at showdown");
}
// Check if there are at least 2 active players
let active_players: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
if active_players.len() < 2 {
return Err("Not enough active players for multiple runs");
}
// Save original deck and community cards state
let original_deck = self.deck.clone();
let original_community_cards = self.community_cards.clone();
let current_stage = self.stage;
// Create result container
let mut multi_run = MultiRunResult {
runs: Vec::with_capacity(run_count as usize),
win_counts: HashMap::new(),
};
// Run the hand multiple times
for _run_index in 0..run_count {
// Reset deck and community cards to original state for each run
self.deck = original_deck.clone();
self.community_cards = original_community_cards.clone();
self.stage = current_stage;
// Shuffle the deck for a different outcome each run
self.deck.shuffle();
// Deal remaining streets until showdown
while self.stage != GameStage::Showdown {
match self.stage {
GameStage::Preflop => {
// Deal the flop
if let (Some(card1), Some(card2), Some(card3)) = (
self.deck.deal(),
self.deck.deal(),
self.deck.deal()
) {
self.community_cards.push(card1);
self.community_cards.push(card2);
self.community_cards.push(card3);
self.stage = GameStage::Flop;
}
},
GameStage::Flop => {
// Deal the turn
if let Some(card) = self.deck.deal() {
self.community_cards.push(card);
self.stage = GameStage::Turn;
}
},
GameStage::Turn => {
// Deal the river
if let Some(card) = self.deck.deal() {
self.community_cards.push(card);
self.stage = GameStage::River;
}
// Move to showdown after dealing river
self.stage = GameStage::Showdown;
},
_ => self.stage = GameStage::Showdown,
}
}
// Evaluate winners for this run (without updating chip stacks)
let (winners, winning_hands) = self.evaluate_winners_without_payout();
// Record win counts
for winner in &winners {
*multi_run.win_counts.entry(*winner).or_insert(0) += 1;
}
// Save the run result
multi_run.runs.push(RunResult {
community_cards: self.community_cards.clone(),
winning_player_indices: winners.clone(),
winning_hands,
});
}
// Restore original state
self.deck = original_deck;
self.community_cards = original_community_cards;
self.stage = current_stage;
// Save results for later reference
self.multi_run_results = Some(multi_run.clone());
Ok(multi_run)
}
/// Complete a hand with multiple runs, distributing the pot proportionally
pub fn complete_with_multiple_runs(&mut self, run_count: u32) -> Result<(), &'static str> {
// Run the hand multiple times
let multi_run = self.run_multiple_times(run_count)?;
// Calculate total pot size
let main_pot = self.pot;
// Calculate side pots if necessary
if self.side_pots.is_empty() {
self.calculate_side_pots();
}
if self.side_pots.is_empty() {
// No side pots, distribute the main pot
self.distribute_pot_by_win_percentage(main_pot, &multi_run.win_counts, run_count);
} else {
// Handle side pots
let side_pots = self.side_pots.clone();
for (pot_amount, eligible) in side_pots {
// Filter win counts to only include eligible players
let filtered_win_counts: HashMap<usize, u32> = multi_run.win_counts.iter()
.filter(|(&player_idx, _)| eligible.contains(&player_idx))
.map(|(&k, &v)| (k, v))
.collect();
self.distribute_pot_by_win_percentage(pot_amount, &filtered_win_counts, run_count);
}
}
// Move to showdown
self.stage = GameStage::Showdown;
Ok(())
}
/// Distribute pot based on win percentages from multiple runs
fn distribute_pot_by_win_percentage(&mut self, pot_amount: u32, win_counts: &HashMap<usize, u32>, run_count: u32) {
// No winners, pot remains
if win_counts.is_empty() {
return;
}
// Calculate pot portions
let total_wins: u32 = win_counts.values().sum();
// In case no one won (shouldn't happen), distribute evenly
if total_wins == 0 {
let player_count = win_counts.len() as u32;
let base_amount = pot_amount / player_count;
let mut leftover = pot_amount % player_count;
for &player_idx in win_counts.keys() {
let mut amount = base_amount;
if leftover > 0 {
amount += 1;
leftover -= 1;
}
self.players[player_idx].collect_winnings(amount);
}
return;
}
// Distribute pot based on win percentage
let mut distributed_amount: u32 = 0;
// First pass: distribute whole chips based on wins
for (&player_idx, &wins) in win_counts.iter() {
let win_percentage = wins as f64 / run_count as f64;
let amount = (pot_amount as f64 * win_percentage).floor() as u32;
self.players[player_idx].collect_winnings(amount);
distributed_amount += amount;
}
// Second pass: distribute remaining chips to players in order of highest remainder
let mut remainders: Vec<(usize, f64)> = win_counts.iter()
.map(|(&player_idx, &wins)| {
let win_percentage = wins as f64 / run_count as f64;
let exact_amount = pot_amount as f64 * win_percentage;
let remainder = exact_amount - exact_amount.floor();
(player_idx, remainder)
})
.collect();
// Sort by remainder (highest first)
remainders.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
// Distribute remaining chips
let leftover = pot_amount - distributed_amount;
for (i, (player_idx, _)) in remainders.iter().enumerate() {
if i < leftover as usize {
self.players[*player_idx].collect_winnings(1);
} else {
break;
}
}
}
/// Evaluate winners without updating chip stacks
fn evaluate_winners_without_payout(&self) -> (Vec<usize>, HashMap<usize, Vec<Card>>) {
// If only one player remains, they win
let active_players: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
if active_players.len() == 1 {
return (vec![active_players[0]], HashMap::new());
}
// Evaluate hands for each active player
let mut player_hands: HashMap<usize, (Vec<Card>, HandEvaluation)> = HashMap::new();
for &player_idx in &active_players {
let player = &self.players[player_idx];
let hole_cards = player.hand.cards();
let (best_hand, evaluation) = match self.rules.variant {
GameVariant::TexasHoldem => {
find_best_hand(hole_cards, &self.community_cards)
},
GameVariant::OmahaHoldem4 |
GameVariant::OmahaHoldem5 |
GameVariant::OmahaHoldem6 => {
find_best_omaha_hand(hole_cards, &self.community_cards)
}
};
player_hands.insert(player_idx, (best_hand, evaluation));
}
// Find the best hand(s)
let mut best_eval: Option<&HandEvaluation> = None;
let mut winners = Vec::new();
let mut winning_hands = HashMap::new();
for (&player_idx, (hand, eval)) in &player_hands {
match best_eval {
None => {
best_eval = Some(eval);
winners = vec![player_idx];
winning_hands.insert(player_idx, hand.clone());
},
Some(best) => {
match eval.cmp(best) {
std::cmp::Ordering::Greater => {
best_eval = Some(eval);
winners = vec![player_idx];
winning_hands.clear();
winning_hands.insert(player_idx, hand.clone());
},
std::cmp::Ordering::Equal => {
winners.push(player_idx);
winning_hands.insert(player_idx, hand.clone());
},
std::cmp::Ordering::Less => {
// Not a winner
}
}
}
}
}
(winners, winning_hands)
}
/// Returns a serializable snapshot of the current game state
/// This can be used to save the game state to a database
pub fn get_snapshot(&self) -> GameSnapshot {
// Create player snapshots
let players = self.players.iter().map(|player| {
PlayerSnapshot {
id: player.id,
name: player.name.clone(),
chips: player.chips,
seat_position: player.seat_position,
hand: player.hand.cards().to_vec(),
is_dealer: player.is_dealer,
is_folded: player.is_folded,
is_all_in: player.is_all_in,
bet_amount: player.bet_amount,
}
}).collect();
// Create the game snapshot
GameSnapshot {
rules: self.rules.clone(),
players,
community_cards: self.community_cards.clone(),
pot: self.pot,
current_bet: self.current_bet,
dealer_position: self.dealer_position,
current_position: self.current_position,
stage: self.stage,
side_pots: self.side_pots.clone(),
deck_state: self.deck.remaining_cards(),
}
}
/// Create a new game from a snapshot
pub fn from_snapshot(snapshot: GameSnapshot) -> Self {
// Create a new deck from the snapshot's deck state
let mut deck = Deck::new_empty();
for card in snapshot.deck_state {
deck.add_card(card);
}
// Create players from snapshots
let mut players = Vec::new();
let mut occupied_seats = HashSet::new();
for player_snap in &snapshot.players {
let mut player = Player::new(
player_snap.id,
player_snap.name.clone(),
player_snap.chips,
player_snap.seat_position,
);
// Restore player state
player.is_dealer = player_snap.is_dealer;
player.is_folded = player_snap.is_folded;
player.is_all_in = player_snap.is_all_in;
player.bet_amount = player_snap.bet_amount;
// Restore player's hand
for card in &player_snap.hand {
player.receive_card(*card);
}
players.push(player);
occupied_seats.insert(player_snap.seat_position);
}
// Create the game
let active_player_count = players.iter().filter(|p| !p.is_folded).count();
Self {
rules: snapshot.rules,
deck,
players,
occupied_seats,
community_cards: snapshot.community_cards,
pot: snapshot.pot,
current_bet: snapshot.current_bet,
dealer_position: snapshot.dealer_position,
current_position: snapshot.current_position,
stage: snapshot.stage,
active_player_count,
side_pots: snapshot.side_pots,
multi_run_results: None,
players_acted: HashSet::new(),
}
}
/// Evaluate winners without updating chip stacks - public wrapper for testing
pub fn evaluate_winners_without_paying(&self) -> (Vec<usize>, HashMap<usize, Vec<Card>>) {
self.evaluate_winners_without_payout()
}
}