// This project simulates a simplified version of a poker game environment including
// player actions, card dealings, and hand evaluation. The simulation is set up to support
// reinforcement learning agents by providing a detailed game state observation.
// Imports for randomness and formatting
use rand::prelude::*;
use std::fmt;
// Constants for the game
const NUM_PLAYERS: usize = 9; // Number of players in the game
const NUM_CARDS: usize = 52; // Number of cards in a standard deck
const NUM_RANKS: usize = 13; // Number of ranks in a standard deck
const NUM_SUITS: usize = 4; // Number of suits in a standard deck
const MAX_STACK: u32 = 10000; // Initial stack size for each player
const SMALL_BLIND: u32 = 50; // Small blind bet
const BIG_BLIND: u32 = 100; // Big blind bet
// Enumeration for player actions
#[derive(Clone, Copy, Debug)]
enum Action {
Fold, // Player gives up their hand
Call, // Player matches the current bet
Raise, // Player increases the current bet
}
// Structure to represent a playing card with rank and suit
#[derive(Clone, Copy, Debug)]
struct Card {
rank: usize,
suit: usize,
}
impl Card {
// Creates a new Card based on an integer ID
fn new(id: usize) -> Card {
Card {
suit: id / NUM_RANKS,
rank: id % NUM_RANKS,
}
}
}
// Display formatting for Card, allowing cards to be printed as strings
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 of cards management (shuffling and dealing)
struct Deck {
cards: Vec,
rng: ThreadRng,
}
impl Deck {
// Creates a new shuffled deck
fn new() -> Deck {
let mut deck = Deck {
cards: Vec::with_capacity(NUM_CARDS),
rng: thread_rng(),
};
deck.generate_deck();
deck.shuffle();
deck
}
code
// Generates a standard deck of 52 cards
fn generate_deck(&mut self) {
self.cards.clear();
for i in 0..NUM_CARDS {
self.cards.push(Card::new(i));
}
}
// Shuffles the deck
fn shuffle(&mut self) {
self.cards.shuffle(&mut self.rng);
}
// Deals a single card from the deck
fn deal(&mut self) -> Card {
self.cards.pop().expect("No more cards in the deck")
}
// Resets the deck to a shuffled full deck
fn reset(&mut self) {
self.generate_deck();
self.shuffle();
}
Assistant
The issue in your Rust code is related to type mismatches between usize and u32. Specifically, the errors occur in the HandEvaluator::hash_quinary function where you're trying to subtract a u32 from a usize, which is not directly allowed.
To fix this, you should ensure that the type of remaining_k is consistent with the type of count. Since count is a u8 and you're casting it to u32, one solution is to just cast it to usize instead. Here's a modification of the code to fix these type mismatches:
rust
User
fix and give me full version of code
Assistant
User
warning: comparison is useless due to type limits
--> src/main.rs:149:12
|
149 | if remaining_k < 0 {
| ^^^^^^^^^^^^^^^
|
= note: #[warn(unused_comparisons)] on by default
Assistant
The warning you're seeing is due to a comparison where remaining_k, which is of type usize, is checked against 0 to see if it's less than zero. Since usize is an unsigned integer type, it cannot be negative, making this check unnecessary and generating the warning.
To resolve the warning, simply remove the comparison with 0 because it's not needed for an unsigned type. Here is the corrected part of your code:
rust
fn hash_quinary(&self, quinary: &[u8; NUM_RANKS]) -> u32 {
let mut hash = 0;
let mut remaining_k = 7; // Use usize for the number of cards in the hand
for (i, &count) in quinary.iter().enumerate() {
if remaining_k >= i {
hash += self.combinations[NUM_RANKS - 1 - i][remaining_k];
}
remaining_k = remaining_k.saturating_sub(count as usize); // Use saturating_sub
}
hash
}
User
RLObservation name is bad
Assistant
If the name RLObservation seems inappropriate or not intuitive, you might consider renaming it to something more descriptive of its purpose or its contents. The purpose of the RLObservation struct is to encapsulate the state of the poker game in a way that can be used by an agent, usually in reinforcement learning contexts.
User
just observation?
Assistant
Certainly, renaming the struct to simply Observation is a succinct and straightforward choice, especially if the context makes it clear that it's related to observing the game state. Here's how this change would be implemented:
rust
}
// Hand evaluation using quinary method
struct HandEvaluator {
combinations: [[u32; 8]; 14], // Combination table using u32 for compatibility
}
impl HandEvaluator {
// Initializes a hand evaluator with precomputed combinations
fn new() -> Self {
let combinations = Self::precompute_combinations();
HandEvaluator { combinations }
}
code
// Precomputes combination table for hand evaluation
fn precompute_combinations() -> [[u32; 8]; 14] {
let mut combinations = [[0; 8]; 14];
for i in 0..14 {
for j in 0..=i.min(7) {
if j == 0 || j == i {
combinations[i][j] = 1;
} else {
combinations[i][j] = combinations[i - 1][j] + combinations[i - 1][j - 1];
}
}
}
combinations
}
// Converts a hand into a quinary representation
fn quinary_from_hand(cards: &[Card]) -> [u8; NUM_RANKS] {
let mut quinary = [0u8; NUM_RANKS];
for card in cards {
quinary[card.rank] += 1;
}
quinary
}
// Evaluates a hand using its quinary representation
fn evaluate_hand(&self, hand: &[Card], community_cards: &[Card]) -> u32 {
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
let quinary = Self::quinary_from_hand(&all_cards);
self.hash_quinary(&quinary)
}
// Computes the hash for a quinary representation
fn hash_quinary(&self, quinary: &[u8; NUM_RANKS]) -> u32 {
let mut hash = 0;
let mut remaining_k = 7; // Number of cards in the hand as u32
for (i, &count) in quinary.iter().enumerate() {
if remaining_k > i {
hash += self.combinations[NUM_RANKS - 1 - i][remaining_k as usize];
}
remaining_k -= count as u32;
if remaining_k < 0 {
break;
}
}
hash
}
}
// Representation of a Player in the game
struct Player {
stack: u32, // Player's current stack
bet: u32, // Player's current bet in the round
active: bool, // Is the player still active in the round
all_in: bool, // Is the player all-in
hand: Vec, // Player's hand (2 cards)
}
impl Player {
// Creates a new player with an initial stack
fn new(stack: u32) -> Player {
Player {
stack,
bet: 0,
active: true,
all_in: false,
hand: Vec::with_capacity(2),
}
}
code
// Resets the player's state for a new round
fn reset(&mut self) {
self.bet = 0;
self.active = true;
self.all_in = false;
self.hand.clear();
}
}
// Comprehensive game state for RL agents
#[derive(Debug, Clone)]
struct GameState {
player_hands: Vec<Vec>, // Each player's hole cards
community_cards: Vec, // The shared community cards
player_stacks: Vec, // Each player's current stack
player_bets: Vec, // Each player's current bet
pot: u32, // Current size of the pot
current_player: usize, // Index of the current player
phase: Phase, // Current phase of the game
}
// RL-compatible observation structure
struct RLObservation {
state: GameState, // Detailed game state
min_call: u32, // Minimum amount needed to call
}
// The core environment managing the game state and progression
struct PokerEnvironment
where
F: Fn(usize, &RLObservation) -> Action,
{
num_players: usize, // Number of players in the game
players: Vec, // Vector of players
deck: Deck, // Deck of cards
pot: u32, // Total pot size
min_call: u32, // Minimum amount to call in the current bet
last_raise: u32, // Last raised amount
current_player: usize,// The index of the current player in action
dealer_position: usize, // The index of the dealer
phase: Phase, // Current phase of the game
betting_round_over: bool, // Is the current betting round over?
community_cards: Vec, // Community cards visible to all players
last_aggressor: Option, // Last player to make an aggressive action
agent_function: F, // Function determining player actions
evaluator: HandEvaluator, // Hand evaluator with precomputed combinations
}
// Enumeration of possible game phases
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
PreFlop,
Flop,
Turn,
River,
Showdown,
}
impl PokerEnvironment
where
F: Fn(usize, &RLObservation) -> Action,
{
// Initializes a new poker game environment
fn new(num_players: usize, agent_function: F) -> PokerEnvironment {
let evaluator = HandEvaluator::new(); // Create evaluator with precomputed values
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,
evaluator,
};
env.initialize_game();
env
}
code
// Sets up a new game with initial states and conditions
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);
}
// Runs a single hand of poker, progressing through rounds and phases
fn play_single_hand(&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_rl_observation();
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_hand();
}
// Generates a detailed observation for RL agents
fn get_rl_observation(&self) -> RLObservation {
RLObservation {
state: GameState {
player_hands: self.players.iter().map(|p| p.hand.clone()).collect(),
community_cards: self.community_cards.clone(),
player_stacks: self.players.iter().map(|p| p.stack).collect(),
player_bets: self.players.iter().map(|p| p.bet).collect(),
pot: self.pot,
current_player: self.current_player,
phase: self.phase,
},
min_call: self.min_call,
}
}
// Processes a player's action and updates the game state
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();
}
}
// Checks if the hand is at a terminal state (finished)
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
}
// Handles the fold action by a player
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;
}
// Handles the call action, matching a player's bet to the minimum call
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;
}
}
// Handles the raise action, increasing a player's bet
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;
}
}
// Advances the current player to the next one in line
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;
}
}
}
// Progresses the game to the next phase
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;
}
}
// Resolves the end of a hand, determining winners and distributing the pot
fn resolve_hand(&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 = self.evaluator.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 u32;
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()
);
}
}
// Posts a blind bet for a specified player
fn post_blind(&mut self, player_id: usize, amount: u32) {
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;
}
}
}
// Function defining a random player action
fn random_agent_function(_player_id: usize, _observation: &RLObservation) -> Action {
let mut rng = thread_rng();
match rng.gen_range(0..3) {
0 => Action::Fold,
1 => Action::Call,
_ => Action::Raise,
}
}
// Main function initializes the game and triggers the simulation
fn main() {
// Use the random agent function
let agent_function = random_agent_function;
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_single_hand();
println!("Hand simulation completed.");
}
error[E0277]: cannot subtract-assign u32 from usize
--> src/main.rs:148:25
|
148 | remaining_k -= count as u32;
| ^^ no implementation for usize -= u32
|
= help: the trait SubAssign<u32> is not implemented for usize
= help: the following other types implement trait SubAssign<Rhs>:
usize implements SubAssign<&usize>usize implements SubAssign
Some errors have detailed explanations: E0277, E0308.
For more information about an error, try rustc --explain E0277.
error: could not compile playground (bin "playground") due to 2 previous errors
Standard Output
fn hash_quinary(&self, quinary: &[u8; NUM_RANKS]) -> u32 {
let mut hash = 0;
let mut remaining_k = 7; // Number of cards in the hand as usize
for (i, &count) in quinary.iter().enumerate() {
if remaining_k > i {
hash += self.combinations[NUM_RANKS - 1 - i][remaining_k as usize];
}
remaining_k -= count as usize; // Cast count to usize here
if remaining_k < 0 {
break;
}
}
hash
}
In this solution, remaining_k is a usize, and count is cast to usize during the subtraction. This eliminates the type mismatch errors and allows the subtraction to proceed correctly. Note that remaining_k should logically be a usize because it will be compared to indices of arrays and used in array indexing, which are typically done with usize in Rust.
Below is the complete corrected version of your Rust code, addressing the type mismatch issue between usize and u32. I've adjusted the types in the hash_quinary function to ensure they match:
rust
use rand::prelude::*;
use std::fmt;
const NUM_PLAYERS: usize = 9; // Number of players in the game
const NUM_CARDS: usize = 52; // Number of cards in a standard deck
const NUM_RANKS: usize = 13; // Number of ranks in a standard deck
const NUM_SUITS: usize = 4; // Number of suits in a standard deck
const MAX_STACK: u32 = 10000; // Initial stack size for each player
const SMALL_BLIND: u32 = 50; // Small blind bet
const BIG_BLIND: u32 = 100; // Big blind bet
#[derive(Clone, Copy, Debug)]
enum Action {
Fold,
Call,
Raise,
}
#[derive(Clone, Copy, Debug)]
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])
}
}
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();
}
}
struct HandEvaluator {
combinations: [[u32; 8]; 14],
}
impl HandEvaluator {
fn new() -> Self {
let combinations = Self::precompute_combinations();
HandEvaluator { combinations }
}
fn precompute_combinations() -> [[u32; 8]; 14] {
let mut combinations = [[0; 8]; 14];
for i in 0..14 {
for j in 0..=i.min(7) {
if j == 0 || j == i {
combinations[i][j] = 1;
} else {
combinations[i][j] = combinations[i - 1][j] + combinations[i - 1][j - 1];
}
}
}
combinations
}
fn quinary_from_hand(cards: &[Card]) -> [u8; NUM_RANKS] {
let mut quinary = [0u8; NUM_RANKS];
for card in cards {
quinary[card.rank] += 1;
}
quinary
}
fn evaluate_hand(&self, hand: &[Card], community_cards: &[Card]) -> u32 {
let mut all_cards = hand.to_vec();
all_cards.extend_from_slice(community_cards);
let quinary = Self::quinary_from_hand(&all_cards);
self.hash_quinary(&quinary)
}
fn hash_quinary(&self, quinary: &[u8; NUM_RANKS]) -> u32 {
let mut hash = 0;
let mut remaining_k = 7; // Change remaining_k to usize
for (i, &count) in quinary.iter().enumerate() {
if remaining_k >= i {
hash += self.combinations[NUM_RANKS - 1 - i][remaining_k];
}
remaining_k = remaining_k.saturating_sub(count as usize); // Use saturating_sub to avoid negative values
}
hash
}
}
struct Player {
stack: u32,
bet: u32,
active: bool,
all_in: bool,
hand: Vec<Card>,
}
impl Player {
fn new(stack: u32) -> 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();
}
}
#[derive(Debug, Clone)]
struct GameState {
player_hands: Vec<Vec<Card>>,
community_cards: Vec<Card>,
player_stacks: Vec<u32>,
player_bets: Vec<u32>,
pot: u32,
current_player: usize,
phase: Phase,
}
struct RLObservation {
state: GameState,
min_call: u32,
}
struct PokerEnvironment<F>
where
F: Fn(usize, &RLObservation) -> Action,
{
num_players: usize,
players: Vec<Player>,
deck: Deck,
pot: u32,
min_call: u32,
last_raise: u32,
current_player: usize,
dealer_position: usize,
phase: Phase,
betting_round_over: bool,
community_cards: Vec<Card>,
last_aggressor: Option<usize>,
agent_function: F,
evaluator: HandEvaluator,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
PreFlop,
Flop,
Turn,
River,
Showdown,
}
impl<F> PokerEnvironment<F>
where
F: Fn(usize, &RLObservation) -> Action,
{
fn new(num_players: usize, agent_function: F) -> PokerEnvironment<F> {
let evaluator = HandEvaluator::new();
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,
evaluator,
};
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_single_hand(&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_rl_observation();
let action = (self.agent_function)(player_id, &observation);
self.step(action);
} else {
self.next_player();
}
}
self.resolve_hand();
}
fn get_rl_observation(&self) -> RLObservation {
RLObservation {
state: GameState {
player_hands: self.players.iter().map(|p| p.hand.clone()).collect(),
community_cards: self.community_cards.clone(),
player_stacks: self.players.iter().map(|p| p.stack).collect(),
player_bets: self.players.iter().map(|p| p.bet).collect(),
pot: self.pot,
current_player: self.current_player,
phase: self.phase,
},
min_call: self.min_call,
}
}
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_hand(&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 = self.evaluator.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 u32;
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: u32) {
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 random_agent_function(_player_id: usize, _observation: &RLObservation) -> Action {
let mut rng = thread_rng();
match rng.gen_range(0..3) {
0 => Action::Fold,
1 => Action::Call,
_ => Action::Raise,
}
}
fn main() {
let agent_function = random_agent_function;
let mut env = PokerEnvironment::new(NUM_PLAYERS, agent_function);
env.play_single_hand();
println!("Hand simulation completed.");
}
Key Modifications
Type Fix in hash_quinary:
Changed remaining_k to usize.
Used saturating_sub to safely subtract count as usize from remaining_k, preventing underflow.
These changes resolve the type mismatch errors and should allow the program to compile and run correctly.
Summary of Changes:
Remove Unnecessary Comparison: Removed if remaining_k < 0 check since remaining_k is a usize and cannot be less than 0.
This addresses the warning you're observing without changing the logic since the safety check is inherently handled by using usize. With this fix, your program should both compile and run without warnings.
Here are a few alternative names that might be more descriptive:
GameObservation: Simple and indicates that it provides an overview of the game's current state.
PokerStateView: Suggests a view or snapshot of the current poker game state.
PlayerViewState: Implies that the structure represents what a player might observe.
GameSnapshot: Indicates a captured view of the game's current state.
Here's how you might rename RLObservation to GameObservation in the code to improve readability and understanding:
rust
// Comprehensive game state for RL agents
#[derive(Debug, Clone)]
struct GameState {
player_hands: Vec<Vec<Card>>, // Each player's hole cards
community_cards: Vec<Card>, // The shared community cards
player_stacks: Vec<u32>, // Each player's current stack
player_bets: Vec<u32>, // Each player's current bet
pot: u32, // Current size of the pot
current_player: usize, // Index of the current player
phase: Phase, // Current phase of the game
}
// Renamed struct
struct GameObservation {
state: GameState, // Detailed game state
min_call: u32, // Minimum amount needed to call
}
fn random_agent_function(_player_id: usize, _observation: &GameObservation) -> Action {
let mut rng = thread_rng();
match rng.gen_range(0..3) {
0 => Action::Fold,
1 => Action::Call,
_ => Action::Raise,
}
}
// Make sure to update all references to RLObservation in the rest of your code
After renaming RLObservation to GameObservation, be sure to update all references to the old name in your code, such as function signatures, method implementations, and any other usage in the PokerEnvironment struct. This refactor helps clarify that this struct is providing a snapshot of the game state, which is especially helpful for agents or observers assessing the current scenario.
// Comprehensive game state for RL agents
#[derive(Debug, Clone)]
struct GameState {
player_hands: Vec<Vec<Card>>, // Each player's hole cards
community_cards: Vec<Card>, // The shared community cards
player_stacks: Vec<u32>, // Each player's current stack
player_bets: Vec<u32>, // Each player's current bet
pot: u32, // Current size of the pot
current_player: usize, // Index of the current player
phase: Phase, // Current phase of the game
}
// Renamed struct
struct Observation {
state: GameState, // Detailed game state
min_call: u32, // Minimum amount needed to call
}
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,
}
}
// Make sure to update all references to RLObservation in the rest of your code
Things to Update:
Function Parameters: Change any references to RLObservation to Observation, e.g., in random_agent_function.
Method Implementations: If there are methods that use RLObservation, update them to use Observation.
Variable Declarations: Ensure that any variable declarations that were using the previous name now use Observation.
By making this change, your code should be clearer in intention while maintaining its current functionality.