1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use rand::rng;
use crate::core::{CardBitSet, FlatDeck, Hand, PlayerBitSet, RSPokerError, Rank, Rankable};
/// Current state of a game.
#[derive(Debug)]
pub struct MonteCarloGame {
/// Flatten deck
deck: FlatDeck,
/// Hands still playing.
hands: Vec<Hand>,
starting_hands: Vec<Hand>,
// The number of community cards that will be dealt to each player.
num_community_cards: usize,
// The number of needed cards each round
cards_needed: usize,
current_offset: usize,
}
impl MonteCarloGame {
/// If we already have hands then lets start there.
pub fn new(hands: Vec<Hand>) -> Result<Self, RSPokerError> {
let mut deck = CardBitSet::default();
let mut max_hand_size: usize = 0;
let mut cards_needed = 0;
for hand in &hands {
let hand_size = hand.count();
if hand_size > 7 {
return Err(RSPokerError::HoldemHandSize);
}
// The largest hand size sets how many community cards to add
max_hand_size = max_hand_size.max(hand_size);
// Compute the number of cards needed per round.
cards_needed += 7 - hand_size;
for card in hand.iter() {
deck.remove(card);
}
}
let num_community_cards = (7 - max_hand_size).max(0);
let flat_deck: FlatDeck = deck.into();
// Grab the deck.len() so that any call to shuffle_if_needed
// will result in a shuffling.
let offset = flat_deck.len();
Ok(Self {
deck: flat_deck,
starting_hands: hands.clone(),
hands,
num_community_cards,
cards_needed,
current_offset: offset,
})
}
/// Simulate finishing a holdem game.
///
/// This will fill out the board and then return the tuple
/// of which hand had the best rank in end.
pub fn simulate(&mut self) -> (PlayerBitSet, Rank) {
self.shuffle_if_needed();
let community_start_idx = self.current_offset;
let community_end_idx = self.current_offset + self.num_community_cards;
self.current_offset += self.num_community_cards;
for h in &mut self.hands {
h.extend(self.deck[community_start_idx..community_end_idx].to_owned());
let hole_needed = 7 - h.count();
let range = &self.deck[self.current_offset..self.current_offset + hole_needed];
h.extend(range.to_owned());
self.current_offset += hole_needed;
}
// Now get the best rank of all the possible hands.
self.hands.iter().map(|h| h.rank()).enumerate().fold(
(PlayerBitSet::default(), Rank::HighCard(0)),
|(mut found, max_rank), (idx, rank)| {
match rank.cmp(&max_rank) {
std::cmp::Ordering::Equal => {
// If this is a tie then add the index.
found.enable(idx);
(found, rank)
}
std::cmp::Ordering::Greater => {
// If this is the higest then reset all the bitset
// Then set only the current hand's index as true
found = PlayerBitSet::default();
found.enable(idx);
(found, rank)
}
// Otherwise keep what we've already found.
_ => (found, max_rank),
}
},
)
}
/// Reset the game state.
pub fn reset(&mut self) {
self.hands
.iter_mut()
.zip(self.starting_hands.iter())
.for_each(|(h, s)| {
h.clear();
h.extend(s.iter());
});
}
fn shuffle_if_needed(&mut self) {
if self.current_offset + self.cards_needed >= self.deck.len() {
self.current_offset = 0;
let mut rng = rng();
self.deck.shuffle(&mut rng);
}
}
/// Estimate the equity of each hand by simulating the game `iterations`
/// times. This will return a vector of floats where each
/// float is the estimated percentage of the pot that the player has in
/// expected value.
///
/// This does not take in account subsequent betting rounds.
///
/// # Arguments
///
/// * `iterations` - The number of times to simulate the game.
///
/// # Example
///
/// ```
/// use rs_poker::core::{Card, Hand, Suit, Value};
/// use rs_poker::holdem::MonteCarloGame;
///
/// let hero = Hand::new_with_cards(vec![
/// Card::new(Value::Jack, Suit::Spade),
/// Card::new(Value::Jack, Suit::Heart),
/// ]);
///
/// let villan = Hand::new_with_cards(vec![
/// Card::new(Value::Ace, Suit::Spade),
/// Card::new(Value::King, Suit::Spade),
/// ]);
///
/// let mut monte_sim = MonteCarloGame::new(vec![hero, villan]).unwrap();
/// let equity = monte_sim.estimate_equity(1000);
///
/// // Jacks with the blocker on spades hold up most of the time
/// assert!(equity[0] > equity[1]);
/// ```
pub fn estimate_equity(&mut self, iterations: usize) -> Vec<f32> {
let mut values = vec![0.0; self.hands.len()];
for _ in 0..iterations {
let (winners, _) = self.simulate();
// Reset the hands
self.reset();
// each player gets the pot divided by the number of people with exactly the
// same hand value. This is to make sure that ties are correctly valued.
let value = 1.0 / winners.count() as f32;
for idx in winners.ones() {
values[idx] += value;
}
}
// Normalize later on in the hopes of not making
// each value actually zero
for v in values.iter_mut() {
*v /= iterations as f32;
}
values
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::core::Card;
use crate::core::Suit;
use crate::core::Value;
#[test]
fn test_simulate_pocket_pair() {
let hands = ["AdAh", "2c2s"]
.iter()
.map(|s| Hand::new_from_str(s).unwrap())
.collect();
let mut g = MonteCarloGame::new(hands).unwrap();
let result = g.simulate();
assert!(result.1 >= Rank::OnePair(0));
}
#[test]
fn test_simulate_pocket_pair_with_board() {
let board = vec![
Card {
suit: Suit::Spade,
value: Value::Ace,
},
Card {
suit: Suit::Diamond,
value: Value::Three,
},
Card {
suit: Suit::Diamond,
value: Value::Four,
},
];
let mut hands: Vec<Hand> = ["AdAh", "2c2s"]
.iter()
.map(|s| Hand::new_from_str(s).unwrap())
.collect();
for h in hands.iter_mut() {
for c in &board {
(*h).insert(*c);
}
}
let mut g = MonteCarloGame::new(hands).unwrap();
let result = g.simulate();
assert!(result.1 >= Rank::ThreeOfAKind(0));
}
#[test]
fn test_unseen_hole_cards() {
let hands = vec![Hand::new_from_str("KsKd").unwrap(), Hand::default()];
let mut g = MonteCarloGame::new(hands).unwrap();
for _i in 0..10_000 {
let result = g.simulate();
assert!(result.1 >= Rank::OnePair(11 << 13));
g.reset();
}
}
#[test]
fn test_simulate_set() {
let mut hands: Vec<Hand> = ["6d6h", "3d3h"]
.iter()
.map(|s| Hand::new_from_str(s).unwrap())
.collect();
let board: Vec<Card> = vec![
Card {
value: Value::Six,
suit: Suit::Spade,
},
Card {
value: Value::King,
suit: Suit::Diamond,
},
Card {
value: Value::Queen,
suit: Suit::Heart,
},
];
for h in hands.iter_mut() {
for c in &board {
(*h).insert(*c);
}
}
let mut g = MonteCarloGame::new(hands).unwrap();
let result = g.simulate();
assert!(result.1 >= Rank::ThreeOfAKind(4));
}
#[test]
fn test_simulate_equity_three_kind() {
let hero = Hand::new_with_cards(vec![
Card {
value: Value::Six,
suit: Suit::Spade,
},
Card {
value: Value::Six,
suit: Suit::Club,
},
Card {
value: Value::Six,
suit: Suit::Heart,
},
Card {
value: Value::King,
suit: Suit::Heart,
},
Card {
value: Value::Ten,
suit: Suit::Diamond,
},
]);
let board = vec![
Card {
value: Value::Six,
suit: Suit::Heart,
},
Card {
value: Value::King,
suit: Suit::Heart,
},
Card {
value: Value::Ten,
suit: Suit::Diamond,
},
];
let hands = vec![
hero,
Hand::new_with_cards(board.clone()),
Hand::new_with_cards(board.clone()),
Hand::new_with_cards(board.clone()),
Hand::new_with_cards(board),
];
let mut g = MonteCarloGame::new(hands).unwrap();
let equity = g.estimate_equity(1000);
assert!(equity[0] > equity[1]);
assert!(equity[0] > equity[2]);
assert!(equity[0] > equity[3]);
assert!(equity[0] > equity[4]);
}
#[test]
fn test_simulate_equity_lots_players() {
let mut rng = rng();
for in_hand in 2..7 {
for num_players in 3..9 {
let mut deck = FlatDeck::default();
deck.shuffle(&mut rng);
let hands: Vec<Hand> = deck[..]
.chunks(in_hand)
.take(num_players)
.map(|cards| Hand::new_with_cards(cards.to_owned()))
.collect();
let mut g = MonteCarloGame::new(hands.clone()).unwrap();
let _result = g.estimate_equity(1_000);
}
}
}
#[test]
fn test_simulate_equity_cleaned_hands() {
let mut rng = rng();
for in_hand in 2..7 {
for num_players in 3..9 {
let mut deck = FlatDeck::default();
deck.shuffle(&mut rng);
let clean_hands = deck[..]
.chunks(in_hand)
.take(num_players)
.map(|cards| Hand::new_with_cards(cards.to_owned()))
.enumerate()
.map(|(idx, h)| if idx == 0 { h } else { Hand::default() })
.collect();
let mut g = MonteCarloGame::new(clean_hands).unwrap();
let _result = g.estimate_equity(1_000);
}
}
}
}