fn generate_deck(&mut self) {
self.cards.clear();
for i in 0..NUM_CARDS {
self.cards.push(Card::new(i));
}
}
fn shuffle(&mut self) {
self.cards.shuffle(&mut self.rng);
}
fn deal(&mut self) -> Card {
self.cards.pop().expect("No more cards in the deck")
}
fn reset(&mut self) {
self.generate_deck();
self.shuffle();
}
}
// Hand evaluation
struct HandEvaluator;
impl HandEvaluator {
fn evaluate_hand(hand: &[Card], community_cards: &[Card]) -> u32 {
// Concatenate the hand and community cards
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
code
// Map cards to integers
let card_ints: Vec<u8> = all_cards.iter().map(|card| Self::card_to_int(*card)).collect();
// Use a simple evaluator for the hand
Self::evaluate_7_card_hand(&card_ints)
}
// Map a card to its unique integer representation
fn card_to_int(card: Card) -> u8 {
let rank_primes = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
];
let suit_bits = [0x10, 0x20, 0x40, 0x80]; // Using NUM_SUITS
let rank_prime = rank_primes[card.rank];
let suit_bit = suit_bits[card.suit];
(rank_prime as u8) | suit_bit
}
// Evaluate a 7-card hand
fn evaluate_7_card_hand(cards: &[u8]) -> u32 {
let mut best_rank = u32::MAX;
// Generate all combinations of 5 cards out of 7
for combo in cards.iter().combinations(5) {
let hand = [combo[0], combo[1], combo[2], combo[3], combo[4]];
let rank = Self::evaluate_5_card_hand(&hand);
if rank < best_rank {
best_rank = rank;
}
}
best_rank
}
fn evaluate_5_card_hand(cards: &[&u8]) -> u32 {
// Simple hand evaluator using counts of ranks and suits
let mut rank_counts = [0u8; NUM_RANKS];
let mut suit_counts = [0u8; NUM_SUITS];
for &&card in cards {
// Extract rank and suit from card integer
let rank_prime = (card & 0x0F) as usize;
let suit_bit = card & 0xF0;
// Map rank prime back to rank index
let rank_index = match rank_prime {
2 => 0,
3 => 1,
5 => 2,
7 => 3,
11 => 4,
13 => 5,
17 => 6,
19 => 7,
23 => 8,
29 => 9,
31 => 10,
37 => 11,
41 => 12,
_ => continue,
};
rank_counts[rank_index] += 1;
// Map suit bit back to suit index
let suit_index = match suit_bit {
0x10 => 0,
0x20 => 1,
0x40 => 2,
0x80 => 3,
_ => continue,
};
suit_counts[suit_index] += 1;
}
// Determine hand strength
let is_flush = suit_counts.iter().any(|&count| count >= 5);
let mut ranks: Vec<u8> = rank_counts.iter().cloned().filter(|&count| count > 0).collect();
ranks.sort_unstable_by(|a, b| b.cmp(a)); // Sort counts descending
let hand_rank = if is_flush && Self::is_straight(&rank_counts) {
1 // Straight Flush
} else if ranks[0] == 4 {
2 // Four of a Kind
} else if ranks[0] == 3 && ranks[1] >= 2 {
3 // Full House
} else if is_flush {
4 // Flush
} else if Self::is_straight(&rank_counts) {
5 // Straight
} else if ranks[0] == 3 {
6 // Three of a Kind
} else if ranks[0] == 2 && ranks[1] == 2 {
7 // Two Pair
} else if ranks[0] == 2 {
8 // One Pair
} else {
9 // High Card
};
hand_rank
}
fn is_straight(rank_counts: &[u8; NUM_RANKS]) -> bool {
let mut consecutive = 0;
// Handle Ace-low straight
let counts = [&rank_counts[..], &[rank_counts[0]]].concat();
for &count in counts.iter() {
if count > 0 {
consecutive += 1;
if consecutive >= 5 {
return true;
}
} else {
consecutive = 0;
}
}
false
}
}
// Player structure
struct Player {
id: usize,
stack: i32,
bet: i32,
active: bool,
all_in: bool,
hand: Vec,
}
impl Player {
fn new(id: usize, stack: i32) -> Player {
Player {
id,
stack,
bet: 0,
active: true,
all_in: false,
hand: Vec::with_capacity(2),
}
}
// Example agent function
fn example_agent_function(_player_id: usize, observation: &str) -> Action {
// Simple agent: Randomly choose between Call and Raise if stack allows
let mut rng = thread_rng();
let choice: f64 = rng.gen();
if observation.contains("Min Call: 0") {
if choice < 0.5 {
Action::Call // Check
} else {
Action::Raise
}
} else if !observation.contains("RAISE") {
if choice < 0.5 {
Action::Call // Call
} else {
Action::Raise
}
} else {
Action::Fold
}
}
// Main function
fn main() {
let agent_function = Box::new(example_agent_function);
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_game();
println!("Game simulation completed. See 'game_log.txt' for details.");
}
do not represent observation/actions as strings
Assistant
To modify the PokerEnvironment so that observations and actions are not represented as strings, we need to make a few changes. This involves representing these elements using structured data types instead, improving efficiency and maintainability.
Let's go through the modifications needed:
Observation Representation:
Instead of creating a string for the player's observation, define a struct that encapsulates all the necessary information the player needs to make decisions.
Action Representation:
Use enums and other types to represent actions more explicitly, avoiding the need for string comparisons.
Here's how you can modify the code:
Modifying Observation
Replace the observation string construction (fn get_observation) with a struct:
Use the Action enum directly instead of parsing a string:
rust
User
full updated code please
Assistant
Below is the updated code with structured data types for observations and actions instead of using strings. The changes improve the code's clarity, safety, and maintainability by employing Rust's type system:
rust
User
remove gamelog file functionality
Assistant
To remove the functionality associated with logging to a file in the PokerEnvironment, you need to remove any code related to creating, writing, or managing the log file. Here’s how you can update the code:
Remove the log_file Field:
Delete the log_file field from the PokerEnvironment struct.
Remove Log File Initialization:
Eliminate the initialization of the log_file field in initialize_game.
Remove Logging Functions:
Remove the log_game_state and log_action methods.
Here's the revised version of your code with these changes implemented:
rust
User
⣿
Progress
⬤⬤⬤
Standard Error
Compiling playground v0.0.1 (/playground)
warning: unused variable: player_id
--> src/main.rs:516:27
|
516 | fn example_agent_function(player_id: usize, observation: &Observation) -> Action {
| ^^^^^^^^^ help: if this is intentional, prefix it with an underscore: _player_id
|
= note: #[warn(unused_variables)] on by default
warning: field id is never read
--> src/main.rs:189:5
|
188 | struct Player {
| ------ field in this struct
189 | id: usize,
| ^^
|
= note: #[warn(dead_code)] on by default
warning: playground (bin "playground") generated 3 warnings
Finished dev profile [unoptimized + debuginfo] target(s) in 0.91s
Running target/debug/playground
Standard Output
Assistant
You're seeing warnings from the Rust compiler about unused variables and fields that are never read. These warnings don't prevent your code from running, but they indicate areas of the code that might need attention. Here's a breakdown of the warnings and suggestions for addressing them:
Unused Variable: player_id:
In your example_agent_function, the variable player_id is declared but never used. If you don't plan to use it, you can rename it to _player_id to clearly indicate that it's intentionally unused, suppressing the warning.
The id field in the Player struct is declared but not used anywhere in the code. If this field is not needed, the best option is to remove it from the struct. However, if you plan to use it later (e.g., for identifying players), you can leave it as is.
Unused Fields in Observation Struct:
The fields player_id, hand, community_cards, pot, current_bet, and stack in the Observation struct are declared but never read. This usually indicates that something is missing in your logic where these fields should be accessed, or these fields might be unnecessary if your function logic doesn't need them.
Here's how you can address the warnings:
rust
// Example agent function with unused variable handled
fn example_agent_function(_player_id: usize, observation: &Observation) -> Action {
let mut rng = thread_rng();
let choice: f64 = rng.gen();
if observation.min_call == 0 {
if choice < 0.5 {
Action::Call // Check
} else {
Action::Raise
}
} else if observation.phase != Phase::Showdown {
if choice < 0.5 {
Action::Call
} else {
Action::Raise
}
} else {
Action::Fold
}
}
// Reduced Player struct if id is not needed now
struct Player {
stack: i32,
bet: i32,
active: bool,
all_in: bool,
hand: Vec<Card>,
}
// Reduced Observation struct if fields are not needed now
struct Observation {
min_call: i32,
phase: Phase,
}
User
full updated code please
Assistant
Sure, let's update the code to address the warnings by marking unused variables properly or removing unnecessary fields if they are not going to be used. If you anticipate using any of these fields later, it's fine to keep them and ignore these warnings.
Below is the modified version of your Rust poker environment code:
rust
User
add an agent what makes fully random moves
Assistant
To implement an agent that makes completely random moves in the poker environment, you can define a function that randomly selects an action from the available Action enum values. This agent will be very simple: it will not consider the current game state or any strategy. Here's how you can set it up:
Define a Random Agent Function:
This function will use a random number generator to pick one of the Action enum variants (Fold, Call, or Raise).
Modify the Main Function:
Use this random agent function as the decision maker in the poker environment.
Here's the complete code with the random agent function implemented:
rust
User
⣿
Standard Error
Compiling playground v0.0.1 (/playground)
warning: constant NUM_PLAYERS is never used
--> src/lib.rs:6:7
|
6 | const NUM_PLAYERS: usize = 9;
| ^^^^^^^^^^^
|
= note: #[warn(dead_code)] on by default
warning: constant NUM_CARDS is never used
--> src/lib.rs:7:7
|
7 | const NUM_CARDS: usize = 52;
| ^^^^^^^^^
warning: constant NUM_RANKS is never used
--> src/lib.rs:8:7
|
8 | const NUM_RANKS: usize = 13;
| ^^^^^^^^^
warning: constant NUM_SUITS is never used
--> src/lib.rs:9:7
|
9 | const NUM_SUITS: usize = 4;
| ^^^^^^^^^
warning: constant MAX_STACK is never used
--> src/lib.rs:10:7
|
10 | const MAX_STACK: i32 = 10000;
| ^^^^^^^^^
warning: constant SMALL_BLIND is never used
--> src/lib.rs:11:7
|
11 | const SMALL_BLIND: i32 = 50;
| ^^^^^^^^^^^
warning: constant BIG_BLIND is never used
--> src/lib.rs:12:7
|
12 | const BIG_BLIND: i32 = 100;
| ^^^^^^^^^
warning: enum Action is never used
--> src/lib.rs:16:6
|
16 | enum Action {
| ^^^^^^
warning: struct Card is never constructed
--> src/lib.rs:24:8
|
24 | struct Card {
| ^^^^
warning: associated function new is never used
--> src/lib.rs:30:8
|
29 | impl Card {
| --------- associated function in this implementation
30 | fn new(id: usize) -> Card {
| ^^^
warning: struct Deck is never constructed
--> src/lib.rs:47:8
|
47 | struct Deck {
| ^^^^
The warnings you are seeing indicate that none of the structures, constants, or functions you have defined are being used. This usually happens when code is placed in a Rust library (lib.rs) instead of an executable (main.rs), and nothing currently uses these definitions.
To resolve these warnings, you should ensure that all of your code exists within an executable context, or invoke these definitions from other parts of a project. Let's create a proper setup for the code by ensuring it compiles and runs without warnings:
Move to main.rs: If your code is within lib.rs, move it to main.rs to ensure it's recognized as an executable.
Executable Structure: Organize the code properly in main.rs, with a correct main function that utilizes the defined structures and functions.
Here's how you can set up your main.rs:
rust
Dataset releases
Not yet included in a published release.
fn initialize_game(&mut self) {
// Initialize logging
self.log_file = Some(File::create("game_log.txt").expect("Unable to create log file"));
self.log_game_state("Game started");
// Initialize players
self.players.clear();
for i in 0..self.num_players {
self.players.push(Player::new(i, MAX_STACK));
}
// Initialize deck
self.deck.reset();
// Deal hands
let mut log_messages = vec![]; // Collect log messages
for player in &mut self.players {
player.reset();
player.hand.push(self.deck.deal());
player.hand.push(self.deck.deal());
// Collect log messages
log_messages.push(format!(
"Player {} dealt hand: {} {}",
player.id, player.hand[0], player.hand[1]
));
}
// Write log messages after the loop
for message in log_messages {
self.log_game_state(&message);
}
// Blinds
self.pot = 0;
self.min_call = BIG_BLIND;
self.last_raise = BIG_BLIND;
self.current_player = (self.dealer_position + 3) % self.num_players;
self.phase = Phase::PreFlop;
self.betting_round_over = false;
self.community_cards.clear();
self.last_aggressor = None;
// Post blinds
let small_blind_position = (self.dealer_position + 1) % self.num_players;
let big_blind_position = (self.dealer_position + 2) % self.num_players;
self.post_blind(small_blind_position, SMALL_BLIND);
self.post_blind(big_blind_position, BIG_BLIND);
}
fn play_game(&mut self) {
while !self.is_terminal() {
let player_id = self.current_player;
let player = &self.players[player_id];
if player.active && !player.all_in {
let observation = self.get_observation(player_id);
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_game();
// Close log file
self.log_file = None;
}
fn get_observation(&self, player_id: usize) -> String {
let player = &self.players[player_id];
let mut obs = String::new();
obs.push_str(&format!("PlayerID: {}\n", player_id));
obs.push_str("Hand: ");
for &card in &player.hand {
obs.push_str(&format!("{} ", card));
}
obs.push_str("\nCommunity Cards: ");
for &card in &self.community_cards {
obs.push_str(&format!("{} ", card));
}
obs.push_str(&format!(
"\nPot: {}\nCurrent Bet: {}\nMin Call: {}\nStack: {}\nPhase: {:?}\n",
self.pot, player.bet, self.min_call, player.stack, self.phase
));
obs
}
fn step(&mut self, action: Action) {
let player_id = self.current_player;
let player = &mut self.players[player_id];
if !player.active || player.all_in {
self.next_player();
return;
}
match action {
Action::Fold => {
self.handle_fold(player_id);
self.log_action(player_id, "FOLD");
}
Action::Call => {
self.handle_call(player_id);
self.log_action(player_id, "CALL");
}
Action::Raise => {
self.handle_raise(player_id);
self.log_action(player_id, "RAISE");
}
}
if self.betting_round_over {
self.advance_phase();
}
if !self.is_terminal() {
self.next_player();
}
}
fn is_terminal(&self) -> bool {
let active_count = self
.players
.iter()
.filter(|p| p.active || p.all_in)
.count();
active_count <= 1 || self.phase == Phase::Showdown
}
fn handle_fold(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
player.active = false;
self.pot += player.bet;
player.bet = 0;
}
fn handle_call(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let call_amount = self.min_call - player.bet;
let amount = std::cmp::min(call_amount, player.stack);
player.bet += amount;
player.stack -= amount;
if player.stack == 0 {
player.all_in = true;
}
}
fn handle_raise(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let raise_amount = std::cmp::max(self.last_raise * 2, self.min_call * 2);
let amount = std::cmp::min(raise_amount, player.stack);
player.bet += amount;
player.stack -= amount;
self.min_call = player.bet;
self.last_raise = amount;
self.last_aggressor = Some(player_id);
if player.stack == 0 {
player.all_in = true;
}
}
fn next_player(&mut self) {
let start_player = self.current_player;
loop {
self.current_player = (self.current_player + 1) % self.num_players;
if self.current_player == start_player {
self.betting_round_over = true;
break;
}
let player = &self.players[self.current_player];
if player.active && !player.all_in {
break;
}
}
if let Some(last_aggressor) = self.last_aggressor {
if self.current_player == last_aggressor {
self.betting_round_over = true;
}
}
}
fn advance_phase(&mut self) {
// Collect bets into the pot
for player in &mut self.players {
self.pot += player.bet;
player.bet = 0;
}
self.min_call = 0;
self.last_raise = 0;
self.betting_round_over = false;
self.last_aggressor = None;
// Advance phase
self.phase = match self.phase {
Phase::PreFlop => {
// Deal three community cards
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.log_game_state("Dealt Flop");
Phase::Flop
}
Phase::Flop => {
self.community_cards.push(self.deck.deal());
self.log_game_state("Dealt Turn");
Phase::Turn
}
Phase::Turn => {
self.community_cards.push(self.deck.deal());
self.log_game_state("Dealt River");
Phase::River
}
Phase::River => Phase::Showdown,
Phase::Showdown => Phase::Showdown,
};
self.log_game_state(&format!("Phase advanced to {:?}", self.phase));
// Reset current player to the first active player
self.current_player = (self.dealer_position + 1) % self.num_players;
while {
let player = &self.players[self.current_player];
(!player.active || player.all_in)
&& self.current_player != self.dealer_position
} {
self.current_player = (self.current_player + 1) % self.num_players;
}
}
fn resolve_game(&mut self) {
// Determine winner(s)
let active_players: Vec<_> = self
.players
.iter()
.enumerate()
.filter(|(_, p)| p.active || p.all_in)
.collect();
if active_players.len() == 1 {
// Only one player left
let (winner_id, _) = active_players[0];
let winner = &mut self.players[winner_id];
winner.stack += self.pot;
self.log_game_state(&format!(
"Player {} wins the pot of {} by default.",
winner_id, self.pot
));
return;
}
// Showdown
let mut best_rank: Option<u32> = None;
let mut winners = vec![];
for (player_id, player) in active_players {
let rank = HandEvaluator::evaluate_hand(&player.hand, &self.community_cards);
if best_rank.is_none() || rank < best_rank.unwrap() {
best_rank = Some(rank);
winners.clear();
winners.push(player_id);
} else if rank == best_rank.unwrap() {
winners.push(player_id);
}
}
let split_pot = self.pot / winners.len() as i32;
for &winner_id in &winners {
let winner = &mut self.players[winner_id];
winner.stack += split_pot;
self.log_game_state(&format!(
"Player {} wins {} with hand rank {}.",
winner_id,
split_pot,
best_rank.unwrap()
));
}
}
fn post_blind(&mut self, player_id: usize, amount: i32) {
let player = &mut self.players[player_id];
let blind_amount = std::cmp::min(amount, player.stack);
player.bet += blind_amount;
player.stack -= blind_amount;
self.pot += blind_amount;
self.min_call = std::cmp::max(self.min_call, player.bet);
if player.stack == 0 {
player.all_in = true;
}
}
fn log_game_state(&mut self, message: &str) {
if let Some(file) = &mut self.log_file {
writeln!(file, "Game State: {}", message).expect("Unable to write to log file");
}
}
fn log_action(&mut self, player_id: usize, action: &str) {
if let Some(file) = &mut self.log_file {
writeln!(file, "Player {}: {}", player_id, action)
.expect("Unable to write to log file");
}
}
fn step(&mut self, action: Action) {
let player_id = self.current_player;
let player = &mut self.players[player_id];
if !player.active || player.all_in {
self.next_player();
return;
}
match action {
Action::Fold => self.handle_fold(player_id),
Action::Call => self.handle_call(player_id),
Action::Raise => self.handle_raise(player_id),
}
if self.betting_round_over {
self.advance_phase();
}
if !self.is_terminal() {
self.next_player();
}
}
Example Agent Function
The example_agent_function now works with the Observation struct:
rust
fn example_agent_function(player_id: usize, observation: &Observation) -> Action {
let mut rng = thread_rng();
let choice: f64 = rng.gen();
if observation.min_call == 0 {
if choice < 0.5 {
Action::Call // Check
} else {
Action::Raise
}
} else if observation.phase != Phase::Showdown {
if choice < 0.5 {
Action::Call
} else {
Action::Raise
}
} else {
Action::Fold
}
}
These changes encapsulate the game's state and actions using data structures, providing clearer, more type-safe, and maintainable logic compared to handling strings directly. This approach solidifies the game logic and enables more precise decision-making in agents.
// File: poker_environment.rs
use rand::prelude::*;
use itertools::Itertools;
use std::fmt;
use std::fs::File;
use std::io::Write;
// Constants
const NUM_PLAYERS: usize = 9;
const NUM_CARDS: usize = 52;
const NUM_RANKS: usize = 13;
const NUM_SUITS: usize = 4;
const MAX_STACK: i32 = 10000;
const SMALL_BLIND: i32 = 50;
const BIG_BLIND: i32 = 100;
// Actions
#[derive(Clone, Copy, Debug)]
enum Action {
Fold,
Call,
Raise,
}
// Card representation
#[derive(Clone, Copy)]
struct Card {
rank: usize,
suit: usize,
}
impl Card {
fn new(id: usize) -> Card {
Card {
suit: id / NUM_RANKS,
rank: id % NUM_RANKS,
}
}
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let rank_strings = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"];
let suit_strings = ["h", "d", "c", "s"];
write!(f, "{}{}", rank_strings[self.rank], suit_strings[self.suit])
}
}
// Deck management
struct Deck {
cards: Vec<Card>,
rng: ThreadRng,
}
impl Deck {
fn new() -> Deck {
let mut deck = Deck {
cards: Vec::with_capacity(NUM_CARDS),
rng: thread_rng(),
};
deck.generate_deck();
deck.shuffle();
deck
}
fn generate_deck(&mut self) {
self.cards.clear();
for i in 0..NUM_CARDS {
self.cards.push(Card::new(i));
}
}
fn shuffle(&mut self) {
self.cards.shuffle(&mut self.rng);
}
fn deal(&mut self) -> Card {
self.cards.pop().expect("No more cards in the deck")
}
fn reset(&mut self) {
self.generate_deck();
self.shuffle();
}
}
// Hand evaluation
struct HandEvaluator;
impl HandEvaluator {
fn evaluate_hand(hand: &[Card], community_cards: &[Card]) -> u32 {
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
let card_ints: Vec<u8> = all_cards.iter().map(|card| Self::card_to_int(*card)).collect();
Self::evaluate_7_card_hand(&card_ints)
}
fn card_to_int(card: Card) -> u8 {
let rank_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
let suit_bits = [0x10, 0x20, 0x40, 0x80];
let rank_prime = rank_primes[card.rank];
let suit_bit = suit_bits[card.suit];
(rank_prime as u8) | suit_bit
}
fn evaluate_7_card_hand(cards: &[u8]) -> u32 {
let mut best_rank = u32::MAX;
for combo in cards.iter().combinations(5) {
let hand = [combo[0], combo[1], combo[2], combo[3], combo[4]];
let rank = Self::evaluate_5_card_hand(&hand);
if rank < best_rank {
best_rank = rank;
}
}
best_rank
}
fn evaluate_5_card_hand(cards: &[&u8]) -> u32 {
let mut rank_counts = [0u8; NUM_RANKS];
let mut suit_counts = [0u8; NUM_SUITS];
for &&card in cards {
let rank_prime = (card & 0x0F) as usize;
let suit_bit = card & 0xF0;
let rank_index = match rank_prime {
2 => 0, 3 => 1, 5 => 2, 7 => 3, 11 => 4,
13 => 5, 17 => 6, 19 => 7, 23 => 8, 29 => 9,
31 => 10, 37 => 11, 41 => 12, _ => continue,
};
rank_counts[rank_index] += 1;
let suit_index = match suit_bit {
0x10 => 0, 0x20 => 1, 0x40 => 2, 0x80 => 3, _ => continue,
};
suit_counts[suit_index] += 1;
}
let is_flush = suit_counts.iter().any(|&count| count >= 5);
let mut ranks: Vec<u8> = rank_counts.iter().cloned().filter(|&count| count > 0).collect();
ranks.sort_unstable_by(|a, b| b.cmp(a));
let hand_rank = if is_flush && Self::is_straight(&rank_counts) {
1 // Straight Flush
} else if ranks[0] == 4 {
2 // Four of a Kind
} else if ranks[0] == 3 && ranks[1] >= 2 {
3 // Full House
} else if is_flush {
4 // Flush
} else if Self::is_straight(&rank_counts) {
5 // Straight
} else if ranks[0] == 3 {
6 // Three of a Kind
} else if ranks[0] == 2 && ranks[1] == 2 {
7 // Two Pair
} else if ranks[0] == 2 {
8 // One Pair
} else {
9 // High Card
};
hand_rank
}
fn is_straight(rank_counts: &[u8; NUM_RANKS]) -> bool {
let mut consecutive = 0;
let counts = [&rank_counts[..], &[rank_counts[0]]].concat();
for &count in counts.iter() {
if count > 0 {
consecutive += 1;
if consecutive >= 5 {
return true;
}
} else {
consecutive = 0;
}
}
false
}
}
// Player structure
struct Player {
id: usize,
stack: i32,
bet: i32,
active: bool,
all_in: bool,
hand: Vec<Card>,
}
impl Player {
fn new(id: usize, stack: i32) -> Player {
Player {
id,
stack,
bet: 0,
active: true,
all_in: false,
hand: Vec::with_capacity(2),
}
}
fn reset(&mut self) {
self.bet = 0;
self.active = true;
self.all_in = false;
self.hand.clear();
}
}
// Observation structure
struct Observation {
player_id: usize,
hand: Vec<Card>,
community_cards: Vec<Card>,
pot: i32,
current_bet: i32,
min_call: i32,
stack: i32,
phase: Phase,
}
// Poker environment
struct PokerEnvironment<'a> {
num_players: usize,
players: Vec<Player>,
deck: Deck,
pot: i32,
min_call: i32,
last_raise: i32,
current_player: usize,
dealer_position: usize,
phase: Phase,
betting_round_over: bool,
community_cards: Vec<Card>,
last_aggressor: Option<usize>,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
log_file: Option<File>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
PreFlop,
Flop,
Turn,
River,
Showdown,
}
impl<'a> PokerEnvironment<'a> {
fn new(
num_players: usize,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
) -> PokerEnvironment<'a> {
let mut env = PokerEnvironment {
num_players,
players: Vec::with_capacity(num_players),
deck: Deck::new(),
pot: 0,
min_call: 0,
last_raise: 0,
current_player: 0,
dealer_position: 0,
phase: Phase::PreFlop,
betting_round_over: false,
community_cards: Vec::new(),
last_aggressor: None,
agent_function,
log_file: None,
};
env.initialize_game();
env
}
fn initialize_game(&mut self) {
self.log_file = Some(File::create("game_log.txt").expect("Unable to create log file"));
self.log_game_state("Game started");
self.players.clear();
for i in 0..self.num_players {
self.players.push(Player::new(i, MAX_STACK));
}
self.deck.reset();
let mut log_messages = vec![];
for player in &mut self.players {
player.reset();
player.hand.push(self.deck.deal());
player.hand.push(self.deck.deal());
log_messages.push(format!(
"Player {} dealt hand: {} {}",
player.id, player.hand[0], player.hand[1]
));
}
for message in log_messages {
self.log_game_state(&message);
}
self.pot = 0;
self.min_call = BIG_BLIND;
self.last_raise = BIG_BLIND;
self.current_player = (self.dealer_position + 3) % self.num_players;
self.phase = Phase::PreFlop;
self.betting_round_over = false;
self.community_cards.clear();
self.last_aggressor = None;
let small_blind_position = (self.dealer_position + 1) % self.num_players;
let big_blind_position = (self.dealer_position + 2) % self.num_players;
self.post_blind(small_blind_position, SMALL_BLIND);
self.post_blind(big_blind_position, BIG_BLIND);
}
fn play_game(&mut self) {
while !self.is_terminal() {
let player_id = self.current_player;
let player = &self.players[player_id];
if player.active && !player.all_in {
let observation = self.get_observation(player_id);
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_game();
self.log_file = None;
}
fn get_observation(&self, player_id: usize) -> Observation {
let player = &self.players[player_id];
Observation {
player_id,
hand: player.hand.clone(),
community_cards: self.community_cards.clone(),
pot: self.pot,
current_bet: player.bet,
min_call: self.min_call,
stack: player.stack,
phase: self.phase,
}
}
fn step(&mut self, action: Action) {
let player_id = self.current_player;
let player = &mut self.players[player_id];
if !player.active || player.all_in {
self.next_player();
return;
}
match action {
Action::Fold => self.handle_fold(player_id),
Action::Call => self.handle_call(player_id),
Action::Raise => self.handle_raise(player_id),
}
if self.betting_round_over {
self.advance_phase();
}
if !self.is_terminal() {
self.next_player();
}
}
fn is_terminal(&self) -> bool {
let active_count = self.players.iter().filter(|p| p.active || p.all_in).count();
active_count <= 1 || self.phase == Phase::Showdown
}
fn handle_fold(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
player.active = false;
self.pot += player.bet;
player.bet = 0;
}
fn handle_call(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let call_amount = self.min_call - player.bet;
let amount = std::cmp::min(call_amount, player.stack);
player.bet += amount;
player.stack -= amount;
if player.stack == 0 {
player.all_in = true;
}
}
fn handle_raise(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let raise_amount = std::cmp::max(self.last_raise * 2, self.min_call * 2);
let amount = std::cmp::min(raise_amount, player.stack);
player.bet += amount;
player.stack -= amount;
self.min_call = player.bet;
self.last_raise = amount;
self.last_aggressor = Some(player_id);
if player.stack == 0 {
player.all_in = true;
}
}
fn next_player(&mut self) {
let start_player = self.current_player;
loop {
self.current_player = (self.current_player + 1) % self.num_players;
if self.current_player == start_player {
self.betting_round_over = true;
break;
}
let player = &self.players[self.current_player];
if player.active && !player.all_in {
break;
}
}
if let Some(last_aggressor) = self.last_aggressor {
if self.current_player == last_aggressor {
self.betting_round_over = true;
}
}
}
fn advance_phase(&mut self) {
for player in &mut self.players {
self.pot += player.bet;
player.bet = 0;
}
self.min_call = 0;
self.last_raise = 0;
self.betting_round_over = false;
self.last_aggressor = None;
self.phase = match self.phase {
Phase::PreFlop => {
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.log_game_state("Dealt Flop");
Phase::Flop
}
Phase::Flop => {
self.community_cards.push(self.deck.deal());
self.log_game_state("Dealt Turn");
Phase::Turn
}
Phase::Turn => {
self.community_cards.push(self.deck.deal());
self.log_game_state("Dealt River");
Phase::River
}
Phase::River => Phase::Showdown,
Phase::Showdown => Phase::Showdown,
};
self.log_game_state(&format!("Phase advanced to {:?}", self.phase));
self.current_player = (self.dealer_position + 1) % self.num_players;
while {
let player = &self.players[self.current_player];
(!player.active || player.all_in) && self.current_player != self.dealer_position
} {
self.current_player = (self.current_player + 1) % self.num_players;
}
}
fn resolve_game(&mut self) {
let active_players: Vec<_> = self
.players
.iter()
.enumerate()
.filter(|(_, p)| p.active || p.all_in)
.collect();
if active_players.len() == 1 {
let (winner_id, _) = active_players[0];
let winner = &mut self.players[winner_id];
winner.stack += self.pot;
self.log_game_state(&format!(
"Player {} wins the pot of {} by default.",
winner_id, self.pot
));
return;
}
let mut best_rank: Option<u32> = None;
let mut winners = vec![];
for (player_id, player) in active_players {
let rank = HandEvaluator::evaluate_hand(&player.hand, &self.community_cards);
if best_rank.is_none() || rank < best_rank.unwrap() {
best_rank = Some(rank);
winners.clear();
winners.push(player_id);
} else if rank == best_rank.unwrap() {
winners.push(player_id);
}
}
let split_pot = self.pot / winners.len() as i32;
for &winner_id in &winners {
let winner = &mut self.players[winner_id];
winner.stack += split_pot;
self.log_game_state(&format!(
"Player {} wins {} with hand rank {}.",
winner_id,
split_pot,
best_rank.unwrap()
));
}
}
fn post_blind(&mut self, player_id: usize, amount: i32) {
let player = &mut self.players[player_id];
let blind_amount = std::cmp::min(amount, player.stack);
player.bet += blind_amount;
player.stack -= blind_amount;
self.pot += blind_amount;
self.min_call = std::cmp::max(self.min_call, player.bet);
if player.stack == 0 {
player.all_in = true;
}
}
fn log_game_state(&mut self, message: &str) {
if let Some(file) = &mut self.log_file {
writeln!(file, "Game State: {}", message).expect("Unable to write to log file");
}
}
fn log_action(&mut self, player_id: usize, action: &str) {
if let Some(file) = &mut self.log_file {
writeln!(file, "Player {}: {}", player_id, action)
.expect("Unable to write to log file");
}
}
}
// Example agent function
fn example_agent_function(player_id: usize, observation: &Observation) -> Action {
let mut rng = thread_rng();
let choice: f64 = rng.gen();
if observation.min_call == 0 {
if choice < 0.5 {
Action::Call // Check
} else {
Action::Raise
}
} else if observation.phase != Phase::Showdown {
if choice < 0.5 {
Action::Call
} else {
Action::Raise
}
} else {
Action::Fold
}
}
// Main function
fn main() {
let agent_function = Box::new(example_agent_function);
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_game();
println!("Game simulation completed. See 'game_log.txt' for details.");
}
Key Changes
Observation Struct: Introduced an Observation struct to hold all relevant game information for a player, replacing the use of strings to pass this information.
Direct Action Handling: Used the Action enum for specifying actions like Fold, Call, and Raise, avoiding string-based logic.
Simplified Agent Function: The agent function now operates with structured Observation data.
These changes ensure a cleaner, more robust, and easier-to-manage implementation, leveraging Rust's strong type system.
// File: poker_environment.rs
use rand::prelude::*;
use itertools::Itertools;
use std::fmt;
// Constants
const NUM_PLAYERS: usize = 9;
const NUM_CARDS: usize = 52;
const NUM_RANKS: usize = 13;
const NUM_SUITS: usize = 4;
const MAX_STACK: i32 = 10000;
const SMALL_BLIND: i32 = 50;
const BIG_BLIND: i32 = 100;
// Actions
#[derive(Clone, Copy, Debug)]
enum Action {
Fold,
Call,
Raise,
}
// Card representation
#[derive(Clone, Copy)]
struct Card {
rank: usize,
suit: usize,
}
impl Card {
fn new(id: usize) -> Card {
Card {
suit: id / NUM_RANKS,
rank: id % NUM_RANKS,
}
}
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let rank_strings = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"];
let suit_strings = ["h", "d", "c", "s"];
write!(f, "{}{}", rank_strings[self.rank], suit_strings[self.suit])
}
}
// Deck management
struct Deck {
cards: Vec<Card>,
rng: ThreadRng,
}
impl Deck {
fn new() -> Deck {
let mut deck = Deck {
cards: Vec::with_capacity(NUM_CARDS),
rng: thread_rng(),
};
deck.generate_deck();
deck.shuffle();
deck
}
fn generate_deck(&mut self) {
self.cards.clear();
for i in 0..NUM_CARDS {
self.cards.push(Card::new(i));
}
}
fn shuffle(&mut self) {
self.cards.shuffle(&mut self.rng);
}
fn deal(&mut self) -> Card {
self.cards.pop().expect("No more cards in the deck")
}
fn reset(&mut self) {
self.generate_deck();
self.shuffle();
}
}
// Hand evaluation
struct HandEvaluator;
impl HandEvaluator {
fn evaluate_hand(hand: &[Card], community_cards: &[Card]) -> u32 {
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
let card_ints: Vec<u8> = all_cards.iter().map(|card| Self::card_to_int(*card)).collect();
Self::evaluate_7_card_hand(&card_ints)
}
fn card_to_int(card: Card) -> u8 {
let rank_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
let suit_bits = [0x10, 0x20, 0x40, 0x80];
let rank_prime = rank_primes[card.rank];
let suit_bit = suit_bits[card.suit];
(rank_prime as u8) | suit_bit
}
fn evaluate_7_card_hand(cards: &[u8]) -> u32 {
let mut best_rank = u32::MAX;
for combo in cards.iter().combinations(5) {
let hand = [combo[0], combo[1], combo[2], combo[3], combo[4]];
let rank = Self::evaluate_5_card_hand(&hand);
if rank < best_rank {
best_rank = rank;
}
}
best_rank
}
fn evaluate_5_card_hand(cards: &[&u8]) -> u32 {
let mut rank_counts = [0u8; NUM_RANKS];
let mut suit_counts = [0u8; NUM_SUITS];
for &&card in cards {
let rank_prime = (card & 0x0F) as usize;
let suit_bit = card & 0xF0;
let rank_index = match rank_prime {
2 => 0, 3 => 1, 5 => 2, 7 => 3, 11 => 4,
13 => 5, 17 => 6, 19 => 7, 23 => 8, 29 => 9,
31 => 10, 37 => 11, 41 => 12, _ => continue,
};
rank_counts[rank_index] += 1;
let suit_index = match suit_bit {
0x10 => 0, 0x20 => 1, 0x40 => 2, 0x80 => 3, _ => continue,
};
suit_counts[suit_index] += 1;
}
let is_flush = suit_counts.iter().any(|&count| count >= 5);
let mut ranks: Vec<u8> = rank_counts.iter().cloned().filter(|&count| count > 0).collect();
ranks.sort_unstable_by(|a, b| b.cmp(a));
let hand_rank = if is_flush && Self::is_straight(&rank_counts) {
1 // Straight Flush
} else if ranks[0] == 4 {
2 // Four of a Kind
} else if ranks[0] == 3 && ranks[1] >= 2 {
3 // Full House
} else if is_flush {
4 // Flush
} else if Self::is_straight(&rank_counts) {
5 // Straight
} else if ranks[0] == 3 {
6 // Three of a Kind
} else if ranks[0] == 2 && ranks[1] == 2 {
7 // Two Pair
} else if ranks[0] == 2 {
8 // One Pair
} else {
9 // High Card
};
hand_rank
}
fn is_straight(rank_counts: &[u8; NUM_RANKS]) -> bool {
let mut consecutive = 0;
let counts = [&rank_counts[..], &[rank_counts[0]]].concat();
for &count in counts.iter() {
if count > 0 {
consecutive += 1;
if consecutive >= 5 {
return true;
}
} else {
consecutive = 0;
}
}
false
}
}
// Player structure
struct Player {
id: usize,
stack: i32,
bet: i32,
active: bool,
all_in: bool,
hand: Vec<Card>,
}
impl Player {
fn new(id: usize, stack: i32) -> Player {
Player {
id,
stack,
bet: 0,
active: true,
all_in: false,
hand: Vec::with_capacity(2),
}
}
fn reset(&mut self) {
self.bet = 0;
self.active = true;
self.all_in = false;
self.hand.clear();
}
}
// Observation structure
struct Observation {
player_id: usize,
hand: Vec<Card>,
community_cards: Vec<Card>,
pot: i32,
current_bet: i32,
min_call: i32,
stack: i32,
phase: Phase,
}
// Poker environment
struct PokerEnvironment<'a> {
num_players: usize,
players: Vec<Player>,
deck: Deck,
pot: i32,
min_call: i32,
last_raise: i32,
current_player: usize,
dealer_position: usize,
phase: Phase,
betting_round_over: bool,
community_cards: Vec<Card>,
last_aggressor: Option<usize>,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
PreFlop,
Flop,
Turn,
River,
Showdown,
}
impl<'a> PokerEnvironment<'a> {
fn new(
num_players: usize,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
) -> PokerEnvironment<'a> {
let mut env = PokerEnvironment {
num_players,
players: Vec::with_capacity(num_players),
deck: Deck::new(),
pot: 0,
min_call: 0,
last_raise: 0,
current_player: 0,
dealer_position: 0,
phase: Phase::PreFlop,
betting_round_over: false,
community_cards: Vec::new(),
last_aggressor: None,
agent_function,
};
env.initialize_game();
env
}
fn initialize_game(&mut self) {
self.players.clear();
for i in 0..self.num_players {
self.players.push(Player::new(i, MAX_STACK));
}
self.deck.reset();
for player in &mut self.players {
player.reset();
player.hand.push(self.deck.deal());
player.hand.push(self.deck.deal());
}
self.pot = 0;
self.min_call = BIG_BLIND;
self.last_raise = BIG_BLIND;
self.current_player = (self.dealer_position + 3) % self.num_players;
self.phase = Phase::PreFlop;
self.betting_round_over = false;
self.community_cards.clear();
self.last_aggressor = None;
let small_blind_position = (self.dealer_position + 1) % self.num_players;
let big_blind_position = (self.dealer_position + 2) % self.num_players;
self.post_blind(small_blind_position, SMALL_BLIND);
self.post_blind(big_blind_position, BIG_BLIND);
}
fn play_game(&mut self) {
while !self.is_terminal() {
let player_id = self.current_player;
let player = &self.players[player_id];
if player.active && !player.all_in {
let observation = self.get_observation(player_id);
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_game();
}
fn get_observation(&self, player_id: usize) -> Observation {
let player = &self.players[player_id];
Observation {
player_id,
hand: player.hand.clone(),
community_cards: self.community_cards.clone(),
pot: self.pot,
current_bet: player.bet,
min_call: self.min_call,
stack: player.stack,
phase: self.phase,
}
}
fn step(&mut self, action: Action) {
let player_id = self.current_player;
let player = &mut self.players[player_id];
if !player.active || player.all_in {
self.next_player();
return;
}
match action {
Action::Fold => self.handle_fold(player_id),
Action::Call => self.handle_call(player_id),
Action::Raise => self.handle_raise(player_id),
}
if self.betting_round_over {
self.advance_phase();
}
if !self.is_terminal() {
self.next_player();
}
}
fn is_terminal(&self) -> bool {
let active_count = self.players.iter().filter(|p| p.active || p.all_in).count();
active_count <= 1 || self.phase == Phase::Showdown
}
fn handle_fold(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
player.active = false;
self.pot += player.bet;
player.bet = 0;
}
fn handle_call(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let call_amount = self.min_call - player.bet;
let amount = std::cmp::min(call_amount, player.stack);
player.bet += amount;
player.stack -= amount;
if player.stack == 0 {
player.all_in = true;
}
}
fn handle_raise(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let raise_amount = std::cmp::max(self.last_raise * 2, self.min_call * 2);
let amount = std::cmp::min(raise_amount, player.stack);
player.bet += amount;
player.stack -= amount;
self.min_call = player.bet;
self.last_raise = amount;
self.last_aggressor = Some(player_id);
if player.stack == 0 {
player.all_in = true;
}
}
fn next_player(&mut self) {
let start_player = self.current_player;
loop {
self.current_player = (self.current_player + 1) % self.num_players;
if self.current_player == start_player {
self.betting_round_over = true;
break;
}
let player = &self.players[self.current_player];
if player.active && !player.all_in {
break;
}
}
if let Some(last_aggressor) = self.last_aggressor {
if self.current_player == last_aggressor {
self.betting_round_over = true;
}
}
}
fn advance_phase(&mut self) {
for player in &mut self.players {
self.pot += player.bet;
player.bet = 0;
}
self.min_call = 0;
self.last_raise = 0;
self.betting_round_over = false;
self.last_aggressor = None;
self.phase = match self.phase {
Phase::PreFlop => {
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
Phase::Flop
}
Phase::Flop => {
self.community_cards.push(self.deck.deal());
Phase::Turn
}
Phase::Turn => {
self.community_cards.push(self.deck.deal());
Phase::River
}
Phase::River => Phase::Showdown,
Phase::Showdown => Phase::Showdown,
};
self.current_player = (self.dealer_position + 1) % self.num_players;
while {
let player = &self.players[self.current_player];
(!player.active || player.all_in) && self.current_player != self.dealer_position
} {
self.current_player = (self.current_player + 1) % self.num_players;
}
}
fn resolve_game(&mut self) {
let active_players: Vec<_> = self
.players
.iter()
.enumerate()
.filter(|(_, p)| p.active || p.all_in)
.collect();
if active_players.len() == 1 {
let (winner_id, _) = active_players[0];
let winner = &mut self.players[winner_id];
winner.stack += self.pot;
println!(
"Player {} wins the pot of {} by default.",
winner_id, self.pot
);
return;
}
let mut best_rank: Option<u32> = None;
let mut winners = vec![];
for (player_id, player) in active_players {
let rank = HandEvaluator::evaluate_hand(&player.hand, &self.community_cards);
if best_rank.is_none() || rank < best_rank.unwrap() {
best_rank = Some(rank);
winners.clear();
winners.push(player_id);
} else if rank == best_rank.unwrap() {
winners.push(player_id);
}
}
let split_pot = self.pot / winners.len() as i32;
for &winner_id in &winners {
let winner = &mut self.players[winner_id];
winner.stack += split_pot;
println!(
"Player {} wins {} with hand rank {}.",
winner_id,
split_pot,
best_rank.unwrap()
);
}
}
fn post_blind(&mut self, player_id: usize, amount: i32) {
let player = &mut self.players[player_id];
let blind_amount = std::cmp::min(amount, player.stack);
player.bet += blind_amount;
player.stack -= blind_amount;
self.pot += blind_amount;
self.min_call = std::cmp::max(self.min_call, player.bet);
if player.stack == 0 {
player.all_in = true;
}
}
}
// Example agent function
fn example_agent_function(player_id: usize, observation: &Observation) -> Action {
let mut rng = thread_rng();
let choice: f64 = rng.gen();
if observation.min_call == 0 {
if choice < 0.5 {
Action::Call // Check
} else {
Action::Raise
}
} else if observation.phase != Phase::Showdown {
if choice < 0.5 {
Action::Call
} else {
Action::Raise
}
} else {
Action::Fold
}
}
// Main function
fn main() {
let agent_function = Box::new(example_agent_function);
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_game();
println!("Game simulation completed.");
}
Key Modifications
Removed Log File Field: The log_file field has been removed from the PokerEnvironment.
Removed Log Initialization and Usage: Any code related to initializing and writing to the log file has been deleted.
Console Output: The game results and actions are printed directly to the console with println!() which is simple and effective for understanding flow.
This version should be cleaner and focused purely on running the poker game simulation.
Further Actions:
Determine Usage: Review the design of your program to decide whether you'll need those fields in future implementations for logging, debugging, or game mechanics.
Access Fields: If these fields should be part of the game logic, ensure they are accessed appropriately in your agent logic or other relevant areas of the code.
use rand::prelude::*;
use itertools::Itertools;
use std::fmt;
// Constants
const NUM_PLAYERS: usize = 9;
const NUM_CARDS: usize = 52;
const NUM_RANKS: usize = 13;
const NUM_SUITS: usize = 4;
const MAX_STACK: i32 = 10000;
const SMALL_BLIND: i32 = 50;
const BIG_BLIND: i32 = 100;
// Actions
#[derive(Clone, Copy, Debug)]
enum Action {
Fold,
Call,
Raise,
}
// Card representation
#[derive(Clone, Copy)]
struct Card {
rank: usize,
suit: usize,
}
impl Card {
fn new(id: usize) -> Card {
Card {
suit: id / NUM_RANKS,
rank: id % NUM_RANKS,
}
}
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let rank_strings = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"];
let suit_strings = ["h", "d", "c", "s"];
write!(f, "{}{}", rank_strings[self.rank], suit_strings[self.suit])
}
}
// Deck management
struct Deck {
cards: Vec<Card>,
rng: ThreadRng,
}
impl Deck {
fn new() -> Deck {
let mut deck = Deck {
cards: Vec::with_capacity(NUM_CARDS),
rng: thread_rng(),
};
deck.generate_deck();
deck.shuffle();
deck
}
fn generate_deck(&mut self) {
self.cards.clear();
for i in 0..NUM_CARDS {
self.cards.push(Card::new(i));
}
}
fn shuffle(&mut self) {
self.cards.shuffle(&mut self.rng);
}
fn deal(&mut self) -> Card {
self.cards.pop().expect("No more cards in the deck")
}
fn reset(&mut self) {
self.generate_deck();
self.shuffle();
}
}
// Hand evaluation
struct HandEvaluator;
impl HandEvaluator {
fn evaluate_hand(hand: &[Card], community_cards: &[Card]) -> u32 {
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
let card_ints: Vec<u8> = all_cards.iter().map(|card| Self::card_to_int(*card)).collect();
Self::evaluate_7_card_hand(&card_ints)
}
fn card_to_int(card: Card) -> u8 {
let rank_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
let suit_bits = [0x10, 0x20, 0x40, 0x80];
let rank_prime = rank_primes[card.rank];
let suit_bit = suit_bits[card.suit];
(rank_prime as u8) | suit_bit
}
fn evaluate_7_card_hand(cards: &[u8]) -> u32 {
let mut best_rank = u32::MAX;
for combo in cards.iter().combinations(5) {
let hand = [combo[0], combo[1], combo[2], combo[3], combo[4]];
let rank = Self::evaluate_5_card_hand(&hand);
if rank < best_rank {
best_rank = rank;
}
}
best_rank
}
fn evaluate_5_card_hand(cards: &[&u8]) -> u32 {
let mut rank_counts = [0u8; NUM_RANKS];
let mut suit_counts = [0u8; NUM_SUITS];
for &&card in cards {
let rank_prime = (card & 0x0F) as usize;
let suit_bit = card & 0xF0;
let rank_index = match rank_prime {
2 => 0, 3 => 1, 5 => 2, 7 => 3, 11 => 4,
13 => 5, 17 => 6, 19 => 7, 23 => 8, 29 => 9,
31 => 10, 37 => 11, 41 => 12, _ => continue,
};
rank_counts[rank_index] += 1;
let suit_index = match suit_bit {
0x10 => 0, 0x20 => 1, 0x40 => 2, 0x80 => 3, _ => continue,
};
suit_counts[suit_index] += 1;
}
let is_flush = suit_counts.iter().any(|&count| count >= 5);
let mut ranks: Vec<u8> = rank_counts.iter().cloned().filter(|&count| count > 0).collect();
ranks.sort_unstable_by(|a, b| b.cmp(a));
let hand_rank = if is_flush && Self::is_straight(&rank_counts) {
1 // Straight Flush
} else if ranks[0] == 4 {
2 // Four of a Kind
} else if ranks[0] == 3 && ranks[1] >= 2 {
3 // Full House
} else if is_flush {
4 // Flush
} else if Self::is_straight(&rank_counts) {
5 // Straight
} else if ranks[0] == 3 {
6 // Three of a Kind
} else if ranks[0] == 2 && ranks[1] == 2 {
7 // Two Pair
} else if ranks[0] == 2 {
8 // One Pair
} else {
9 // High Card
};
hand_rank
}
fn is_straight(rank_counts: &[u8; NUM_RANKS]) -> bool {
let mut consecutive = 0;
let counts = [&rank_counts[..], &[rank_counts[0]]].concat();
for &count in counts.iter() {
if count > 0 {
consecutive += 1;
if consecutive >= 5 {
return true;
}
} else {
consecutive = 0;
}
}
false
}
}
// Player structure
struct Player {
// Removed the id field as it was unused
stack: i32,
bet: i32,
active: bool,
all_in: bool,
hand: Vec<Card>,
}
impl Player {
fn new(stack: i32) -> Player {
Player {
stack,
bet: 0,
active: true,
all_in: false,
hand: Vec::with_capacity(2),
}
}
fn reset(&mut self) {
self.bet = 0;
self.active = true;
self.all_in = false;
self.hand.clear();
}
}
// Observation structure
struct Observation {
min_call: i32,
phase: Phase,
}
// Poker environment
struct PokerEnvironment<'a> {
num_players: usize,
players: Vec<Player>,
deck: Deck,
pot: i32,
min_call: i32,
last_raise: i32,
current_player: usize,
dealer_position: usize,
phase: Phase,
betting_round_over: bool,
community_cards: Vec<Card>,
last_aggressor: Option<usize>,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
PreFlop,
Flop,
Turn,
River,
Showdown,
}
impl<'a> PokerEnvironment<'a> {
fn new(
num_players: usize,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
) -> PokerEnvironment<'a> {
let mut env = PokerEnvironment {
num_players,
players: Vec::with_capacity(num_players),
deck: Deck::new(),
pot: 0,
min_call: 0,
last_raise: 0,
current_player: 0,
dealer_position: 0,
phase: Phase::PreFlop,
betting_round_over: false,
community_cards: Vec::new(),
last_aggressor: None,
agent_function,
};
env.initialize_game();
env
}
fn initialize_game(&mut self) {
self.players.clear();
for _ in 0..self.num_players {
self.players.push(Player::new(MAX_STACK));
}
self.deck.reset();
for player in &mut self.players {
player.reset();
player.hand.push(self.deck.deal());
player.hand.push(self.deck.deal());
}
self.pot = 0;
self.min_call = BIG_BLIND;
self.last_raise = BIG_BLIND;
self.current_player = (self.dealer_position + 3) % self.num_players;
self.phase = Phase::PreFlop;
self.betting_round_over = false;
self.community_cards.clear();
self.last_aggressor = None;
let small_blind_position = (self.dealer_position + 1) % self.num_players;
let big_blind_position = (self.dealer_position + 2) % self.num_players;
self.post_blind(small_blind_position, SMALL_BLIND);
self.post_blind(big_blind_position, BIG_BLIND);
}
fn play_game(&mut self) {
while !self.is_terminal() {
let player_id = self.current_player;
let player = &self.players[player_id];
if player.active && !player.all_in {
let observation = self.get_observation();
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_game();
}
fn get_observation(&self) -> Observation {
Observation {
min_call: self.min_call,
phase: self.phase,
}
}
fn step(&mut self, action: Action) {
let player_id = self.current_player;
let player = &mut self.players[player_id];
if !player.active || player.all_in {
self.next_player();
return;
}
match action {
Action::Fold => self.handle_fold(player_id),
Action::Call => self.handle_call(player_id),
Action::Raise => self.handle_raise(player_id),
}
if self.betting_round_over {
self.advance_phase();
}
if !self.is_terminal() {
self.next_player();
}
}
fn is_terminal(&self) -> bool {
let active_count = self.players.iter().filter(|p| p.active || p.all_in).count();
active_count <= 1 || self.phase == Phase::Showdown
}
fn handle_fold(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
player.active = false;
self.pot += player.bet;
player.bet = 0;
}
fn handle_call(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let call_amount = self.min_call - player.bet;
let amount = std::cmp::min(call_amount, player.stack);
player.bet += amount;
player.stack -= amount;
if player.stack == 0 {
player.all_in = true;
}
}
fn handle_raise(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let raise_amount = std::cmp::max(self.last_raise * 2, self.min_call * 2);
let amount = std::cmp::min(raise_amount, player.stack);
player.bet += amount;
player.stack -= amount;
self.min_call = player.bet;
self.last_raise = amount;
self.last_aggressor = Some(player_id);
if player.stack == 0 {
player.all_in = true;
}
}
fn next_player(&mut self) {
let start_player = self.current_player;
loop {
self.current_player = (self.current_player + 1) % self.num_players;
if self.current_player == start_player {
self.betting_round_over = true;
break;
}
let player = &self.players[self.current_player];
if player.active && !player.all_in {
break;
}
}
if let Some(last_aggressor) = self.last_aggressor {
if self.current_player == last_aggressor {
self.betting_round_over = true;
}
}
}
fn advance_phase(&mut self) {
for player in &mut self.players {
self.pot += player.bet;
player.bet = 0;
}
self.min_call = 0;
self.last_raise = 0;
self.betting_round_over = false;
self.last_aggressor = None;
self.phase = match self.phase {
Phase::PreFlop => {
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
Phase::Flop
}
Phase::Flop => {
self.community_cards.push(self.deck.deal());
Phase::Turn
}
Phase::Turn => {
self.community_cards.push(self.deck.deal());
Phase::River
}
Phase::River => Phase::Showdown,
Phase::Showdown => Phase::Showdown,
};
self.current_player = (self.dealer_position + 1) % self.num_players;
while {
let player = &self.players[self.current_player];
(!player.active || player.all_in) && self.current_player != self.dealer_position
} {
self.current_player = (self.current_player + 1) % self.num_players;
}
}
fn resolve_game(&mut self) {
let active_players: Vec<_> = self
.players
.iter()
.enumerate()
.filter(|(_, p)| p.active || p.all_in)
.collect();
if active_players.len() == 1 {
let (winner_id, _) = active_players[0];
let winner = &mut self.players[winner_id];
winner.stack += self.pot;
println!(
"Player {} wins the pot of {} by default.",
winner_id, self.pot
);
return;
}
let mut best_rank: Option<u32> = None;
let mut winners = vec![];
for (player_id, player) in active_players {
let rank = HandEvaluator::evaluate_hand(&player.hand, &self.community_cards);
if best_rank.is_none() || rank < best_rank.unwrap() {
best_rank = Some(rank);
winners.clear();
winners.push(player_id);
} else if rank == best_rank.unwrap() {
winners.push(player_id);
}
}
let split_pot = self.pot / winners.len() as i32;
for &winner_id in &winners {
let winner = &mut self.players[winner_id];
winner.stack += split_pot;
println!(
"Player {} wins {} with hand rank {}.",
winner_id,
split_pot,
best_rank.unwrap()
);
}
}
fn post_blind(&mut self, player_id: usize, amount: i32) {
let player = &mut self.players[player_id];
let blind_amount = std::cmp::min(amount, player.stack);
player.bet += blind_amount;
player.stack -= blind_amount;
self.pot += blind_amount;
self.min_call = std::cmp::max(self.min_call, player.bet);
if player.stack == 0 {
player.all_in = true;
}
}
}
// Example agent function
fn example_agent_function(_player_id: usize, observation: &Observation) -> Action {
let mut rng = thread_rng();
let choice: f64 = rng.gen();
if observation.min_call == 0 {
if choice < 0.5 {
Action::Call // Check
} else {
Action::Raise
}
} else if observation.phase != Phase::Showdown {
if choice < 0.5 {
Action::Call
} else {
Action::Raise
}
} else {
Action::Fold
}
}
// Main function
fn main() {
let agent_function = Box::new(example_agent_function);
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_game();
println!("Game simulation completed.");
}
Key Changes:
Unused Variables: The player_id in example_agent_function is prefixed with an underscore because it's unused.
Removed Unused Fields: The id field from the Player struct is removed as it was not being utilized in the provided code.
Trimmed Observation Struct: The Observation struct now only contains the fields used in the decision-making logic.
This version should compile without warnings related to unused variables or fields, given the constraints of the current logic. If you need to expand functionality later, you can revisit these fields.
use rand::prelude::*;
use itertools::Itertools;
use std::fmt;
// Constants
const NUM_PLAYERS: usize = 9;
const NUM_CARDS: usize = 52;
const NUM_RANKS: usize = 13;
const NUM_SUITS: usize = 4;
const MAX_STACK: i32 = 10000;
const SMALL_BLIND: i32 = 50;
const BIG_BLIND: i32 = 100;
// Actions
#[derive(Clone, Copy, Debug)]
enum Action {
Fold,
Call,
Raise,
}
// Card representation
#[derive(Clone, Copy)]
struct Card {
rank: usize,
suit: usize,
}
impl Card {
fn new(id: usize) -> Card {
Card {
suit: id / NUM_RANKS,
rank: id % NUM_RANKS,
}
}
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let rank_strings = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"];
let suit_strings = ["h", "d", "c", "s"];
write!(f, "{}{}", rank_strings[self.rank], suit_strings[self.suit])
}
}
// Deck management
struct Deck {
cards: Vec<Card>,
rng: ThreadRng,
}
impl Deck {
fn new() -> Deck {
let mut deck = Deck {
cards: Vec::with_capacity(NUM_CARDS),
rng: thread_rng(),
};
deck.generate_deck();
deck.shuffle();
deck
}
fn generate_deck(&mut self) {
self.cards.clear();
for i in 0..NUM_CARDS {
self.cards.push(Card::new(i));
}
}
fn shuffle(&mut self) {
self.cards.shuffle(&mut self.rng);
}
fn deal(&mut self) -> Card {
self.cards.pop().expect("No more cards in the deck")
}
fn reset(&mut self) {
self.generate_deck();
self.shuffle();
}
}
// Hand evaluation
struct HandEvaluator;
impl HandEvaluator {
fn evaluate_hand(hand: &[Card], community_cards: &[Card]) -> u32 {
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
let card_ints: Vec<u8> = all_cards.iter().map(|card| Self::card_to_int(*card)).collect();
Self::evaluate_7_card_hand(&card_ints)
}
fn card_to_int(card: Card) -> u8 {
let rank_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
let suit_bits = [0x10, 0x20, 0x40, 0x80];
let rank_prime = rank_primes[card.rank];
let suit_bit = suit_bits[card.suit];
(rank_prime as u8) | suit_bit
}
fn evaluate_7_card_hand(cards: &[u8]) -> u32 {
let mut best_rank = u32::MAX;
for combo in cards.iter().combinations(5) {
let hand = [combo[0], combo[1], combo[2], combo[3], combo[4]];
let rank = Self::evaluate_5_card_hand(&hand);
if rank < best_rank {
best_rank = rank;
}
}
best_rank
}
fn evaluate_5_card_hand(cards: &[&u8]) -> u32 {
let mut rank_counts = [0u8; NUM_RANKS];
let mut suit_counts = [0u8; NUM_SUITS];
for &&card in cards {
let rank_prime = (card & 0x0F) as usize;
let suit_bit = card & 0xF0;
let rank_index = match rank_prime {
2 => 0, 3 => 1, 5 => 2, 7 => 3, 11 => 4,
13 => 5, 17 => 6, 19 => 7, 23 => 8, 29 => 9,
31 => 10, 37 => 11, 41 => 12, _ => continue,
};
rank_counts[rank_index] += 1;
let suit_index = match suit_bit {
0x10 => 0, 0x20 => 1, 0x40 => 2, 0x80 => 3, _ => continue,
};
suit_counts[suit_index] += 1;
}
let is_flush = suit_counts.iter().any(|&count| count >= 5);
let mut ranks: Vec<u8> = rank_counts.iter().cloned().filter(|&count| count > 0).collect();
ranks.sort_unstable_by(|a, b| b.cmp(a));
let hand_rank = if is_flush && Self::is_straight(&rank_counts) {
1 // Straight Flush
} else if ranks[0] == 4 {
2 // Four of a Kind
} else if ranks[0] == 3 && ranks[1] >= 2 {
3 // Full House
} else if is_flush {
4 // Flush
} else if Self::is_straight(&rank_counts) {
5 // Straight
} else if ranks[0] == 3 {
6 // Three of a Kind
} else if ranks[0] == 2 && ranks[1] == 2 {
7 // Two Pair
} else if ranks[0] == 2 {
8 // One Pair
} else {
9 // High Card
};
hand_rank
}
fn is_straight(rank_counts: &[u8; NUM_RANKS]) -> bool {
let mut consecutive = 0;
let counts = [&rank_counts[..], &[rank_counts[0]]].concat();
for &count in counts.iter() {
if count > 0 {
consecutive += 1;
if consecutive >= 5 {
return true;
}
} else {
consecutive = 0;
}
}
false
}
}
// Player structure
struct Player {
stack: i32,
bet: i32,
active: bool,
all_in: bool,
hand: Vec<Card>,
}
impl Player {
fn new(stack: i32) -> Player {
Player {
stack,
bet: 0,
active: true,
all_in: false,
hand: Vec::with_capacity(2),
}
}
fn reset(&mut self) {
self.bet = 0;
self.active = true;
self.all_in = false;
self.hand.clear();
}
}
// Observation structure
struct Observation {
min_call: i32,
phase: Phase,
}
// Poker environment
struct PokerEnvironment<'a> {
num_players: usize,
players: Vec<Player>,
deck: Deck,
pot: i32,
min_call: i32,
last_raise: i32,
current_player: usize,
dealer_position: usize,
phase: Phase,
betting_round_over: bool,
community_cards: Vec<Card>,
last_aggressor: Option<usize>,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
PreFlop,
Flop,
Turn,
River,
Showdown,
}
impl<'a> PokerEnvironment<'a> {
fn new(
num_players: usize,
agent_function: Box<dyn Fn(usize, &Observation) -> Action + 'a>,
) -> PokerEnvironment<'a> {
let mut env = PokerEnvironment {
num_players,
players: Vec::with_capacity(num_players),
deck: Deck::new(),
pot: 0,
min_call: 0,
last_raise: 0,
current_player: 0,
dealer_position: 0,
phase: Phase::PreFlop,
betting_round_over: false,
community_cards: Vec::new(),
last_aggressor: None,
agent_function,
};
env.initialize_game();
env
}
fn initialize_game(&mut self) {
self.players.clear();
for _ in 0..self.num_players {
self.players.push(Player::new(MAX_STACK));
}
self.deck.reset();
for player in &mut self.players {
player.reset();
player.hand.push(self.deck.deal());
player.hand.push(self.deck.deal());
}
self.pot = 0;
self.min_call = BIG_BLIND;
self.last_raise = BIG_BLIND;
self.current_player = (self.dealer_position + 3) % self.num_players;
self.phase = Phase::PreFlop;
self.betting_round_over = false;
self.community_cards.clear();
self.last_aggressor = None;
let small_blind_position = (self.dealer_position + 1) % self.num_players;
let big_blind_position = (self.dealer_position + 2) % self.num_players;
self.post_blind(small_blind_position, SMALL_BLIND);
self.post_blind(big_blind_position, BIG_BLIND);
}
fn play_game(&mut self) {
while !self.is_terminal() {
let player_id = self.current_player;
let player = &self.players[player_id];
if player.active && !player.all_in {
let observation = self.get_observation();
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_game();
}
fn get_observation(&self) -> Observation {
Observation {
min_call: self.min_call,
phase: self.phase,
}
}
fn step(&mut self, action: Action) {
let player_id = self.current_player;
let player = &mut self.players[player_id];
if !player.active || player.all_in {
self.next_player();
return;
}
match action {
Action::Fold => self.handle_fold(player_id),
Action::Call => self.handle_call(player_id),
Action::Raise => self.handle_raise(player_id),
}
if self.betting_round_over {
self.advance_phase();
}
if !self.is_terminal() {
self.next_player();
}
}
fn is_terminal(&self) -> bool {
let active_count = self.players.iter().filter(|p| p.active || p.all_in).count();
active_count <= 1 || self.phase == Phase::Showdown
}
fn handle_fold(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
player.active = false;
self.pot += player.bet;
player.bet = 0;
}
fn handle_call(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let call_amount = self.min_call - player.bet;
let amount = std::cmp::min(call_amount, player.stack);
player.bet += amount;
player.stack -= amount;
if player.stack == 0 {
player.all_in = true;
}
}
fn handle_raise(&mut self, player_id: usize) {
let player = &mut self.players[player_id];
let raise_amount = std::cmp::max(self.last_raise * 2, self.min_call * 2);
let amount = std::cmp::min(raise_amount, player.stack);
player.bet += amount;
player.stack -= amount;
self.min_call = player.bet;
self.last_raise = amount;
self.last_aggressor = Some(player_id);
if player.stack == 0 {
player.all_in = true;
}
}
fn next_player(&mut self) {
let start_player = self.current_player;
loop {
self.current_player = (self.current_player + 1) % self.num_players;
if self.current_player == start_player {
self.betting_round_over = true;
break;
}
let player = &self.players[self.current_player];
if player.active && !player.all_in {
break;
}
}
if let Some(last_aggressor) = self.last_aggressor {
if self.current_player == last_aggressor {
self.betting_round_over = true;
}
}
}
fn advance_phase(&mut self) {
for player in &mut self.players {
self.pot += player.bet;
player.bet = 0;
}
self.min_call = 0;
self.last_raise = 0;
self.betting_round_over = false;
self.last_aggressor = None;
self.phase = match self.phase {
Phase::PreFlop => {
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
self.community_cards.push(self.deck.deal());
Phase::Flop
}
Phase::Flop => {
self.community_cards.push(self.deck.deal());
Phase::Turn
}
Phase::Turn => {
self.community_cards.push(self.deck.deal());
Phase::River
}
Phase::River => Phase::Showdown,
Phase::Showdown => Phase::Showdown,
};
self.current_player = (self.dealer_position + 1) % self.num_players;
while {
let player = &self.players[self.current_player];
(!player.active || player.all_in) && self.current_player != self.dealer_position
} {
self.current_player = (self.current_player + 1) % self.num_players;
}
}
fn resolve_game(&mut self) {
let active_players: Vec<_> = self
.players
.iter()
.enumerate()
.filter(|(_, p)| p.active || p.all_in)
.collect();
if active_players.len() == 1 {
let (winner_id, _) = active_players[0];
let winner = &mut self.players[winner_id];
winner.stack += self.pot;
println!(
"Player {} wins the pot of {} by default.",
winner_id, self.pot
);
return;
}
let mut best_rank: Option<u32> = None;
let mut winners = vec![];
for (player_id, player) in active_players {
let rank = HandEvaluator::evaluate_hand(&player.hand, &self.community_cards);
if best_rank.is_none() || rank < best_rank.unwrap() {
best_rank = Some(rank);
winners.clear();
winners.push(player_id);
} else if rank == best_rank.unwrap() {
winners.push(player_id);
}
}
let split_pot = self.pot / winners.len() as i32;
for &winner_id in &winners {
let winner = &mut self.players[winner_id];
winner.stack += split_pot;
println!(
"Player {} wins {} with hand rank {}.",
winner_id,
split_pot,
best_rank.unwrap()
);
}
}
fn post_blind(&mut self, player_id: usize, amount: i32) {
let player = &mut self.players[player_id];
let blind_amount = std::cmp::min(amount, player.stack);
player.bet += blind_amount;
player.stack -= blind_amount;
self.pot += blind_amount;
self.min_call = std::cmp::max(self.min_call, player.bet);
if player.stack == 0 {
player.all_in = true;
}
}
}
// Random agent function
fn random_agent_function(_player_id: usize, _observation: &Observation) -> Action {
let mut rng = thread_rng();
match rng.gen_range(0..3) {
0 => Action::Fold,
1 => Action::Call,
_ => Action::Raise,
}
}
// Main function
fn main() {
let agent_function = Box::new(random_agent_function);
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_game();
println!("Game simulation completed.");
}
Explanation:
Random Agent: The random_agent_function uses the rand::Rng trait to generate a random number between 0 and 2, each corresponding to a different Action (Fold, Call, Raise).
Usage: This random agent is plugged into the poker environment, making decisions independent of the game state, purely at random.
This setup allows you to test the game system or use as a baseline for evaluating more sophisticated strategies or agents.
warning: struct Player is never constructed
--> src/lib.rs:186:8
|
186 | struct Player {
| ^^^^^^
warning: associated items new and reset are never used
--> src/lib.rs:195:8
|
194 | impl Player {
| ----------- associated items in this implementation
195 | fn new(stack: i32) -> Player {
| ^^^
...
205 | fn reset(&mut self) {
| ^^^^^
warning: struct Observation is never constructed
--> src/lib.rs:214:8
|
214 | struct Observation {
| ^^^^^^^^^^^
warning: struct PokerEnvironment is never constructed
--> src/lib.rs:220:8
|
220 | struct PokerEnvironment<'a> {
| ^^^^^^^^^^^^^^^^
warning: enum Phase is never used
--> src/lib.rs:237:6
|
237 | enum Phase {
| ^^^^^