1use super::chips::Chips;
12use crate::card::{mask_has, mask_of, Card, CardSet};
13
14#[derive(Debug, Clone, PartialEq)]
33pub struct GameConfig {
34 pub(crate) board: Vec<Card>,
35 pub(crate) pot: Chips,
36 pub(crate) effective_stack: Chips,
37 pub(crate) bet_sizes: Vec<f64>,
38 pub(crate) max_raises: u32,
39 pub(crate) suit_isomorphism: bool,
40}
41
42impl GameConfig {
43 pub fn new(board: Vec<Card>, pot: Chips, effective_stack: Chips) -> GameConfig {
48 GameConfig {
49 board,
50 pot,
51 effective_stack,
52 bet_sizes: Vec::new(),
53 max_raises: 0,
54 suit_isomorphism: false,
55 }
56 }
57
58 pub fn with_bet_sizes(mut self, bet_sizes: impl Into<Vec<f64>>) -> GameConfig {
64 self.bet_sizes = bet_sizes.into();
65 self
66 }
67
68 pub fn with_max_raises(mut self, max_raises: u32) -> GameConfig {
71 self.max_raises = max_raises;
72 self
73 }
74
75 pub fn with_suit_isomorphism(mut self, suit_isomorphism: bool) -> GameConfig {
83 self.suit_isomorphism = suit_isomorphism;
84 self
85 }
86
87 pub fn board(&self) -> &[Card] {
89 &self.board
90 }
91
92 pub fn pot(&self) -> Chips {
94 self.pot
95 }
96
97 pub fn effective_stack(&self) -> Chips {
99 self.effective_stack
100 }
101
102 pub fn bet_sizes(&self) -> &[f64] {
104 &self.bet_sizes
105 }
106
107 pub fn max_raises(&self) -> u32 {
109 self.max_raises
110 }
111
112 pub fn suit_isomorphism(&self) -> bool {
114 self.suit_isomorphism
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub enum Player {
121 Oop,
123 Ip,
125}
126
127impl Player {
128 pub const ALL: [Player; 2] = [Player::Oop, Player::Ip];
130
131 pub fn other(self) -> Player {
133 match self {
134 Player::Oop => Player::Ip,
135 Player::Ip => Player::Oop,
136 }
137 }
138
139 pub fn index(self) -> usize {
141 match self {
142 Player::Oop => 0,
143 Player::Ip => 1,
144 }
145 }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub enum Action {
151 Check,
153 Bet(Chips),
155 Call,
157 Fold,
159 Raise(Chips),
161}
162
163#[derive(Debug, Clone, Copy, PartialEq)]
165pub enum Terminal {
166 Fold {
174 winner: Player,
176 invested: [f64; 2],
178 },
179 Showdown {
182 invested: [f64; 2],
184 },
185}
186
187#[derive(Debug, Clone, PartialEq)]
189pub enum Node {
190 Decision {
192 id: usize,
196 player: Player,
198 actions: Vec<Action>,
200 children: Vec<Node>,
202 },
203 Chance {
212 children: Vec<(Vec<Card>, Node)>,
214 },
215 Terminal(Terminal),
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221#[non_exhaustive]
222pub enum BoardError {
223 WrongSize {
225 len: usize,
227 },
228 DuplicateCard {
230 card: Card,
232 },
233}
234
235impl std::fmt::Display for BoardError {
236 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237 match self {
238 Self::WrongSize { len } => write!(f, "board has {len} cards; expected 3, 4, or 5"),
239 Self::DuplicateCard { card } => {
240 write!(f, "board card {card} appears more than once")
241 }
242 }
243 }
244}
245
246impl std::error::Error for BoardError {}
247
248pub(crate) fn validate_board(board: &[Card]) -> Result<(), BoardError> {
250 if !(3..=5).contains(&board.len()) {
251 return Err(BoardError::WrongSize { len: board.len() });
252 }
253 let mut seen = CardSet::EMPTY;
254 for &card in board {
255 if !seen.insert(card) {
256 return Err(BoardError::DuplicateCard { card });
257 }
258 }
259 Ok(())
260}
261
262#[derive(Debug, Clone, PartialEq, Eq)]
264#[non_exhaustive]
265pub enum TreeError {
266 Board(BoardError),
268 NonPositivePot,
270 NegativeStack,
272 InvalidBetSize {
274 index: usize,
276 },
277 TooManyDecisionNodes {
279 limit: usize,
281 },
282}
283
284impl std::fmt::Display for TreeError {
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 match self {
287 Self::Board(error) => write!(f, "invalid board: {error}"),
288 Self::NonPositivePot => write!(f, "pot must be positive"),
289 Self::NegativeStack => write!(f, "effective stack must not be negative"),
290 Self::InvalidBetSize { index } => write!(
291 f,
292 "bet size at index {index} must be a positive, finite pot fraction"
293 ),
294 Self::TooManyDecisionNodes { limit } => write!(
295 f,
296 "game tree exceeds {limit} decision nodes; reduce bet sizes, raises, or start on a later street"
297 ),
298 }
299 }
300}
301
302impl std::error::Error for TreeError {
303 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
304 match self {
305 Self::Board(error) => Some(error),
306 _ => None,
307 }
308 }
309}
310
311impl From<BoardError> for TreeError {
312 fn from(error: BoardError) -> Self {
313 Self::Board(error)
314 }
315}
316
317fn validate_config(cfg: &GameConfig) -> Result<(), TreeError> {
319 validate_board(&cfg.board)?;
320 if cfg.pot <= Chips::ZERO {
321 return Err(TreeError::NonPositivePot);
322 }
323 if cfg.effective_stack < Chips::ZERO {
324 return Err(TreeError::NegativeStack);
325 }
326 if let Some(index) = cfg
327 .bet_sizes
328 .iter()
329 .position(|&size| !size.is_finite() || size <= 0.0)
330 {
331 return Err(TreeError::InvalidBetSize { index });
332 }
333 Ok(())
334}
335
336#[derive(Debug, Clone, PartialEq)]
338pub struct Tree {
339 pub board: Vec<Card>,
341 pub root: Node,
343 pub num_decision_nodes: usize,
345}
346
347pub fn build_tree(cfg: &GameConfig) -> Result<Tree, TreeError> {
375 build_tree_bounded(cfg, usize::MAX)
376}
377
378pub fn build_tree_bounded(cfg: &GameConfig, max_decision_nodes: usize) -> Result<Tree, TreeError> {
388 validate_config(cfg)?;
389 let mut budget = BuildBudget {
390 next_id: 0,
391 max_decision_nodes,
392 };
393 let stack = [cfg.effective_stack, cfg.effective_stack];
394 let root = build(
395 cfg,
396 &cfg.board,
397 Player::Oop,
398 [Chips::ZERO; 2],
399 stack,
400 None,
401 false,
402 0,
403 &mut budget,
404 )?;
405 Ok(Tree {
406 board: cfg.board.clone(),
407 root,
408 num_decision_nodes: budget.next_id,
409 })
410}
411
412struct BuildBudget {
413 next_id: usize,
414 max_decision_nodes: usize,
415}
416
417impl BuildBudget {
418 fn allocate_id(&mut self) -> Result<usize, TreeError> {
419 if self.next_id >= self.max_decision_nodes {
420 return Err(TreeError::TooManyDecisionNodes {
421 limit: self.max_decision_nodes,
422 });
423 }
424 let id = self.next_id;
425 self.next_id += 1;
426 Ok(id)
427 }
428}
429
430fn free_suits(board: &[Card]) -> [bool; 4] {
434 let mut used = [false; 4];
435 for &c in board {
436 used[c.suit() as usize] = true;
437 }
438 [!used[0], !used[1], !used[2], !used[3]]
439}
440
441pub(crate) fn deal_classes(suit_isomorphism: bool, board: &[Card]) -> Vec<Vec<Card>> {
453 let used = mask_of(board);
454 let free = if suit_isomorphism {
455 free_suits(board)
456 } else {
457 [false; 4]
458 };
459
460 let mut classes: Vec<Vec<Card>> = Vec::new();
461 let mut free_rank_class: [Option<usize>; 13] = [None; 13];
462 for c in Card::all() {
463 if mask_has(used, c) {
464 continue;
465 }
466 if free[c.suit() as usize] {
467 let r = c.rank() as usize;
468 match free_rank_class[r] {
469 Some(idx) => classes[idx].push(c),
470 None => {
471 free_rank_class[r] = Some(classes.len());
472 classes.push(vec![c]);
473 }
474 }
475 } else {
476 classes.push(vec![c]);
477 }
478 }
479 classes
480}
481
482fn end_of_street(
486 cfg: &GameConfig,
487 board: &[Card],
488 added: [Chips; 2],
489 stack: [Chips; 2],
490 budget: &mut BuildBudget,
491) -> Result<Node, TreeError> {
492 if board.len() >= 5 {
493 return Ok(Node::Terminal(Terminal::Showdown {
494 invested: invested(cfg, added),
495 }));
496 }
497 let mut children = Vec::new();
498 for members in deal_classes(cfg.suit_isomorphism, board) {
499 let rep = members[0];
500 let mut next_board = board.to_vec();
501 next_board.push(rep);
502 let child = build(
503 cfg,
504 &next_board,
505 Player::Oop,
506 added,
507 stack,
508 None,
509 false,
510 0,
511 budget,
512 )?;
513 children.push((members, child));
514 }
515 Ok(Node::Chance { children })
516}
517
518fn invested(cfg: &GameConfig, added: [Chips; 2]) -> [f64; 2] {
521 let baseline = cfg.pot.to_f64() / 2.0;
522 [baseline + added[0].to_f64(), baseline + added[1].to_f64()]
523}
524
525#[allow(clippy::too_many_arguments)]
527fn build(
528 cfg: &GameConfig,
529 board: &[Card],
530 player: Player,
531 added: [Chips; 2],
532 stack: [Chips; 2],
533 facing: Option<Chips>,
534 prev_checked: bool,
535 raises_so_far: u32,
536 budget: &mut BuildBudget,
537) -> Result<Node, TreeError> {
538 if facing.is_none() && stack == [Chips::ZERO; 2] {
544 return end_of_street(cfg, board, added, stack, budget);
545 }
546 let id = budget.allocate_id()?;
547
548 let mut actions = Vec::new();
549 let mut children = Vec::new();
550
551 if let Some(to_call) = facing {
552 actions.push(Action::Fold);
553 children.push(Node::Terminal(Terminal::Fold {
554 winner: player.other(),
555 invested: invested(cfg, added),
556 }));
557
558 let mut call_added = added;
559 call_added[player.index()] += to_call;
560 let mut call_stack = stack;
561 call_stack[player.index()] -= to_call;
562 actions.push(Action::Call);
563 children.push(end_of_street(cfg, board, call_added, call_stack, budget)?);
564
565 if raises_so_far < cfg.max_raises && stack[player.index()] > to_call {
566 let opponent = player.other();
567 let pot_after_call = cfg.pot + added[0] + added[1] + to_call;
568 let own_room = stack[player.index()] - to_call;
569 let opponent_room = stack[opponent.index()];
570 let raise_extras =
571 sized_amounts(&cfg.bet_sizes, pot_after_call, own_room.min(opponent_room));
572
573 for extra in raise_extras {
574 let mut new_added = added;
575 new_added[player.index()] += to_call + extra;
576 let mut new_stack = stack;
577 new_stack[player.index()] -= to_call + extra;
578 actions.push(Action::Raise(extra));
579 children.push(build(
580 cfg,
581 board,
582 opponent,
583 new_added,
584 new_stack,
585 Some(extra),
586 false,
587 raises_so_far + 1,
588 budget,
589 )?);
590 }
591 }
592 } else {
593 let check_child = if prev_checked {
594 end_of_street(cfg, board, added, stack, budget)?
595 } else {
596 build(
597 cfg,
598 board,
599 player.other(),
600 added,
601 stack,
602 None,
603 true,
604 raises_so_far,
605 budget,
606 )?
607 };
608 actions.push(Action::Check);
609 children.push(check_child);
610
611 if stack[player.index()] > Chips::ZERO {
612 let opponent = player.other();
613 let pot_now = cfg.pot + added[0] + added[1];
614 let room = stack[player.index()].min(stack[opponent.index()]);
615 let bet_amounts = sized_amounts(&cfg.bet_sizes, pot_now, room);
616
617 for amt in bet_amounts {
618 let mut new_added = added;
619 new_added[player.index()] += amt;
620 let mut new_stack = stack;
621 new_stack[player.index()] -= amt;
622 actions.push(Action::Bet(amt));
623 children.push(build(
624 cfg,
625 board,
626 opponent,
627 new_added,
628 new_stack,
629 Some(amt),
630 false,
631 raises_so_far,
632 budget,
633 )?);
634 }
635 }
636 }
637
638 Ok(Node::Decision {
639 id,
640 player,
641 actions,
642 children,
643 })
644}
645
646fn sized_amounts(fractions: &[f64], pot: Chips, room: Chips) -> Vec<Chips> {
649 let mut amounts: Vec<Chips> = fractions
650 .iter()
651 .map(|&frac| pot.fraction(frac).min(room))
652 .filter(|&amt| amt > Chips::ZERO)
653 .collect();
654 amounts.sort_unstable();
655 amounts.dedup();
656 amounts
657}
658
659#[cfg(test)]
660mod tests {
661 use super::*;
662 use crate::card::Card;
663
664 fn river_board() -> Vec<Card> {
665 ["2h", "7c", "9d", "Jc", "4s"]
666 .iter()
667 .map(|s| s.parse::<Card>().unwrap())
668 .collect()
669 }
670
671 fn turn_board() -> Vec<Card> {
672 ["2h", "7c", "9d", "Jc"]
673 .iter()
674 .map(|s| s.parse::<Card>().unwrap())
675 .collect()
676 }
677
678 fn shape(node: &Node, scale: i64, out: &mut Vec<String>) {
681 let unscale = |amount: Chips| {
682 assert_eq!(
683 amount.0 % scale,
684 0,
685 "{amount:?} is not a multiple of {scale}"
686 );
687 Chips(amount.0 / scale)
688 };
689 match node {
690 Node::Decision {
691 player,
692 actions,
693 children,
694 ..
695 } => {
696 let actions: Vec<Action> = actions
697 .iter()
698 .map(|action| match *action {
699 Action::Bet(amount) => Action::Bet(unscale(amount)),
700 Action::Raise(amount) => Action::Raise(unscale(amount)),
701 other => other,
702 })
703 .collect();
704 out.push(format!("{player:?} {actions:?}"));
705 children.iter().for_each(|child| shape(child, scale, out));
706 }
707 Node::Chance { children } => children
708 .iter()
709 .for_each(|(_, child)| shape(child, scale, out)),
710 Node::Terminal(Terminal::Fold { invested, .. } | Terminal::Showdown { invested }) => {
711 out.push(format!("{:?}", invested.map(|chips| chips / scale as f64)));
712 }
713 }
714 }
715
716 fn check_stacks(node: &Node, stack: [Chips; 2], facing: Option<Chips>, all_in: bool) {
719 match node {
720 Node::Decision {
721 player,
722 actions,
723 children,
724 ..
725 } => {
726 assert!(!all_in, "decision after a called all-in");
727 let p = player.index();
728 for (action, child) in actions.iter().zip(children) {
729 let mut next = stack;
730 let (paid, next_facing) = match *action {
731 Action::Check | Action::Fold => (Chips::ZERO, None),
732 Action::Call => (facing.unwrap(), None),
733 Action::Bet(amount) => (amount, Some(amount)),
734 Action::Raise(extra) => (facing.unwrap() + extra, Some(extra)),
735 };
736 if let Action::Bet(amount) | Action::Raise(amount) = *action {
737 assert!(amount > Chips::ZERO);
738 }
739 next[p] -= paid;
740 assert!(next[p] >= Chips::ZERO, "stack went negative");
741 let called_all_in = matches!(action, Action::Call) && next == [Chips::ZERO; 2];
742 check_stacks(child, next, next_facing, called_all_in);
743 }
744 }
745 Node::Chance { children } => children
746 .iter()
747 .for_each(|(_, child)| check_stacks(child, stack, None, all_in)),
748 Node::Terminal(_) => {}
749 }
750 }
751
752 fn config(
753 board: Vec<Card>,
754 pot: Chips,
755 stack: Chips,
756 bet_sizes: Vec<f64>,
757 max_raises: u32,
758 ) -> GameConfig {
759 GameConfig {
760 board,
761 pot,
762 effective_stack: stack,
763 bet_sizes,
764 max_raises,
765 suit_isomorphism: true,
766 }
767 }
768
769 fn scaled(cfg: &GameConfig, scale: i64) -> GameConfig {
770 GameConfig {
771 pot: Chips(cfg.pot.0 * scale),
772 effective_stack: Chips(cfg.effective_stack.0 * scale),
773 ..cfg.clone()
774 }
775 }
776
777 #[test]
778 fn all_in_leaves_no_residual_stack_at_any_scale() {
779 for (pot, stack) in [(5500, 9000), (1500, 3900)] {
782 for board in [river_board(), turn_board()] {
783 let cfg = config(board, Chips(pot), Chips(stack), vec![0.33, 0.75, 1.5], 3);
784 let base = build_tree(&cfg).unwrap().num_decision_nodes;
785 for scale in [1, 10, 100] {
786 let tree = build_tree(&scaled(&cfg, scale)).unwrap();
787 assert_eq!(
788 tree.num_decision_nodes, base,
789 "pot {pot} stack {stack} x{scale}"
790 );
791 check_stacks(
792 &tree.root,
793 [cfg.effective_stack; 2].map(|s| Chips(s.0 * scale)),
794 None,
795 false,
796 );
797 }
798 }
799 }
800 let river = config(
801 river_board(),
802 Chips(5500),
803 Chips(9000),
804 vec![0.33, 0.75, 1.5],
805 3,
806 );
807 assert_eq!(build_tree(&river).unwrap().num_decision_nodes, 26);
808 }
809
810 #[test]
811 fn tree_shape_is_scale_invariant_when_sizes_need_no_rounding() {
812 let mut seed = 0x2545_f491_4f6c_dd1du64;
816 let mut next = |bound: u64| {
817 seed ^= seed << 13;
818 seed ^= seed >> 7;
819 seed ^= seed << 17;
820 seed % bound
821 };
822 for _ in 0..200 {
823 let pot = Chips::whole(1 + next(40) as i64);
824 let stack = Chips::whole(1 + next(120) as i64);
825 let sizes: Vec<f64> = (0..1 + next(3))
826 .map(|_| [0.5, 1.0, 1.5, 2.0][next(4) as usize])
827 .collect();
828 let cfg = config(river_board(), pot, stack, sizes, next(3) as u32);
829 let mut base = Vec::new();
830 shape(&build_tree(&cfg).unwrap().root, 1, &mut base);
831 for scale in [10, 100] {
832 let mut other = Vec::new();
833 shape(
834 &build_tree(&scaled(&cfg, scale)).unwrap().root,
835 scale,
836 &mut other,
837 );
838 assert_eq!(base, other, "{cfg:?} x{scale}");
839 }
840 }
841 }
842
843 #[test]
844 fn arbitrary_thousandth_amounts_keep_stacks_exact() {
845 let mut seed = 0x9e37_79b9_7f4a_7c15u64;
846 let mut next = |bound: u64| {
847 seed ^= seed << 13;
848 seed ^= seed >> 7;
849 seed ^= seed << 17;
850 seed % bound
851 };
852 for _ in 0..300 {
853 let pot = Chips(1 + next(20_000) as i64);
854 let stack = Chips(1 + next(60_000) as i64);
855 let sizes: Vec<f64> = (0..1 + next(4))
856 .map(|_| (1 + next(300)) as f64 / 100.0)
857 .collect();
858 let cfg = config(river_board(), pot, stack, sizes, next(4) as u32);
859 check_stacks(&build_tree(&cfg).unwrap().root, [stack; 2], None, false);
860 }
861 }
862
863 #[test]
864 fn bounded_tree_preserves_ids_actions_and_exact_boundary() {
865 let cfg = GameConfig {
866 board: turn_board(),
867 pot: Chips::whole(100),
868 effective_stack: Chips::whole(200),
869 bet_sizes: vec![0.5, 1.0],
870 max_raises: 1,
871 suit_isomorphism: true,
872 };
873 let original = build_tree(&cfg).unwrap();
874 let bounded = build_tree_bounded(&cfg, original.num_decision_nodes).unwrap();
875 assert_eq!(
876 format!("{:?}", original.root),
877 format!("{:?}", bounded.root)
878 );
879 assert_eq!(original.num_decision_nodes, bounded.num_decision_nodes);
880 assert!(build_tree_bounded(&cfg, original.num_decision_nodes - 1).is_err());
881 assert!(build_tree_bounded(&cfg, 0).is_err());
882 }
883
884 #[test]
885 fn bounded_tree_aborts_large_flop_construction() {
886 let cfg = GameConfig {
887 board: turn_board()[..3].to_vec(),
888 pot: Chips::whole(100),
889 effective_stack: Chips::whole(100000),
890 bet_sizes: vec![0.25, 0.5, 1.0, 2.0],
891 max_raises: 4,
892 suit_isomorphism: false,
893 };
894 let error = build_tree_bounded(&cfg, 100).expect_err("must exceed construction budget");
895 assert_eq!(error, TreeError::TooManyDecisionNodes { limit: 100 });
896 assert!(error.to_string().contains("100 decision nodes"));
897 }
898
899 #[test]
900 fn check_check_ends_in_showdown_on_the_river() {
901 let cfg = GameConfig {
902 board: river_board(),
903 pot: Chips::whole(100),
904 effective_stack: Chips::whole(200),
905 bet_sizes: vec![1.0],
906 max_raises: 0,
907 suit_isomorphism: false,
908 };
909 let tree = build_tree(&cfg).unwrap();
910 let Node::Decision {
911 actions, children, ..
912 } = &tree.root
913 else {
914 panic!("expected decision")
915 };
916 assert_eq!(actions.len(), 2);
917 let Node::Decision {
918 player: ip_player,
919 actions: ip_actions,
920 children: ip_children,
921 ..
922 } = &children[0]
923 else {
924 panic!("expected IP decision after check")
925 };
926 assert_eq!(*ip_player, Player::Ip);
927 assert_eq!(ip_actions.len(), 2);
928 assert!(matches!(
929 ip_children[0],
930 Node::Terminal(Terminal::Showdown { .. })
931 ));
932 }
933
934 #[test]
935 fn bet_size_is_pot_fraction_and_call_ends_in_showdown_on_the_river() {
936 let cfg = GameConfig {
937 board: river_board(),
938 pot: Chips::whole(100),
939 effective_stack: Chips::whole(200),
940 bet_sizes: vec![1.0],
941 max_raises: 0,
942 suit_isomorphism: false,
943 };
944 let tree = build_tree(&cfg).unwrap();
945 let Node::Decision {
946 actions, children, ..
947 } = &tree.root
948 else {
949 panic!("expected decision")
950 };
951 let Action::Bet(amount) = actions[1] else {
952 panic!("expected a bet action")
953 };
954 assert_eq!(amount, Chips::whole(100));
955
956 let Node::Decision {
957 actions: ip_actions,
958 children: ip_children,
959 ..
960 } = &children[1]
961 else {
962 panic!("expected IP decision facing the bet")
963 };
964 assert_eq!(ip_actions.len(), 2);
965 assert!(matches!(
966 ip_children[0],
967 Node::Terminal(Terminal::Fold { .. })
968 ));
969 assert!(matches!(
970 ip_children[1],
971 Node::Terminal(Terminal::Showdown { .. })
972 ));
973 }
974
975 #[test]
976 fn raises_are_capped_by_max_raises_per_street() {
977 let cfg = GameConfig {
978 board: river_board(),
979 pot: Chips::whole(100),
980 effective_stack: Chips::whole(1000),
981 bet_sizes: vec![1.0],
982 max_raises: 1,
983 suit_isomorphism: false,
984 };
985 let tree = build_tree(&cfg).unwrap();
986 let Node::Decision { children, .. } = &tree.root else {
987 panic!("expected decision")
988 };
989 let Node::Decision {
990 actions,
991 children: ip_children,
992 ..
993 } = &children[1]
994 else {
995 panic!("expected IP decision facing the bet")
996 };
997 assert_eq!(actions.len(), 3);
998 let Node::Decision {
999 actions: oop_actions,
1000 ..
1001 } = &ip_children[2]
1002 else {
1003 panic!("expected OOP decision facing the raise")
1004 };
1005 assert_eq!(oop_actions.len(), 2);
1006 }
1007
1008 #[test]
1009 fn check_check_on_the_turn_deals_a_chance_node_with_48_river_cards() {
1010 let cfg = GameConfig {
1011 board: turn_board(),
1012 pot: Chips::whole(100),
1013 effective_stack: Chips::whole(200),
1014 bet_sizes: vec![1.0],
1015 max_raises: 0,
1016 suit_isomorphism: false,
1017 };
1018 let tree = build_tree(&cfg).unwrap();
1019 let Node::Decision { children, .. } = &tree.root else {
1020 panic!("expected decision")
1021 };
1022 let Node::Decision {
1023 children: ip_children,
1024 ..
1025 } = &children[0]
1026 else {
1027 panic!("expected IP decision after check")
1028 };
1029 let Node::Chance {
1031 children: river_deals,
1032 } = &ip_children[0]
1033 else {
1034 panic!("expected a chance node dealing the river")
1035 };
1036 assert_eq!(river_deals.len(), 48); for (members, _) in river_deals {
1039 assert_eq!(members.len(), 1);
1040 }
1041
1042 for (_, node) in river_deals {
1044 assert!(matches!(
1045 node,
1046 Node::Decision {
1047 player: Player::Oop,
1048 ..
1049 }
1050 ));
1051 }
1052 }
1053
1054 #[test]
1055 fn river_deals_never_repeat_an_existing_board_card() {
1056 let cfg = GameConfig {
1057 board: turn_board(),
1058 pot: Chips::whole(100),
1059 effective_stack: Chips::whole(200),
1060 bet_sizes: vec![1.0],
1061 max_raises: 0,
1062 suit_isomorphism: false,
1063 };
1064 let tree = build_tree(&cfg).unwrap();
1065 let Node::Decision { children, .. } = &tree.root else {
1066 panic!("expected decision")
1067 };
1068 let Node::Decision {
1069 children: ip_children,
1070 ..
1071 } = &children[0]
1072 else {
1073 panic!("expected IP decision after check")
1074 };
1075 let Node::Chance {
1076 children: river_deals,
1077 } = &ip_children[0]
1078 else {
1079 panic!("expected a chance node dealing the river")
1080 };
1081 let board_set = mask_of(&turn_board());
1082 for (members, _) in river_deals {
1083 for &card in members {
1084 assert!(!mask_has(board_set, card));
1085 }
1086 }
1087 }
1088
1089 #[test]
1090 fn suit_isomorphism_groups_free_suit_cards_of_the_same_rank() {
1091 let board: Vec<Card> = ["2c", "7d", "9c"]
1093 .iter()
1094 .map(|s| s.parse::<Card>().unwrap())
1095 .collect();
1096 let cfg = GameConfig {
1097 board: board.clone(),
1098 pot: Chips::whole(100),
1099 effective_stack: Chips::whole(200),
1100 bet_sizes: vec![1.0],
1101 max_raises: 0,
1102 suit_isomorphism: true,
1103 };
1104 let tree = build_tree(&cfg).unwrap();
1105 let Node::Decision { children, .. } = &tree.root else {
1106 panic!("expected decision")
1107 };
1108 let Node::Decision {
1109 children: ip_children,
1110 ..
1111 } = &children[0]
1112 else {
1113 panic!("expected IP decision after check")
1114 };
1115 let Node::Chance { children: deals } = &ip_children[0] else {
1116 panic!("expected a chance node dealing the turn")
1117 };
1118
1119 let used = mask_of(&board);
1125 let mut seen = std::collections::HashSet::new();
1126 let mut total_members = 0;
1127 for (members, _) in deals {
1128 assert!(!members.is_empty());
1129 let ranks: std::collections::HashSet<u8> = members.iter().map(|&c| c.rank()).collect();
1130 assert_eq!(
1131 ranks.len(),
1132 1,
1133 "every class member must share the same rank"
1134 );
1135 if members.len() > 1 {
1136 for &c in members {
1137 let s = c.suit();
1138 assert!(
1139 s == 2 || s == 3,
1140 "grouped members must use a free suit (h=2, s=3)"
1141 );
1142 }
1143 }
1144 for &c in members {
1145 assert!(
1146 !mask_has(used, c),
1147 "class must not include an already-used card"
1148 );
1149 assert!(
1150 seen.insert(c),
1151 "each undealt card must appear in exactly one class"
1152 );
1153 }
1154 total_members += members.len();
1155 }
1156 assert_eq!(total_members, 52 - board.len());
1157 assert!(deals.iter().any(|(members, _)| members.len() == 2));
1160 assert!(deals.iter().all(|(members, _)| members.len() <= 2));
1162 }
1163}