robopoker 0.1.1

Implementations of Meta's Pluribus No-Limit Texas Hold-Em solution.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use super::action::Action;
use super::payout::Payout;
use super::seat::Seat;
use super::seat::State;
use super::Chips;
use super::N;
use super::STACK;
use crate::cards::board::Board;
use crate::cards::card::Card;
use crate::cards::deck::Deck;
use crate::cards::hand::Hand;
use crate::cards::observation::Observation;
use crate::cards::street::Street;
use crate::cards::strength::Strength;
use crate::play::continuation::Transition;
use crate::play::showdown::Showdown;
use crate::players::human::Human;

type Position = usize;
/// Rotation represents the memoryless state of the game in between actions.
///
/// It records both public and private data structs, and is responsible for managing the
/// rotation of players, the pot, and the board. Its immutable methods reveal
/// pure functions representing the rules of how the game may proceed.
/// This full game state will also be our CFR node representation.
#[derive(Debug, Clone, Copy)]
pub struct Game {
    seats: [Seat; N],
    chips: Chips,
    board: Board,
    dealer: Position,
    player: Position,
}

impl Game {
    pub fn root() -> Self {
        println!("root");
        let mut root = Self {
            chips: 0,
            seats: [Seat::new(STACK); N],
            board: Board::empty(),
            dealer: 0usize,
            player: 0usize,
        };
        root.rotate();
        root.deal_cards();
        root.post_blinds(Self::sblind());
        root.post_blinds(Self::bblind());
        root
    }

    /// HACK
    /// for chance transitions, only bc of Preflop,
    /// we use an arbitrary (MIN) draw card
    /// it will be "coerced" into an Edge::Chance
    /// variant in the end anyway, in MCCFR
    ///
    /// it should actually just be a fix to the
    /// Player Terminal Continuation complex
    /// information gets lost and reintorudced at different layers of abstraction
    pub fn children(&self) -> Vec<(Game, Action)> {
        match self.chooser() {
            Transition::Terminal => vec![],
            Transition::Awaiting(street) => {
                let mut child = self.clone();
                child.show_revealed(street);
                vec![(child, Action::Draw(Card::draw()))] //? TODO should we return a single draw? or use the street enum to drive this? let's use the street enum. it's inside of Awaiting(_). and we can condition on
            }
            Transition::Decision(_) => self
                .options()
                .into_iter()
                .map(|decision| {
                    assert!(!matches!(decision, Action::Draw(_)),);
                    assert!(!matches!(decision, Action::Blind(_)),);
                    let mut child = self.clone();
                    child.apply(decision);
                    (child, decision)
                })
                .collect(),
        }
    }

    /// play against yourself in an infinite loop
    /// similar to children(), except a single decision action will come from
    /// Human::act() rather than all possible decision actions
    /// coming from self.options()
    pub fn play() -> ! {
        let mut node = Self::root();
        loop {
            match node.chooser() {
                Transition::Terminal => {
                    node.into_terminal(); // node.clone(); node...(&mut self) ; node = node
                }
                Transition::Awaiting(street) => {
                    node.show_revealed(street); // node.clone(); node...(&mut self) ; node = node
                }
                Transition::Decision(_) => {
                    node.make_decision(); // node.clone(); node...(&mut self) ; node = node
                }
            }
        }
    }

    fn apply(&mut self, ref action: Action) {
        // assert!(self.options().contains(action));
        self.update_stdout(action);
        self.update_stacks(action);
        self.update_states(action);
        self.update_boards(action);
        self.update_nseats(action);
    }

    pub fn actor(&self) -> &Seat {
        self.actor_ref()
    }
    pub fn chips(&self) -> Chips {
        self.chips
    }
    pub fn board(&self) -> Board {
        self.board
    }
    pub fn options(&self) -> Vec<Action> {
        let mut options = Vec::new();
        if self.is_terminal() {
            return options;
        }
        if self.is_sampling() {
            // for card in self.deck() {}
            options.push(Action::Draw(self.deck().draw()));
            return options;
        }
        if self.can_call() {
            options.push(Action::Call(self.to_call()));
        }
        if self.can_raise() {
            options.push(Action::Raise(self.to_raise()));
        }
        if self.can_shove() {
            options.push(Action::Shove(self.to_shove()));
        }
        if self.can_check() {
            options.push(Action::Check);
        }
        if self.can_fold() {
            options.push(Action::Fold);
        }
        options
        //? TODO
        // nothing in here about Action::Blind() being possible,
        // it's only accessible from Game::root()
        // presumably we won't care about this
        // when we construct our MCCFR tree
    }
    pub fn chooser(&self) -> Transition {
        if self.is_terminal() {
            return Transition::Terminal;
        }
        if self.is_sampling() {
            return Transition::Awaiting(self.board.street().next());
        }
        if self.is_decision() {
            return Transition::Decision(self.actor_relative_idx());
        }
        unreachable!("game rules violated")
    }

    fn deck(&self) -> Deck {
        let board = Hand::from(self.board);
        let mut removed = Hand::add(Hand::empty(), board);
        for seat in self.seats.iter() {
            let hole = Hand::from(seat.cards());
            removed = Hand::add(removed, hole);
        }
        Deck::from(removed.complement())
    }
    fn actor_relative_idx(&self) -> Position {
        assert!(self.seats.len() == N);
        self.player.wrapping_sub(self.dealer) % N
    }
    fn actor_absolute_idx(&self) -> Position {
        assert!(self.seats.len() == N);
        (self.dealer + self.player) % N
    }
    fn actor_ref(&self) -> &Seat {
        let index = self.actor_absolute_idx();
        self.seats
            .get(index)
            .expect("index should be in bounds bc modulo")
    }
    fn actor_mut(&mut self) -> &mut Seat {
        let index = self.actor_absolute_idx();
        self.seats
            .get_mut(index)
            .expect("index should be in bounds bc modulo")
    }

    #[allow(dead_code)]
    fn effective_stack(&self) -> Chips {
        let mut totals = self
            .seats
            .iter()
            .map(|s| s.stack() + s.stake())
            .collect::<Vec<Chips>>();
        totals.sort_unstable();
        totals.pop().unwrap_or(0);
        totals.pop().unwrap_or(0)
    }
    fn effective_stake(&self) -> Chips {
        self.seats
            .iter()
            .map(|s| s.stake())
            .max()
            .expect("non-empty seats")
    }

    const fn bblind() -> Chips {
        2
    }
    const fn sblind() -> Chips {
        1
    }

    fn update_stacks(&mut self, action: &Action) {
        match action {
            Action::Call(bet) | Action::Blind(bet) | Action::Raise(bet) | Action::Shove(bet) => {
                self.chips += bet;
                self.actor_mut().bet(bet);
            }
            _ => {}
        }
    }
    fn update_states(&mut self, action: &Action) {
        match action {
            Action::Shove(_) => self.actor_mut().set_state(State::Shoving),
            Action::Fold => self.actor_mut().set_state(State::Folding),
            _ => {}
        }
    }
    fn update_boards(&mut self, action: &Action) {
        match action {
            Action::Draw(card) => self.board.add(card.clone()),
            _ => {}
        }
    }
    fn update_nseats(&mut self, action: &Action) {
        match action {
            Action::Draw(_) => {}
            _ => self.rotate(),
        }
    }
    fn update_stdout(&self, action: &Action) {
        match action {
            Action::Draw(_) => {
                println!("  {}", action);
            }
            _ => {
                println!("{} {}", self.actor_absolute_idx(), action);
            }
        }
    }
    fn rotate(&mut self) {
        'left: loop {
            self.player += 1;
            match self.actor_ref().state() {
                State::Playing => break 'left,
                State::Folding => continue 'left,
                State::Shoving => continue 'left,
            }
        }
    }

    //
    fn into_terminal(&mut self) {
        assert!(self.seats.iter().all(|s| s.stack() > 0), "game over");
        // conclusion of this hand
        self.give_chips();
        // beginning of next hand
        self.wipe_board();
        self.deal_cards();
        self.move_button();
        self.post_blinds(Self::sblind());
        self.post_blinds(Self::bblind());
    }
    fn give_chips(&mut self) {
        println!("::::::::::::::");
        println!("{}", self.board());
        for (i, (settlement, seat)) in self
            .settlement()
            .iter()
            .zip(self.seats.iter_mut())
            .enumerate()
        {
            println!("{} {} {:>7} {}", i, seat.cards(), seat.stack(), settlement);
            seat.win(settlement.reward);
        }
        println!();
    }
    fn wipe_board(&mut self) {
        self.chips = 0;
        self.board.clear();
        assert!(self.board.street() == Street::Pref);
    }
    fn deal_cards(&mut self) {
        assert!(self.board.street() == Street::Pref);
        let mut deck = Deck::new();
        for seat in self.seats.iter_mut() {
            seat.set_state(State::Playing);
            seat.set_cards(deck.hole());
            seat.set_stake();
            seat.set_spent();
        }
    }
    fn move_button(&mut self) {
        assert!(self.seats.len() == N);
        assert!(self.board.street() == Street::Pref);
        self.dealer += 1;
        self.dealer %= N;
        self.player = 0;
        self.rotate();
    }
    fn post_blinds(&mut self, blind: Chips) {
        assert!(self.board.street() == Street::Pref);
        let stack = self.actor_ref().stack();
        if blind < stack {
            self.apply(Action::Blind(blind))
        } else {
            self.apply(Action::Shove(stack))
        }
    }

    //
    fn show_revealed(&mut self, street: Street) {
        assert!(self.board.street().next() == street);
        println!("{}", street);
        self.player = 0;
        self.rotate();
        self.next_street_public();
        self.next_street_stacks();
    }
    fn next_street_public(&mut self) {
        let mut deck = self.deck();
        match self.board.street() {
            Street::Rive => unreachable!("terminal"),
            Street::Flop => self.apply(Action::Draw(deck.draw())),
            Street::Turn => self.apply(Action::Draw(deck.draw())),
            Street::Pref => {
                self.apply(Action::Draw(deck.draw()));
                self.apply(Action::Draw(deck.draw()));
                self.apply(Action::Draw(deck.draw()));
            }
        }
    }
    fn next_street_stacks(&mut self) {
        for seat in self.seats.iter_mut() {
            seat.set_stake();
        }
    }

    //
    fn make_decision(&mut self) {
        self.apply(Human::act(&self));
    }

    //
    fn is_terminal(&self) -> bool {
        self.board.street() == Street::Rive && self.is_everyone_waiting()
            || self.is_everyone_folding()
    }
    fn is_sampling(&self) -> bool {
        self.board.street() != Street::Rive && self.is_everyone_waiting()
    }
    fn is_decision(&self) -> bool {
        assert!(!self.is_terminal());
        assert!(!self.is_sampling());
        assert!(self.actor().state() == State::Playing);
        true
    }

    //
    fn is_everyone_waiting(&self) -> bool {
        self.is_everyone_shoving() || self.is_everyone_calling()
    }
    fn is_everyone_calling(&self) -> bool {
        self.is_everyone_matched() && self.is_everyone_decided()
    }
    fn is_everyone_shoving(&self) -> bool {
        self.player == 0
            && self
                .seats
                .iter()
                .filter(|s| s.state() == State::Playing)
                .count()
                == 1
            || self
                .seats
                .iter()
                .filter(|s| s.state() != State::Folding)
                .all(|s| s.state() == State::Shoving)
    }
    fn is_everyone_matched(&self) -> bool {
        let stake = self.effective_stake();
        self.seats
            .iter()
            .filter(|s| s.state() == State::Playing)
            .all(|s| s.stake() == stake)
    }
    fn is_everyone_folding(&self) -> bool {
        self.seats
            .iter()
            .filter(|s| s.state() != State::Folding)
            .count()
            == 1
    }
    fn is_everyone_decided(&self) -> bool {
        self.player
            > match self.board.street() {
                Street::Pref => N + 2,
                _ => N,
            }
    }

    //
    fn can_fold(&self) -> bool {
        self.to_call() > 0
    }
    fn can_call(&self) -> bool {
        self.can_fold() && self.to_call() <= self.actor_ref().stack()
    }
    fn can_check(&self) -> bool {
        self.effective_stake() == self.actor_ref().stake()
    }
    fn can_raise(&self) -> bool {
        self.to_shove() > self.to_raise()
    }
    fn can_shove(&self) -> bool {
        self.to_shove() > 0 && false
    }

    //
    pub fn to_call(&self) -> Chips {
        self.effective_stake() - self.actor_ref().stake()
    }
    pub fn to_shove(&self) -> Chips {
        self.actor_ref().stack()
    }
    pub fn to_raise(&self) -> Chips {
        let mut stakes = self
            .seats
            .iter()
            .filter(|s| s.state() != State::Folding)
            .map(|s| s.stake())
            .collect::<Vec<Chips>>();
        stakes.sort_unstable();
        let most_large_stake = stakes.pop().unwrap_or(0);
        let next_large_stake = stakes.pop().unwrap_or(0);
        let relative_raise = most_large_stake - self.actor().stake();
        let marginal_raise = most_large_stake - next_large_stake;
        let required_raise = std::cmp::max(marginal_raise, Self::bblind());
        relative_raise + required_raise
    }

    //
    pub fn settlement(&self) -> Vec<Payout> {
        assert!(self.is_terminal());
        Showdown::from(self.ledger()).settle()
    }
    fn ledger(&self) -> Vec<Payout> {
        self.seats
            .iter()
            .map(|seat| self.entry(seat))
            .collect::<Vec<Payout>>()
    }
    fn entry(&self, seat: &Seat) -> Payout {
        Payout {
            reward: 0,
            risked: seat.spent(),
            status: seat.state(),
            strength: self.strength(seat),
        }
    }
    fn strength(&self, seat: &Seat) -> Strength {
        Strength::from(Hand::add(
            Hand::from(seat.cards()),
            Hand::from(self.board()),
        ))
    }
}

impl std::fmt::Display for Game {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        for seat in self.seats.iter() {
            write!(f, "{:>6}", seat.stack())?;
        }
        write!(f, " :: {:>6} {}", self.chips, self.board)?;
        Ok(())
    }
}

impl From<&Game> for Observation {
    fn from(game: &Game) -> Self {
        Observation::from((
            Hand::from(game.actor().cards()), //
            Hand::from(game.board()),         //
        ))
    }
}