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
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
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::hand::Hand;
use crate::rules::{GameRules, GameVariant, AnteStructure};
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
pub players_acted: Vec<usize>, // Track which players have acted in the current betting round
pub active_straddles: Vec<(usize, u32)>, // Track active straddles
pub last_straddle_position: Option<usize>, // Position of the last straddle
pub last_preflop_position: Option<usize>, // Position of the player who should act last preflop
pub disbursements: Option<Vec<Disbursement>>,
}
/// 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: Hand,
pub is_dealer: bool,
pub is_folded: bool,
pub is_all_in: bool,
pub bet_amount: u32,
}
/// Details of how a single pot was distributed
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PotDisbursement {
pub pot_id: usize,
pub winners: Vec<usize>,
pub chips_per_winner: u32,
pub leftover: u32,
}
/// A player's total result from a showdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Disbursement {
pub player: usize,
pub total_won: u32,
}
/// The aggregated result of a showdown, including who won what
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShowdownResult {
pub winners: Vec<usize>,
pub pot_distributions: Vec<PotDisbursement>,
pub disbursements: Vec<Disbursement>,
}
#[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
pub active_straddles: Vec<(usize, u32)>, // (player_idx, amount) - tracks posted straddles
pub last_straddle_position: Option<usize>, // Position of the last straddle in this hand
pub last_preflop_position: Option<usize>, // Position of the player who should act last preflop
pub last_showdown: Option<ShowdownResult>,
pub last_raise_amount: u32, // Track the size of the last raise for min-raise validation
}
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(),
active_straddles: Vec::new(),
last_straddle_position: None,
last_preflop_position: None,
last_showdown: None,
last_raise_amount: 0,
}
}
/// 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");
}
// Check if a hand is already in progress
if self.stage != GameStage::Showdown && (self.pot > 0 || !self.community_cards.is_empty()) {
return Err("Cannot start a new hand while one is in progress");
}
// 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()?;
// Clear any straddles from previous hand
self.active_straddles.clear();
self.last_straddle_position = None;
// By default, the big blind position acts last preflop
self.last_preflop_position = Some(self.get_big_blind_position());
// 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();
// Check if small blind player has any chips
if self.players[sb_pos].chips == 0 {
return Err("Small blind player has no chips to post");
}
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();
// Check if big blind player has any chips
if self.players[bb_pos].chips == 0 {
return Err("Big blind player has no chips to post");
}
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 = bb_amount;
// Set the initial raise amount to the big blind
self.last_raise_amount = bb_amount;
}
// Post antes based on the ante structure
match self.rules.ante_structure {
AnteStructure::None => {
// No antes to post
},
AnteStructure::Fixed(ante_amount) => {
// Each player posts the fixed ante
for player in &mut self.players {
if player.chips > 0 {
let ante = ante_amount.min(player.chips);
let amount = player.bet(ante);
self.pot += amount;
}
}
},
AnteStructure::BigBlindOnly(ante_amount) => {
// Only the big blind player posts the ante
let ante = ante_amount.min(self.players[bb_pos].chips);
if ante > 0 {
let amount = self.players[bb_pos].bet(ante);
self.pot += amount;
}
},
AnteStructure::ButtonOnly(ante_amount) => {
// Only the dealer (button) posts the ante
let dealer_position = self.dealer_position;
let ante = ante_amount.min(self.players[dealer_position].chips);
if ante > 0 {
let amount = self.players[dealer_position].bet(ante);
self.pot += amount;
}
},
AnteStructure::BigBlindPercentage(_) => {
// Calculate ante as percentage of big blind
let ante_amount = self.rules.calculate_ante_amount();
// Each player posts the calculated ante
for player in &mut self.players {
if player.chips > 0 {
let ante = ante_amount.min(player.chips);
let amount = player.bet(ante);
self.pot += amount;
}
}
}
}
Ok(())
}
pub 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()
}
pub 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;
self.reset_betting_round();
} else {
return Err("Not enough cards in deck");
}
},
GameStage::River => {
// Move to showdown
self.handle_uncalled_bets();
self.stage = GameStage::Showdown;
self.evaluate_winner();
},
GameStage::Showdown => {
return Err("Hand is already at showdown");
}
}
Ok(self.stage)
}
// Reset the betting round state (bets, current position, etc.)
fn reset_betting_round(&mut self) {
// Reset bet-related state for a new betting round
self.current_bet = 0;
self.last_raise_amount = 0; // Reset last raise amount for the new street
for player in &mut self.players {
player.bet_amount = 0;
}
// Clear the set of players who have acted
self.players_acted.clear();
// Heads-up post-flop rule: the big blind (non-dealer) acts first.
// This matches most live-play conventions and the expectations of the
// majority of our unit-tests.
let starting_position = if self.players.len() == 2 && self.stage != GameStage::Preflop {
// For heads-up post-flop, start with BB
let bb_pos = self.get_big_blind_position();
bb_pos
} else {
// For all other cases (including preflop and 3+ players) we start
// with the first active player after the dealer – typically the
// small blind.
let sb_pos = self.get_small_blind_position();
sb_pos
};
// Find the first active player starting from the determined position
let mut pos = starting_position;
let start_pos = pos; // Remember where we started to detect full loops
// Skip players who can't act
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 == start_pos {
break;
}
}
self.current_position = pos;
// Reset last_preflop_position if we're no longer preflop
if self.stage != GameStage::Preflop {
self.last_preflop_position = None;
}
}
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();
// If no active players, round is complete
if active_players.is_empty() {
return true;
}
// Standard checks for round completion
// 1. All active players have acted
let all_active_acted = active_players.iter()
.all(|pos| self.players_acted.contains(pos));
// 2. 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);
// Debug the case where everyone appears to have acted but we're saying not complete
if all_active_acted && all_bet_matched && active_players.len() == self.players_acted.len() {
// If all active players have acted and matched the bet, and the number of
// active players matches the number of players who have acted,
// then the round should be complete
return true;
}
// Special case for preflop with straddles
if self.stage == GameStage::Preflop &&
self.last_preflop_position.is_some() &&
!self.active_straddles.is_empty() &&
active_players.contains(&self.last_preflop_position.unwrap()) {
// The straddler position
let straddler_position = self.last_preflop_position.unwrap();
// Special handling: if straddler has acted in this round,
// and all bets are matched, the round is complete
let straddler_has_bet = self.players_acted.contains(&straddler_position);
// Check if the straddler has acted last (all other players must have acted too)
let all_players_acted = self.players.iter().enumerate()
.filter(|(_, p)| !p.is_folded && !p.is_all_in && p.chips > 0)
.all(|(i, _)| self.players_acted.contains(&i));
// The round is complete only if all have acted AND bets are matched
return all_bet_matched && all_players_acted && straddler_has_bet;
}
// Default case - round is complete if all active players have acted and matched the bet
all_active_acted && all_bet_matched
}
pub fn handle_action(&mut self, action: Action) -> Result<(), &'static str> {
// First check if we're in a betting round (not in Showdown)
if self.stage == GameStage::Showdown {
return Err("Hand is already at showdown");
}
// Get the current player's position - this is the only player who should act
let current_position = self.current_position;
// Check if preflop with straddle - special handling for UTG position
let is_preflop_with_straddle = self.stage == GameStage::Preflop &&
self.last_preflop_position.is_some() &&
!self.active_straddles.is_empty();
// Validate the player's action based on game state
match action {
Action::Fold => {
// Player can always fold
self.players[current_position].is_folded = true;
self.active_player_count -= 1;
// Add player to players_acted
self.players_acted.insert(current_position);
},
Action::Bet(delta) => {
let player = &mut self.players[current_position];
let player_bet = player.bet_amount;
// Cannot bet negative? (u32 so fine)
if delta == 0 {
// check or invalid depending on current bet
if self.current_bet != player_bet {
return Err("Must put chips to call or raise");
}
self.players_acted.insert(current_position);
} else {
// ensure player has chips
if delta > player.chips {
return Err("Not enough chips for that bet");
}
let to_call = self.current_bet.saturating_sub(player_bet);
if delta < to_call && delta != player.chips {
return Err("Must call the current bet or go all-in");
}
// Check minimum bet size requirements
if to_call == 0 && self.current_bet == 0 && self.stage != GameStage::Preflop {
// First bet in the street (postflop only) - must be at least the big blind
if delta < self.rules.big_blind && delta != player.chips {
return Err("First bet must be at least the size of the big blind");
}
}
// move chips
player.chips -= delta;
player.bet_amount += delta;
self.pot += delta;
// update current bet if this is a raise
if player.bet_amount > self.current_bet {
// Calculate the raise amount (how much was added to the current bet)
let raise_amount = player.bet_amount - self.current_bet;
// If we have a previous raise, check if this one meets minimum requirements
if self.last_raise_amount > 0 && raise_amount < self.last_raise_amount && player.chips > 0 {
// Undo the bet since it doesn't meet minimum raise requirements
player.chips += delta;
player.bet_amount -= delta;
self.pot -= delta;
return Err("Raise too small - must be at least the previous raise amount");
}
// Valid raise - update tracking variables
self.last_raise_amount = raise_amount;
self.current_bet = player.bet_amount;
self.players_acted.clear();
}
self.players_acted.insert(current_position);
if player.chips == 0 {
player.is_all_in = true;
}
}
},
Action::Post(amount) => {
// Post a blind or straddle
if self.players[current_position].chips < amount {
return Err("Not enough chips to post");
}
// Update player's chips and bet amount
self.players[current_position].chips -= amount;
self.players[current_position].bet_amount += amount;
self.pot += amount;
// Update current bet if this post is higher
if self.players[current_position].bet_amount > self.current_bet {
self.current_bet = self.players[current_position].bet_amount;
}
// Check if this post makes the player all-in
if self.players[current_position].chips == 0 {
self.players[current_position].is_all_in = true;
}
// Add player to players_acted unless it's a straddle (handled separately in post_straddle)
self.players_acted.insert(current_position);
}
}
// Special case for straddler acting last in preflop
if is_preflop_with_straddle {
let straddler_position = self.last_preflop_position.unwrap();
// If the current player is not the straddler and all other players have acted,
// make sure the straddler gets to act last
if current_position != straddler_position {
let active_players = self.players.iter().enumerate()
.filter(|(i, p)| *i != straddler_position &&
!p.is_folded &&
!p.is_all_in &&
p.chips > 0)
.map(|(i, _)| i)
.collect::<Vec<_>>();
let all_others_acted = active_players.iter()
.all(|pos| self.players_acted.contains(pos));
let all_bets_matched = active_players.iter()
.all(|pos| self.players[*pos].bet_amount == self.current_bet);
// If all other players have acted and matched the bet, straddler acts next
if all_others_acted && all_bets_matched &&
!self.players[straddler_position].is_folded &&
!self.players[straddler_position].is_all_in {
// Move directly to the straddler and return
self.current_position = straddler_position;
return Ok(());
}
}
}
// Move to next player
self.next_player();
// Check if round is now complete and advance to next street if needed
let round_now_complete = self.is_round_complete();
if round_now_complete {
// Count players who are still eligible for the pot (not folded)
let eligible_players = self.players.iter().filter(|p| !p.is_folded).count();
if eligible_players <= 1 {
// Only one player left eligible for the pot, go to showdown
self.handle_uncalled_bets();
self.stage = GameStage::Showdown;
self.evaluate_winner();
} else if self.stage != GameStage::Showdown {
// 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, handle uncalled bets first
self.handle_uncalled_bets();
// Then create side pots for proper distribution
self.calculate_side_pots();
// Deal remaining cards based on current stage
while self.stage != GameStage::Showdown {
if self.stage == GameStage::River {
// After dealing river, go to showdown
self.stage = GameStage::Showdown;
break;
} else {
// Deal next street (flop, turn, or river)
self.next_street().expect("Failed to deal next street");
}
}
// Now evaluate winner at showdown
self.evaluate_winner();
} else {
// Regular betting round complete, move to next street
// Create side pots if players are all-in
self.calculate_side_pots();
match self.stage {
GameStage::Preflop => {
// Reset players_acted before moving to next street
self.players_acted.clear();
self.current_bet = 0;
self.next_street().expect("Failed to deal flop");
},
GameStage::Flop => {
// Reset players_acted before moving to next street
self.players_acted.clear();
self.current_bet = 0;
self.next_street().expect("Failed to deal turn");
},
GameStage::Turn => {
// Reset players_acted before moving to next street
self.players_acted.clear();
self.current_bet = 0;
self.next_street().expect("Failed to deal river");
},
GameStage::River => {
self.handle_uncalled_bets();
self.stage = GameStage::Showdown;
self.evaluate_winner();
},
GameStage::Showdown => {
// Already at showdown
}
}
}
}
}
// Special case for straddler acting last in preflop
// If the straddler has just acted and we're still in preflop, check if the round is complete
if is_preflop_with_straddle &&
self.last_preflop_position.is_some() &&
current_position == self.last_preflop_position.unwrap() &&
self.stage == GameStage::Preflop {
// Check if all players have acted and all bets are matched
let all_bets_matched = self.players.iter().enumerate()
.filter(|(_, p)| !p.is_folded && !p.is_all_in && p.chips > 0)
.all(|(_, p)| p.bet_amount == self.current_bet);
let all_players_acted = self.players.iter().enumerate()
.filter(|(_, p)| !p.is_folded && !p.is_all_in && p.chips > 0)
.all(|(i, _)| self.players_acted.contains(&i));
// If the straddler has acted last and all bets are matched, move to the flop
if all_bets_matched && all_players_acted {
// Reset players_acted before moving to next street
self.players_acted.clear();
self.current_bet = 0;
// Move to the flop if the straddler was the last to act
self.next_street().expect("Failed to deal flop");
}
}
Ok(())
}
fn next_player(&mut self) {
// Check if the round is complete - no need to move to next player
if self.is_round_complete() {
return;
}
// 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;
if pot_contribution <= 0 {
continue; // Skip if no contribution to this pot level
}
// Find players who contributed to this pot level
// A player contributes to this pot level if:
// 1. They are not folded
// 2. They bet at least the amount of this all-in
let eligible: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded && p.bet_amount >= *amount)
.map(|(i, _)| i)
.collect();
// Always create the side pot – even if only one player is eligible (refund of over-bet)
if !eligible.is_empty() {
// Calculate side pot size: number of eligible players * contribution amount
let pot_size = eligible.len() as u32 * pot_contribution;
self.side_pots.push((pot_size, eligible));
total_side_pot_amount += pot_size;
}
prev_amount = *amount;
}
// Find players with bets higher than the highest all-in amount
let highest_all_in = all_in_amounts.last().map(|&(_, amount)| amount).unwrap_or(0);
// Calculate main pot (if any players have bet more than highest all-in)
let remaining_players: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded && p.bet_amount > highest_all_in)
.map(|(i, _)| i)
.collect();
if !remaining_players.is_empty() {
// Find the minimum bet among remaining players
let min_bet = remaining_players.iter()
.map(|&idx| self.players[idx].bet_amount)
.min()
.unwrap_or(0);
// Calculate remaining pot
// Each player contributes (min_bet - highest_all_in)
let player_contribution = min_bet - highest_all_in;
let remaining_pot = remaining_players.len() as u32 * player_contribution;
// Add main pot if there's anything left
if remaining_pot > 0 {
self.side_pots.push((remaining_pot, remaining_players));
total_side_pot_amount += remaining_pot;
}
}
// If there's still pot money unaccounted for, it's because our calculations are off
// This can happen if some players folded after betting
if self.pot > total_side_pot_amount {
let unaccounted = self.pot - total_side_pot_amount;
// Add this to the last pot or create a new one if needed
if !self.side_pots.is_empty() {
let last_idx = self.side_pots.len() - 1;
let (amount, eligible) = &self.side_pots[last_idx];
self.side_pots[last_idx] = (amount + unaccounted, eligible.clone());
} else {
// Create a pot with all non-folded players
let eligible: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
if !eligible.is_empty() {
self.side_pots.push((unaccounted, eligible));
}
}
}
}
/// Evaluate winners and distribute pot
pub fn evaluate_winner(&mut self) -> ShowdownResult {
// Ensure we're at showdown stage before evaluating
if self.stage != GameStage::Showdown {
panic!("Cannot evaluate winners before showdown stage; current stage = {:?}", self.stage);
}
// 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];
let amount = self.pot;
self.players[winner_idx].collect_winnings(amount);
self.pot = 0;
let pd = PotDisbursement { pot_id: 0, winners: vec![winner_idx], chips_per_winner: amount, leftover: 0 };
let disp = Disbursement { player: winner_idx, total_won: amount };
let sr = ShowdownResult { winners: vec![winner_idx], pot_distributions: vec![pd], disbursements: vec![disp] };
self.stage = GameStage::Showdown;
self.last_showdown = Some(sr.clone());
return sr;
}
// 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));
}
// Ensure side pots are up to date
if self.side_pots.is_empty() {
self.calculate_side_pots();
}
// If we still have no side pots (no all-ins) and pot > 0, create a simple main pot
if self.side_pots.is_empty() && self.pot > 0 {
let main_pot_eligible: Vec<usize> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, _)| i)
.collect();
self.side_pots.push((self.pot, main_pot_eligible));
}
let mut pot_distributions = Vec::new();
let mut totals: HashMap<usize, u32> = HashMap::new();
// Debug info
if cfg!(debug_assertions) {
println!("Pot at evaluate_winner: {}", self.pot);
println!("Side pots count: {}", self.side_pots.len());
for (i, (amount, eligible)) in self.side_pots.iter().enumerate() {
println!("Side pot {}: amount={}, eligible={:?}", i, amount, eligible);
}
}
// Iterate through each pot (including main pot)
for (pot_id, (pot_amount, eligible)) in self.side_pots.clone().into_iter().enumerate() {
// Find winners for this pot
let mut best_eval = None;
let mut winners = Vec::new();
let _winning_hands: HashMap<usize, Vec<Card>> = HashMap::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 => {}
}
}
}
}
if winners.is_empty() { continue; }
let count = winners.len() as u32;
let base_amount = pot_amount / count;
let mut remainder = pot_amount % count;
// Award base_amount to each winner
for &w in &winners {
self.players[w].collect_winnings(base_amount);
*totals.entry(w).or_insert(0) += base_amount;
}
// Determine out-of-position ordering for remainder chips
let num_players = self.players.len();
let start_pos = (self.dealer_position + 1) % num_players;
let mut ordered = winners.clone();
ordered.sort_by_key(|&w| (w + num_players - start_pos) % num_players);
// Distribute remainder one chip at a time
for &w in &ordered {
if remainder == 0 { break; }
self.players[w].collect_winnings(1);
*totals.entry(w).or_insert(0) += 1;
remainder -= 1;
}
pot_distributions.push(PotDisbursement {
pot_id,
winners: winners.clone(),
chips_per_winner: base_amount,
leftover: pot_amount % count,
});
}
// Cleanup pot state
self.pot = 0;
self.side_pots.clear();
// Build flat disbursements map
let disbursements = totals.into_iter()
.map(|(player, total_won)| Disbursement { player, total_won })
.collect();
// Overall winners are those from the main pot (last in distributions)
let winners = pot_distributions.last()
.map(|pd| pd.winners.clone())
.unwrap_or_default();
let sr = ShowdownResult { winners, pot_distributions, disbursements };
self.stage = GameStage::Showdown;
self.last_showdown = Some(sr.clone());
sr
}
/// 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.clone(),
is_dealer: player.is_dealer,
is_folded: player.is_folded,
is_all_in: player.is_all_in,
bet_amount: player.bet_amount,
}
}).collect();
// Map internal positions (indices) to physical seat numbers so that
// any consumer of the snapshot does not need to be aware of the
// internal player ordering.
let dealer_seat = self.players.get(self.dealer_position)
.map(|p| p.seat_position)
.unwrap_or(self.dealer_position);
let current_seat = self.players.get(self.current_position)
.map(|p| p.seat_position)
.unwrap_or(self.current_position);
let last_straddle_seat = self.last_straddle_position
.and_then(|idx| self.players.get(idx).map(|p| p.seat_position));
let last_preflop_seat = self.last_preflop_position
.and_then(|idx| self.players.get(idx).map(|p| p.seat_position));
// 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: dealer_seat,
current_position: current_seat,
stage: self.stage,
side_pots: self.side_pots.clone(),
deck_state: self.deck.remaining_cards(),
players_acted: self.players_acted.iter().cloned().collect(),
active_straddles: self.active_straddles.iter().map(|(idx, amt)| {
let seat = self.players.get(*idx).map(|p| p.seat_position).unwrap_or(*idx);
(seat, *amt)
}).collect(),
last_straddle_position: last_straddle_seat,
last_preflop_position: last_preflop_seat,
disbursements: if self.stage == GameStage::Showdown {
self.last_showdown.as_ref().map(|sr| sr.disbursements.clone())
} else {
None
},
}
}
/// 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
player.hand = player_snap.hand.clone();
players.push(player);
occupied_seats.insert(player_snap.seat_position);
}
// Ensure players are ordered the same way Chironaut expects (by seat)
players.sort_by_key(|p| p.seat_position);
// Helper to convert a seat number into the corresponding player index
let seat_to_index = |seat: Option<usize>| -> Option<usize> {
seat.and_then(|s| players.iter().position(|p| p.seat_position == s))
};
let dealer_index = seat_to_index(Some(snapshot.dealer_position)).unwrap_or(0);
let current_index = seat_to_index(Some(snapshot.current_position)).unwrap_or(dealer_index);
let last_straddle_index = seat_to_index(snapshot.last_straddle_position);
let last_preflop_index = seat_to_index(snapshot.last_preflop_position);
// Convert active_straddles seat references back into internal indices
let active_straddles_internal: Vec<(usize, u32)> = snapshot.active_straddles.into_iter()
.filter_map(|(seat, amt)| {
seat_to_index(Some(seat)).map(|idx| (idx, amt))
})
.collect();
// Reconstruct which players have already acted in the current betting
// round. The snapshot stores *player indices* (not seat numbers)
// because they originally came straight from `self.players_acted`.
// For forward-compatibility we also tolerate a snapshot that stored
// seat numbers and translate those back into the matching index.
let players_acted_internal: HashSet<usize> = snapshot.players_acted.into_iter()
.filter_map(|val| {
// Value equals an existing index – fine.
if val < players.len() {
return Some(val);
}
// Otherwise treat it as a seat-number and map to index.
seat_to_index(Some(val))
})
.collect();
// 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: dealer_index,
current_position: current_index,
stage: snapshot.stage,
active_player_count,
side_pots: snapshot.side_pots, // amounts only – player refs handled elsewhere
multi_run_results: None,
players_acted: players_acted_internal,
active_straddles: active_straddles_internal,
last_straddle_position: last_straddle_index,
last_preflop_position: last_preflop_index,
last_showdown: None,
last_raise_amount: 0,
}
}
/// 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()
}
/// Post a straddle at a specific position
///
/// # Parameters
/// * `position`: The position of the player who is straddling
/// * `amount`: The amount to straddle (typically 2x the big blind or previous straddle)
///
/// # Returns
/// * `Ok(())` if the straddle was successfully posted
/// * `Err(...)` with an error message if the straddle was invalid
pub fn post_straddle(&mut self, position: usize, amount: u32) -> Result<(), &'static str> {
// Validate game state
if self.stage != GameStage::Preflop {
return Err("Straddles can only be posted preflop");
}
// Check if straddles are allowed
if !self.rules.allow_straddles {
return Err("Straddles are not allowed in this game");
}
// Check if player has already acted
if self.players_acted.contains(&position) {
return Err("Player has already acted and cannot straddle");
}
// Check if player has enough chips
if self.players[position].chips < amount {
return Err("Player doesn't have enough chips to post straddle");
}
// Validate straddle amount
let min_straddle = if !self.active_straddles.is_empty() {
// If there's a previous straddle, new straddle must be at least 2x the previous
let (_, prev_amount) = self.active_straddles.last().unwrap();
prev_amount * 2
} else {
// Otherwise, straddle must be at least 2x the big blind
self.rules.big_blind * 2
};
if amount < min_straddle {
return Err("Straddle amount must be at least 2x the previous bet");
}
// Post the straddle
self.current_position = position;
// Use handle_action to post the bet
self.handle_action(Action::Post(amount))?;
// Record the straddle
self.active_straddles.push((position, amount));
self.last_straddle_position = Some(position);
// In poker, the last straddler acts last in the preflop betting round
self.last_preflop_position = Some(position);
// After straddles, the first to act is the player after the last straddle
self.current_position = (position + 1) % self.players.len();
// DO NOT mark the straddle player as having acted for betting purposes
// We only want to mark them as having acted when they make a betting decision
// Remove them from players_acted if they're there (from the Post action above)
self.players_acted.remove(&position);
Ok(())
}
/// Force a particular seat to win the current hand.
///
/// This helper is primarily meant for testing or administrative scenarios. It
/// 1. Validates that the provided `seat` has an active player sitting in it.
/// 2. Folds every other player that is still in the hand.
/// 3. Sets the game stage to `Showdown` and uses the normal `evaluate_winner`
/// flow to award the pot and generate a `ShowdownResult`.
///
/// The method returns a `ShowdownResult` identical to what would be produced
/// during a regular showdown so that callers can reuse their existing logic.
///
/// # Arguments
/// * `seat` – The physical seat number (0-based) that should be declared the
/// winner.
///
/// # Errors
/// * Returns `Err` if there is no player occupying the given seat or the
/// hand has not been started yet.
pub fn force_win(&mut self, seat: usize) -> Result<ShowdownResult, &'static str> {
// Validate that the hand is in progress – we at least need cards dealt
// and a pot that can be awarded. The hand could be at any stage except
// that it must not have been completed already.
if self.stage == GameStage::Showdown {
return Err("Hand is already at showdown");
}
// Check that a hand has actually started
if self.pot == 0 && self.community_cards.is_empty() && self.players.iter().all(|p| p.bet_amount == 0) {
return Err("Cannot force win when hand has not been started");
}
// Locate the player that occupies the specified seat.
let winner_idx = self.players
.iter()
.position(|p| p.seat_position == seat)
.ok_or("No player found in the specified seat")?;
// Fold every other player that is still in the hand.
for (idx, player) in self.players.iter_mut().enumerate() {
if idx != winner_idx {
if !player.is_folded {
player.is_folded = true;
}
}
}
// Only a single active player should remain now.
self.active_player_count = 1;
// Move straight to showdown and use the normal flow to determine the
// winner and award the pot. This guarantees that all bookkeeping is
// identical to a natural showdown (side-pots, disbursements, etc.).
self.stage = GameStage::Showdown;
let result = self.evaluate_winner();
Ok(result)
}
/// Handle uncalled bets by returning them to the bettor
/// This should be called before evaluate_winner() when the betting round ends
fn handle_uncalled_bets(&mut self) {
// Get all non-folded players and their bet amounts
let player_bets: Vec<(usize, u32)> = self.players.iter()
.enumerate()
.filter(|(_, p)| !p.is_folded)
.map(|(i, p)| (i, p.bet_amount))
.collect();
if player_bets.len() <= 1 {
return; // No uncalled bets possible with 0 or 1 players
}
// Sort by bet amount (highest first)
let mut sorted_bets = player_bets.clone();
sorted_bets.sort_by_key(|&(_, amount)| std::cmp::Reverse(amount));
let highest_bet = sorted_bets[0].1;
let second_highest_bet = sorted_bets[1].1;
// If there's a difference, we have an uncalled bet
if highest_bet > second_highest_bet {
let uncalled_amount = highest_bet - second_highest_bet;
let bettor_idx = sorted_bets[0].0;
// Return the uncalled bet to the bettor
self.players[bettor_idx].chips += uncalled_amount;
self.players[bettor_idx].bet_amount -= uncalled_amount;
self.pot -= uncalled_amount;
// Debug logging
if cfg!(debug_assertions) {
println!("Returning uncalled bet of {} to player {}",
uncalled_amount, self.players[bettor_idx].name);
println!("Pot reduced from {} to {}",
self.pot + uncalled_amount, self.pot);
}
}
}
}