chironaut 0.3.5

A poker game library for Texas Hold'em and other poker variants
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
use chironaut::{
    action::Action,
    game::Game,
    rules::GameRules,
    card::Card,
    game::GameStage,
};
use std::io::{self, Write};

fn main() {
    println!("=== CLI POKER GAME ===\n");
    
    // Create a No-Limit Hold'em game with 10/20 blinds
    let rules = GameRules::nlhe(10, 20);
    let mut game = Game::new(rules);

    // Setup players
    setup_players(&mut game);
    
    // Game loop
    let mut continue_playing = true;
    while continue_playing {
        // Start a new hand
        game.start_hand().unwrap();
        println!("\n--- NEW HAND STARTED ---");
        
        // Play the hand through all streets
        play_hand(&mut game);
        
        // Ask if players want to continue
        continue_playing = ask_continue();
    }
    
    println!("Thanks for playing!");
}

fn setup_players(game: &mut Game) {
    println!("Setting up players (2 players with 1000 chips each)");
    
    // Add players to specific seats
    game.add_player_to_seat("Player 1".to_string(), 2000, 0).unwrap();
    game.add_player_to_seat("Player 2".to_string(), 1000, 1).unwrap();
    // game.add_player_to_seat("Player 3".to_string(), 1000, 2).unwrap();
    
    println!("Players added successfully!");
}

fn play_hand(game: &mut Game) {
    // Determine if we're in heads-up (2 player) mode
    let is_heads_up = game.players.len() == 2;

    // Show blinds information – account for heads-up where the dealer is the small blind
    let sb_pos = if game.players.len() == 2 {
        // In heads-up the dealer posts the small blind
        game.dealer_position
    } else {
        find_player_seat(game, game.dealer_position + 1)
    };

    let bb_pos = if game.players.len() == 2 {
        // Big blind is the other player
        find_player_seat(game, game.dealer_position + 1)
    } else {
        find_player_seat(game, game.dealer_position + 2)
    };

    // Use the blind values from game rules for display
    println!(
        "Blinds: {} (small blind, {}), {} (big blind, {})",
        game.players[sb_pos].name,
        game.rules.small_blind,
        game.players[bb_pos].name,
        game.rules.big_blind
    );

    // For heads-up play, verify that the SB (dealer) acts first preflop
    if is_heads_up && game.current_position != sb_pos {
        println!("Adjusting play order for heads-up: SB acts first preflop");
        game.current_position = sb_pos;
    }
    
    // Play preflop
    println!("\n--- PREFLOP ---");
    println!("Pot: {}", game.pot);
    
    // Play the betting round using library's round control
    play_street(game);
    print_player_chips(game);
    
    // Check if hand is over early
    if is_hand_over_early(game) {
        handle_early_end(game);
        return;
    }
    
    // Check game stage - if we're already at showdown due to all-in,
    // the library has handled it
    if matches!(game.stage, GameStage::Showdown) {
        resolve_showdown(game);
        return;
    }
    
    // For postflop streets, we want small blind to act first
    // Make sure postflop play starts with first active player after dealer
    if is_heads_up && game.current_position != sb_pos && game.stage == GameStage::Flop {
        println!("Adjusting play order for postflop: SB acts first");
        game.current_position = sb_pos;
    }
    
    // Play flop
    game.next_street().unwrap();
    println!("\n--- FLOP ---");
    println!("Community cards: {}", format_community_cards(&game.community_cards));
    println!("Pot: {}", game.pot);
    
    // Play flop betting round
    play_street(game);
    print_player_chips(game);
    
    // Check if hand is over
    if is_hand_over_early(game) {
        handle_early_end(game);
        return;
    }
    
    // Check game stage - if we're already at showdown due to all-in,
    // the library has handled it
    if matches!(game.stage, GameStage::Showdown) {
        resolve_showdown(game);
        return;
    }
    
    // Play turn
    game.next_street().unwrap();
    println!("\n--- TURN ---");
    println!("Community cards: {}", format_community_cards(&game.community_cards));
    println!("Pot: {}", game.pot);
    
    // Play turn betting round
    play_street(game);
    print_player_chips(game);
    
    // Check if hand is over
    if is_hand_over_early(game) {
        handle_early_end(game);
        return;
    }
    
    // Check game stage - if we're already at showdown due to all-in,
    // the library has handled it
    if matches!(game.stage, GameStage::Showdown) {
        resolve_showdown(game);
        return;
    }
    
    // Play river
    game.next_street().unwrap();
    println!("\n--- RIVER ---");
    println!("Community cards: {}", format_community_cards(&game.community_cards));
    println!("Pot: {}", game.pot);
    
    // Play river betting round
    play_street(game);
    print_player_chips(game);
    
    // Show results and award pot
    resolve_showdown(game);
}

// Helper function to find the next available player position
fn find_player_seat(game: &Game, pos: usize) -> usize {
    pos % game.players.len()
}

// Check if the hand ended early (only one player left)
fn is_hand_over_early(game: &Game) -> bool {
    game.players.iter().filter(|p| !p.is_folded).count() <= 1
}

// Handle an early end to the hand (when only one player remains)
fn handle_early_end(game: &mut Game) {
    // Find the remaining player
    let winner = game.players.iter()
        .position(|p| !p.is_folded)
        .expect("Should have at least one player not folded");
    
    // Award the pot to the winner
    let pot_amount = game.pot;
    game.players[winner].chips += pot_amount;
    
    println!("\n--- HAND ENDED EARLY ---");
    println!("{} wins {} chips (all others folded)", 
        game.players[winner].name, pot_amount);
    
    // Reset game pot
    game.pot = 0;
}

// Play a single betting round
fn play_street(game: &mut Game) {
    // Show community cards at start of each street's betting
    if !game.community_cards.is_empty() {
        println!("Community cards: {}", format_community_cards(&game.community_cards));
    }
    
    // Continue until the betting round is complete
    while !game.is_round_complete() {
        let current_position = game.current_position;
        let player_name = game.players[current_position].name.clone();
        let player_chips = game.players[current_position].chips;
        let player_bet_amount = game.players[current_position].bet_amount;
        let player_seat = game.players[current_position].seat_position;
        
        println!("\n{}'s turn (seat {})", player_name, player_seat);
        println!("Your cards: {}", game.players[current_position].hand);
        
        // Show community cards before each player's action for reference
        if !game.community_cards.is_empty() {
            println!("Community cards: {}", format_community_cards(&game.community_cards));
        }
        
        let action = get_player_action(game);
        
        match game.handle_action(action.clone()) {
            Ok(_) => {
                // Display player-friendly action description
                match action {
                    Action::Fold => println!("{} folds", player_name),
                    Action::Bet(amount) => {
                        // Translate bet amounts to poker terminology
                        if amount == 0 {
                            println!("{} checks", player_name);
                        }
                        else if player_bet_amount + amount == game.current_bet {
                            println!("{} calls", player_name);
                        }
                        else if amount == player_chips {
                            println!("{} goes all-in with {}", player_name, amount);
                        }
                        else if game.current_bet == 0 {
                            println!("{} bets {}", player_name, amount);
                        }
                        else {
                            println!("{} raises to {}", player_name, player_bet_amount + amount);
                        }
                    },
                    Action::Post(amount) => println!("{} posts {}", player_name, amount),
                }
                
                // If we've moved to showdown, break out of the loop
                if matches!(game.stage, GameStage::Showdown) {
                    break;
                }
            },
            Err(e) => {
                println!("Invalid action: {}. Please try again.", e);
                continue;
            }
        }
    }
}

// Helper function to determine available actions
fn get_player_action(game: &Game) -> Action {
    let current_player = &game.players[game.current_position];
    let options = get_available_actions(game);
    
    println!("Available actions:");
    for (i, action) in options.iter().enumerate() {
        match action {
            Action::Fold => println!("{}. Fold", i + 1),
            Action::Bet(amount) => {
                // Translate to poker terminology for display
                if *amount == 0 {
                    println!("{}. Check", i + 1);
                }
                else if current_player.bet_amount + *amount == game.current_bet {
                    println!("{}. Call ({})", i + 1, amount);
                }
                else if *amount == current_player.chips {
                    println!("{}. All-In ({})", i + 1, amount);
                }
                else if game.current_bet == 0 {
                    println!("{}. Bet ({})", i + 1, amount);
                }
                else {
                    println!("{}. Raise to ({})", i + 1, current_player.bet_amount + *amount);
                }
            },
            Action::Post(amount) => println!("{}. Post {}", i + 1, amount),
        }
    }
    
    loop {
        print!("> ");
        io::stdout().flush().unwrap();
        
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let input = input.trim();
        
        // Parse the input
        if let Ok(choice) = input.parse::<usize>() {
            if choice > 0 && choice <= options.len() {
                return options[choice - 1].clone();
            } else {
                println!("Invalid choice. Please enter a number between 1 and {}", options.len());
            }
        } else {
            println!("Invalid input. Please enter a number.");
        }
    }
}

// Helper function to determine available actions
fn get_available_actions(game: &Game) -> Vec<Action> {
    let current_player = &game.players[game.current_position];
    let mut actions = Vec::new();
    
    // Fold is always available
    actions.push(Action::Fold);
    
    // Check if player can check (only if they've already matched the current bet)
    // This prevents SB from checking preflop - they must call the BB's bet
    let is_preflop = game.stage == GameStage::Preflop;
    if is_preflop && game.players.len() == 2 && current_player.bet_amount == game.rules.small_blind {
        // Small blind can't check preflop - must call the difference to BB
        // Don't add "check" option
    } else if game.current_bet == current_player.bet_amount {
        // Can check only if bet amounts are truly equal
        actions.push(Action::Bet(0)); // Check is a bet of 0
    }
    
    // Call if there's a bet to call
    if game.current_bet > current_player.bet_amount {
        let call_amount = game.current_bet - current_player.bet_amount;
        if call_amount <= current_player.chips {
            actions.push(Action::Bet(call_amount)); // Call is a bet equal to the difference
        }
    }
    
    // Bet if no one has bet yet
    if game.current_bet == 0 {
        let min_bet = game.rules.big_blind;
        if current_player.chips > min_bet {
            actions.push(Action::Bet(min_bet));
        }
    }
    
    // Raise if someone has bet
    if game.current_bet > 0 && current_player.chips > (game.current_bet - current_player.bet_amount) {
        let min_raise = game.current_bet * 2 - current_player.bet_amount;
        if current_player.chips > min_raise {
            actions.push(Action::Bet(min_raise));
        }
    }
    
    // All-in is available if player has chips
    if current_player.chips > 0 {
        // Only add all-in as a distinct option if it's not already covered
        let all_in_amount = current_player.chips;
        if !actions.iter().any(|a| matches!(a, Action::Bet(amount) if *amount == all_in_amount)) {
            actions.push(Action::Bet(all_in_amount));
        }
    }
    
    actions
}

fn is_hand_over(game: &Game) -> bool {
    // A hand is over if there's only one player left or we've completed the river
    game.players.iter().filter(|p| !p.is_folded).count() <= 1 
        || matches!(game.stage, GameStage::Showdown)
}

// Resolve the showdown and award pot to winner(s)
fn resolve_showdown(game: &mut Game) {
    println!("\n--- HAND RESULTS ---");
    
    // Show all community cards
    if !game.community_cards.is_empty() {
        println!("Community cards: {}", format_community_cards(&game.community_cards));
    }
    
    // Show players' hands and results
    for player in &game.players {
        if player.is_folded {
            println!("{} folded", player.name);
        } else {
            println!("{}: {} (Chips: {})", 
                player.name, 
                player.hand,
                player.chips);
        }
    }
    
    // Get active (non-folded) players
    let active_players: Vec<_> = game.players.iter()
        .enumerate()
        .filter(|(_, p)| !p.is_folded)
        .collect();
    
    // Capture pot amount before any evaluation/distribution
    let pot_amount = game.pot;
    
    if active_players.len() == 1 {
        // Only one player left
        let (winner_idx, _) = active_players[0];
        
        // Award the pot
        game.players[winner_idx].chips += pot_amount;
        
        println!("\n{} wins {} chips (all others folded)", 
            game.players[winner_idx].name, pot_amount);
    }
    else if active_players.len() > 1 {
        // Use the game's built-in hand evaluation
        let (winners, _best_hands) = game.evaluate_winners_without_paying();
        
        if winners.is_empty() {
            println!("\nNo winners determined!");
            return;
        }
        
        // Calculate pot split (simple even split for now)
        let share = pot_amount / winners.len() as u32;
        let remainder = pot_amount % winners.len() as u32;
        
        // Award to each winner and explicitly track actual awards
        for (i, &winner_idx) in winners.iter().enumerate() {
            let mut amount = share;
            if i == 0 {
                amount += remainder; // First winner gets any odd chips
            }
            
            game.players[winner_idx].chips += amount;
            
            println!("\n{} wins {} chips with best hand", 
                game.players[winner_idx].name, amount);
        }
        
        // Double-check total awarded equals pot
        assert_eq!(share * winners.len() as u32 + remainder, pot_amount,
                   "Pot distribution error: awarded {} of {} chips", 
                   share * winners.len() as u32 + remainder, pot_amount);
    }
    
    // Reset game pot
    game.pot = 0;
}

fn ask_continue() -> bool {
    println!("\nPlay another hand? (y/n)");
    loop {
        print!("> ");
        io::stdout().flush().unwrap();
        
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let input = input.trim().to_lowercase();
        
        match input.as_str() {
            "y" | "yes" => return true,
            "n" | "no" => return false,
            _ => println!("Please enter 'y' or 'n'"),
        }
    }
}

fn format_community_cards(cards: &[Card]) -> String {
    cards.iter()
        .map(|card| format!("{}", card))
        .collect::<Vec<_>>()
        .join(" ")
}

// Print out each player's chip count
fn print_player_chips(game: &Game) {
    println!("\n--- CHIP COUNTS ---");
    for player in &game.players {
        println!("{}: {} chips", player.name, player.chips);
    }
}