rs_poker 5.0.0

A library to help with any Rust code dealing with poker. This includes card values, suits, hands, hand ranks, 5 card hand strength calculation, 7 card hand strength calulcation, and monte carlo game simulation helpers.
Documentation
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
//! Action validation and filtering for CFR agents.
//!
//! This module provides centralized validation logic for filtering actions
//! generated by action generators. It handles:
//! - Removing invalid actions (e.g., fold when nothing to call)
//! - Removing equivalent actions (e.g., Bet(x) that equals Call amount)
//! - Enforcing raise caps (read from GameState.max_raises_per_round)

use super::action_generator::ActionVec;
use crate::arena::{GameState, action::AgentAction};

/// Epsilon for floating point comparisons.
const EPSILON: f32 = 0.01;

/// Main entry point - validate and filter actions.
///
/// Applies all validation filters in order:
/// 1. Remove invalid fold (when nothing to call)
/// 2. Remove call-equivalent bets (when Call exists)
/// 3. Remove all-in-equivalent bets (when AllIn exists)
/// 4. Remove duplicate bet amounts
/// 5. Remove raises when capped (reads max_raises_per_round from GameState)
pub fn validate_actions(actions: impl Into<ActionVec>, game_state: &GameState) -> ActionVec {
    let mut actions = actions.into();

    actions = filter_invalid_fold(actions, game_state);
    actions = filter_call_equivalents(actions, game_state);
    actions = filter_all_in_equivalents(actions, game_state);
    actions = filter_duplicate_bets(actions);
    actions = filter_raises_when_capped(actions, game_state);

    actions
}

/// Remove Fold when there's nothing to call (current_round_bet == player's bet).
///
/// Folding when there's nothing to call is always suboptimal - you'd just check instead.
pub fn filter_invalid_fold(actions: impl Into<ActionVec>, game_state: &GameState) -> ActionVec {
    let actions = actions.into();
    let to_call = game_state.current_round_bet() - game_state.current_round_current_player_bet();

    if to_call <= 0.0 {
        // Nothing to call, remove Fold
        actions
            .into_iter()
            .filter(|a| !matches!(a, AgentAction::Fold))
            .collect()
    } else {
        actions
    }
}

/// Remove Bet actions that are equivalent to Call when Call exists.
///
/// If we have both Call and Bet(current_bet), they're the same action.
/// Keep Call, remove the Bet.
pub fn filter_call_equivalents(actions: impl Into<ActionVec>, game_state: &GameState) -> ActionVec {
    let actions = actions.into();
    let current_bet = game_state.current_round_bet();
    let has_call = actions.iter().any(|a| matches!(a, AgentAction::Call));

    if has_call {
        actions
            .into_iter()
            .filter(|a| {
                if let AgentAction::Bet(amount) = a {
                    // Remove Bet if it's approximately equal to current bet (i.e., a call)
                    (amount - current_bet).abs() >= EPSILON
                } else {
                    true
                }
            })
            .collect()
    } else {
        actions
    }
}

/// Remove Bet actions that are equivalent to AllIn when AllIn exists.
///
/// If we have both AllIn and Bet(all_in_amount), they're the same action.
/// Keep AllIn, remove the Bet.
pub fn filter_all_in_equivalents(
    actions: impl Into<ActionVec>,
    game_state: &GameState,
) -> ActionVec {
    let actions = actions.into();
    let all_in_amount =
        game_state.current_round_current_player_bet() + game_state.current_player_stack();
    let has_all_in = actions.iter().any(|a| matches!(a, AgentAction::AllIn));

    if has_all_in {
        actions
            .into_iter()
            .filter(|a| {
                if let AgentAction::Bet(amount) = a {
                    // Remove Bet if it's approximately equal to all-in amount
                    (amount - all_in_amount).abs() >= EPSILON
                } else {
                    true
                }
            })
            .collect()
    } else {
        actions
    }
}

/// Remove duplicate Bet actions with the same amount.
///
/// If multiple Bet actions have the same amount, keep only the first one.
pub fn filter_duplicate_bets(actions: impl Into<ActionVec>) -> ActionVec {
    let actions = actions.into();
    let mut seen_amounts: Vec<f32> = Vec::new();
    let mut result = ActionVec::with_capacity(actions.len());

    for action in actions {
        match &action {
            AgentAction::Bet(amount) => {
                // Check if we've seen a similar amount
                let is_duplicate = seen_amounts
                    .iter()
                    .any(|seen| (seen - amount).abs() < EPSILON);
                if !is_duplicate {
                    seen_amounts.push(*amount);
                    result.push(action);
                }
            }
            _ => {
                // Non-bet actions are always kept
                result.push(action);
            }
        }
    }

    result
}

/// Remove raise bets when the raise cap has been reached.
///
/// If GameState.max_raises_per_round is set and we've reached the limit,
/// filter out Bet actions that would constitute a raise.
/// AllIn is always allowed regardless of raise cap.
pub fn filter_raises_when_capped(
    actions: impl Into<ActionVec>,
    game_state: &GameState,
) -> ActionVec {
    let actions = actions.into();
    if !game_state.is_raise_capped() {
        // No limit or haven't reached the cap yet
        return actions;
    }

    // Raises are capped - filter out any Bet that's greater than call amount
    let current_bet = game_state.current_round_bet();

    actions
        .into_iter()
        .filter(|a| {
            match a {
                AgentAction::Bet(amount) => {
                    // Keep only if it's a call (not a raise)
                    (amount - current_bet).abs() < EPSILON
                }
                AgentAction::AllIn => true, // AllIn always allowed
                _ => true,                  // Fold, Call always allowed
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::arena::GameStateBuilder;

    // Helper to create a simple game state for testing
    fn create_test_game_state() -> GameState {
        GameStateBuilder::new()
            .num_players_with_stack(2, 100.0)
            .blinds(10.0, 5.0)
            .build()
            .unwrap()
    }

    fn create_flop_game_state_with_bet(bet_amount: f32) -> GameState {
        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 500.0)
            .blinds(10.0, 5.0)
            .build()
            .unwrap();
        game_state.advance_round(); // To flop
        game_state.do_bet(bet_amount, false).unwrap();
        game_state
    }

    // === filter_invalid_fold tests ===

    #[test]
    fn test_fold_removed_when_nothing_to_call() {
        // On flop with no bet, there's nothing to call
        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 100.0)
            .blinds(10.0, 5.0)
            .build()
            .unwrap();
        game_state.advance_round(); // To flop, player bets are reset

        let actions = vec![AgentAction::Fold, AgentAction::Call, AgentAction::AllIn];
        let filtered = filter_invalid_fold(actions, &game_state);

        assert!(!filtered.contains(&AgentAction::Fold));
        assert!(filtered.contains(&AgentAction::Call));
        assert!(filtered.contains(&AgentAction::AllIn));
    }

    #[test]
    fn test_fold_kept_when_facing_bet() {
        let game_state = create_flop_game_state_with_bet(30.0);

        let actions = vec![AgentAction::Fold, AgentAction::Call, AgentAction::AllIn];
        let filtered = filter_invalid_fold(actions, &game_state);

        assert!(filtered.contains(&AgentAction::Fold));
    }

    // === filter_call_equivalents tests ===

    #[test]
    fn test_bet_equal_to_call_removed_when_call_exists() {
        let game_state = create_flop_game_state_with_bet(30.0);
        let call_amount = game_state.current_round_bet();

        let actions = vec![
            AgentAction::Call,
            AgentAction::Bet(call_amount),
            AgentAction::Bet(50.0),
        ];
        let filtered = filter_call_equivalents(actions, &game_state);

        assert!(filtered.contains(&AgentAction::Call));
        assert!(filtered.iter().any(|a| matches!(a, AgentAction::Bet(50.0))));
        // The Bet(30.0) should be removed
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_bet_equal_to_call_kept_when_no_call() {
        let game_state = create_flop_game_state_with_bet(30.0);
        let call_amount = game_state.current_round_bet();

        // No Call action, just Bet(call_amount)
        let actions = vec![AgentAction::Fold, AgentAction::Bet(call_amount)];
        let filtered = filter_call_equivalents(actions, &game_state);

        // Should keep the Bet since there's no Call to dedupe against
        assert_eq!(filtered.len(), 2);
    }

    // === filter_all_in_equivalents tests ===

    #[test]
    fn test_bet_equal_to_all_in_removed_when_all_in_exists() {
        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 100.0)
            .blinds(10.0, 5.0)
            .build()
            .unwrap();
        game_state.advance_round();

        // Player's all-in amount
        let all_in =
            game_state.current_round_current_player_bet() + game_state.current_player_stack();

        let actions = vec![
            AgentAction::AllIn,
            AgentAction::Bet(all_in),
            AgentAction::Bet(50.0),
        ];
        let filtered = filter_all_in_equivalents(actions, &game_state);

        assert!(filtered.contains(&AgentAction::AllIn));
        assert!(filtered.iter().any(|a| matches!(a, AgentAction::Bet(50.0))));
        // The Bet(all_in) should be removed
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_bet_less_than_all_in_kept() {
        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 100.0)
            .blinds(10.0, 5.0)
            .build()
            .unwrap();
        game_state.advance_round();

        let actions = vec![AgentAction::AllIn, AgentAction::Bet(50.0)];
        let filtered = filter_all_in_equivalents(actions, &game_state);

        assert!(filtered.contains(&AgentAction::AllIn));
        assert!(filtered.iter().any(|a| matches!(a, AgentAction::Bet(50.0))));
        assert_eq!(filtered.len(), 2);
    }

    // === filter_duplicate_bets tests ===

    #[test]
    fn test_duplicate_bet_amounts_removed() {
        let actions = vec![
            AgentAction::Fold,
            AgentAction::Bet(30.0),
            AgentAction::Bet(30.0),
            AgentAction::Bet(50.0),
        ];
        let filtered = filter_duplicate_bets(actions);

        assert!(filtered.contains(&AgentAction::Fold));
        // Should have only one Bet(30.0)
        let bet_30_count = filtered
            .iter()
            .filter(|a| matches!(a, AgentAction::Bet(x) if (*x - 30.0).abs() < EPSILON))
            .count();
        assert_eq!(bet_30_count, 1);
        assert_eq!(filtered.len(), 3); // Fold + Bet(30) + Bet(50)
    }

    #[test]
    fn test_different_bet_amounts_kept() {
        let actions = vec![
            AgentAction::Bet(20.0),
            AgentAction::Bet(30.0),
            AgentAction::Bet(50.0),
        ];
        let filtered = filter_duplicate_bets(actions);

        assert_eq!(filtered.len(), 3);
    }

    // === filter_raises_when_capped tests ===

    #[test]
    fn test_raises_removed_when_capped() {
        let mut game_state = create_flop_game_state_with_bet(30.0);
        game_state.round_data.total_raise_count = 3;
        game_state.max_raises_per_round = Some(3);

        let current_bet = game_state.current_round_bet();
        let actions = vec![
            AgentAction::Fold,
            AgentAction::Bet(current_bet), // Call-equivalent
            AgentAction::Bet(60.0),        // Raise
            AgentAction::AllIn,
        ];
        let filtered = filter_raises_when_capped(actions, &game_state);

        assert!(filtered.contains(&AgentAction::Fold));
        assert!(filtered.contains(&AgentAction::AllIn));
        // The call-equivalent Bet should be kept
        assert!(
            filtered
                .iter()
                .any(|a| matches!(a, AgentAction::Bet(x) if (*x - current_bet).abs() < EPSILON))
        );
        // The raise Bet(60.0) should be removed
        assert!(
            !filtered
                .iter()
                .any(|a| matches!(a, AgentAction::Bet(x) if (*x - 60.0).abs() < EPSILON))
        );
    }

    #[test]
    fn test_all_in_kept_when_capped() {
        let mut game_state = create_flop_game_state_with_bet(30.0);
        game_state.round_data.total_raise_count = 3;
        game_state.max_raises_per_round = Some(3);

        let actions = vec![AgentAction::Fold, AgentAction::AllIn];
        let filtered = filter_raises_when_capped(actions, &game_state);

        assert!(filtered.contains(&AgentAction::AllIn));
    }

    #[test]
    fn test_raises_kept_when_not_capped() {
        let mut game_state = create_flop_game_state_with_bet(30.0);
        game_state.round_data.total_raise_count = 2;
        game_state.max_raises_per_round = Some(3);

        let actions = vec![
            AgentAction::Fold,
            AgentAction::Bet(60.0),
            AgentAction::AllIn,
        ];
        let filtered = filter_raises_when_capped(actions, &game_state);

        // All should be kept since we haven't hit the cap
        assert_eq!(filtered.len(), 3);
    }

    #[test]
    fn test_raises_kept_when_no_limit() {
        let mut game_state = create_flop_game_state_with_bet(30.0);
        game_state.round_data.total_raise_count = 10;
        game_state.max_raises_per_round = None;

        let actions = vec![
            AgentAction::Fold,
            AgentAction::Bet(60.0),
            AgentAction::AllIn,
        ];
        let filtered = filter_raises_when_capped(actions, &game_state);

        // All should be kept since there's no limit
        assert_eq!(filtered.len(), 3);
    }

    // === Integration tests ===

    #[test]
    fn test_full_validation_pipeline() {
        let mut game_state = create_flop_game_state_with_bet(30.0);
        game_state.round_data.total_raise_count = 2;
        game_state.max_raises_per_round = Some(3);

        let current_bet = game_state.current_round_bet();
        let all_in =
            game_state.current_round_current_player_bet() + game_state.current_player_stack();

        let actions = vec![
            AgentAction::Fold,
            AgentAction::Call,
            AgentAction::Bet(current_bet), // Duplicate of Call
            AgentAction::Bet(50.0),
            AgentAction::Bet(50.0),   // Duplicate
            AgentAction::Bet(all_in), // Duplicate of AllIn
            AgentAction::AllIn,
        ];

        let filtered = validate_actions(actions, &game_state);

        // Should have: Fold, Call, Bet(50), AllIn
        assert!(filtered.contains(&AgentAction::Fold));
        assert!(filtered.contains(&AgentAction::Call));
        assert!(filtered.contains(&AgentAction::AllIn));
        // Only one Bet(50)
        let bet_50_count = filtered
            .iter()
            .filter(|a| matches!(a, AgentAction::Bet(x) if (*x - 50.0).abs() < EPSILON))
            .count();
        assert_eq!(bet_50_count, 1);
        // No Bet(current_bet) or Bet(all_in)
        assert!(
            !filtered
                .iter()
                .any(|a| matches!(a, AgentAction::Bet(x) if (*x - current_bet).abs() < EPSILON))
        );
    }

    // === Edge case tests ===

    #[test]
    fn test_all_in_equals_sizing() {
        // When 66% pot equals stack, AllIn should win
        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 50.0)
            .blinds(10.0, 5.0)
            .build()
            .unwrap();
        game_state.advance_round();

        let all_in =
            game_state.current_round_current_player_bet() + game_state.current_player_stack();

        let actions = vec![
            AgentAction::Call,
            AgentAction::Bet(all_in), // Equals AllIn
            AgentAction::AllIn,
        ];
        let filtered = filter_all_in_equivalents(actions, &game_state);

        assert!(filtered.contains(&AgentAction::AllIn));
        // Bet(all_in) should be removed
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_empty_actions_after_filtering() {
        // This shouldn't happen in practice, but let's make sure we don't panic
        let game_state = create_test_game_state();

        let actions = vec![];
        let filtered = validate_actions(actions, &game_state);

        assert!(filtered.is_empty());
    }

    #[test]
    fn test_player_already_all_in() {
        // When player has no stack left, only Call/check makes sense
        // Start with valid stacks and simulate going all-in by modifying state
        let mut game_state = GameStateBuilder::new()
            .stacks(vec![100.0, 10.0])
            .blinds(10.0, 5.0)
            .build()
            .unwrap();
        game_state.advance_round(); // Starting -> Ante
        game_state.advance_round(); // Ante -> Deal Preflop
        game_state.advance_round(); // Deal -> Preflop

        // Player 1 (SB) goes all-in by betting their remaining stack
        game_state.do_bet(5.0, true).unwrap(); // SB posts 5
        game_state.do_bet(10.0, true).unwrap(); // BB posts 10
        // Now player 0 acts - they call (10 to match BB)
        game_state.do_bet(10.0, false).unwrap();
        // Player 1 acts - they're already in for 5, have 5 left, let them go all-in
        game_state.do_bet(10.0, false).unwrap(); // Go all-in

        let actions = vec![AgentAction::Fold, AgentAction::Call];

        // This should work without panicking
        let filtered = validate_actions(actions, &game_state);
        assert!(!filtered.is_empty());
    }
}