ceelo-core 0.1.2

Logic for the 'Cee-Lo' Dice Game
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! This library is meant to be an "engine" for simulating the Cee-Lo Game. The game's mechanics aren't very simple, so I wrote this library to make sure I got it right and not mix game logic with implementation details.

use std::{io::Write, rc::Rc};

use either::Either;
use rand::random_range;

/// Stand in for the information known at the time the player or bank will make a bet.
pub enum WagerData {
    PlayerWager,
    BankWager,
}

/// Types implenting this Trait will be able to make an informed wager.
pub trait Wager {
    fn wager(&self, data: WagerData) -> u32;
}

#[derive(Eq, Hash, PartialEq, Clone, Debug)]
pub struct Player {
    name: String,
}

/// Identifier for Players in a  Cee-Lo Game.
impl Player {
    /// Introduces named players
    #[must_use]
    pub const fn new(name: String) -> Self {
        Self { name }
    }
}

/// Stores the amount of money a player has in addition to their betting strategy.
#[derive(Clone)]
pub struct PlayerData {
    points: u32,
    wager: Rc<dyn Wager>,
}

impl PlayerData {
    /// Initialises a some new player data using the betting strategy `wager` and initial amount of money `points`.
    pub const fn new(wager: Rc<dyn Wager>, points: u32) -> Self {
        Self { points, wager }
    }
}

impl std::fmt::Debug for PlayerData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PlayerData")
            .field("points", &self.points)
            .field(
                "wager",
                &"Wager is `Rc<dyn Wager>` and therefore not `Debug`able",
            )
            .finish()
    }
}

pub type Bet = u32;
/// This helper function helps to keep score of all of the bets.
// return type is (faded_bank_bet, player_left_over_bet)
#[must_use]
pub const fn fade_bet(bank_bet: u32, player_bet: u32) -> (u32, u32) {
    let leftovers = bank_bet.saturating_sub(player_bet);

    (
        leftovers,
        if leftovers == 0 { bank_bet } else { player_bet },
    )
}

/// In Cee-Lo, it is necessary for the bank to make an initial bet through the use of it's `wager` function. The other players will then in order choose some portion of the bank's bet to "cover". We accomplish this by calling the players' `wager` functions. Once the bank's bet is completely "covered", no more betting can occur until the round ends.
#[must_use]
pub fn fade_bets(players: Vec<(Player, PlayerData)>) -> Vec<(Player, PlayerData, Bet)> {
    // call bank and other players' wager function progressively "updating" wagers
    let (bank, players) = {
        let mut players = players;
        (players.remove(0), players)
    };
    let original_bank_wager = bank.1.wager.wager(WagerData::BankWager);
    let mut bank_wager = original_bank_wager;
    let players: Vec<(Player, PlayerData, Bet)> = players
        .into_iter()
        .map(|(player, player_data)| {
            let faded_wager = fade_bet(bank_wager, player_data.wager.wager(WagerData::PlayerWager));
            bank_wager = faded_wager.0;
            (player, player_data, faded_wager.1)
        })
        .collect();
    let mut new_players = players;
    let (bank, bank_data) = bank;
    new_players.insert(0, (bank, bank_data, original_bank_wager));
    new_players
}

/// Helper function that rolls 3d6 and gives the result.
#[must_use]
pub fn roll_dice() -> (u8, u8, u8) {
    (
        random_range(1..6 + 1),
        random_range(1..6 + 1),
        random_range(1..6 + 1),
    )
}

/// This struct is necessary because whenever a valid roll occurs in Cee-Lo, we can evaluate it:
/// - `X-X-X`, `4-5-6` and `X-X-6` are all instant wins if rolled
/// - Finally, `X-X-Y`, where 6 != Y != 1, is setting a point of Y
/// - `1-2-3` and `X-X-1` are instant losses
///
/// This struct represents these three cases.
#[derive(PartialEq, Debug, Eq, Clone)]
pub enum Rolls {
    InstantWin { multiplier: u8 },
    Point { point: u8, other: u8 }, // point is never 6 because that's instant win tho
    Loss,
}

/// Type representing the need to Reroll the dice in hopes of a valid combination.
#[derive(Debug)]
pub struct Reroll;

/// This Trait impl indicated that not all dice rolls are valid. In fact, the only valid dice rolls are of the form:
/// - Triples `X-X-X`
/// - Doubles `X-X-Y`
/// - Four-Five-Six `4-5-6`
/// - One-Two-Three `1-2-3`
///
/// In Cee-Lo if one of these combinations isn't rolled the player must reroll.
impl TryFrom<(u8, u8, u8)> for Rolls {
    type Error = Reroll;

    fn try_from(value: (u8, u8, u8)) -> Result<Self, Self::Error> {
        match (value.0 == value.1, value.1 == value.2) {
            (true, true) => Ok(Self::InstantWin {
                multiplier: if value.0 == 1 { 5 } else { 3 },
            }),
            (true, false) => {
                if value.2 == 6 {
                    Ok(Self::InstantWin { multiplier: 1 })
                } else if value.2 == 1 {
                    Ok(Self::Loss)
                } else {
                    Ok(Self::Point {
                        point: value.2,
                        other: value.0,
                    })
                }
            }
            (false, true) => {
                if value.0 == 6 {
                    Ok(Self::InstantWin { multiplier: 1 })
                } else if value.0 == 1 {
                    Ok(Self::Loss)
                } else {
                    Ok(Self::Point {
                        point: value.0,
                        other: value.1,
                    })
                }
            }
            (false, false) => {
                if value.0 == value.2 {
                    if value.1 == 6 {
                        Ok(Self::InstantWin { multiplier: 1 })
                    } else if value.1 == 1 {
                        Ok(Self::Loss)
                    } else {
                        Ok(Self::Point {
                            point: value.1,
                            other: value.0,
                        })
                    }
                } else {
                    let p = [value.0, value.1, value.2];
                    if p.contains(&4) && p.contains(&5) && p.contains(&6) {
                        Ok(Self::InstantWin { multiplier: 2 })
                    } else if p.contains(&1) && p.contains(&2) && p.contains(&3) {
                        Ok(Self::Loss)
                    } else {
                        Err(Reroll)
                    }
                }
            }
        }
    }
}

/// Using recursion to our advantage to always get a valid roll. This will run forever if you are particularly unlucky.
#[must_use]
pub fn always_roll() -> ((u8, u8, u8), Rolls) {
    let mut raw = roll_dice();
    loop {
        if let Ok(res) = Rolls::try_from(raw) {
            return (raw, res);
        }
        raw = roll_dice();
    }
}

/// All players roll the dice in this phase. Both the raw dice result and "Quality" are stored for later.
#[must_use]
pub fn everyone_roll(
    players: Vec<(Player, PlayerData, Bet)>,
) -> Vec<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)> {
    let mut rolls = vec![];
    for (player, player_data, wager) in players {
        let (roll_raw, roll) = always_roll();
        rolls.push((player, player_data, wager, roll_raw, roll));
    }
    rolls
}

/// Struct for storing if the Bank or Player had a higher quality dice roll than each other and how. In Cee-Lo, payouts can be up to 5 times the initial bet.
#[derive(Clone)]
pub enum WinOrLose {
    InstWin(u8),
    Win,
    Tie,
    Lose(u8),
}

/// Helper function to determine how the players in the game won or lost
// it's sufficent to track the players besides the bank
#[must_use]
pub fn wins_and_losses(
    players: Vec<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)>,
) -> Vec<(
    Player,
    PlayerData,
    Bet,
    (u8, u8, u8),
    Rolls,
    Option<WinOrLose>,
)> {
    let (bank, players) = {
        let mut players = players;
        (players.remove(0), players)
    };

    match bank.4 {
        // bank gets all the money
        Rolls::InstantWin { multiplier } => vec![players
            .into_iter()
            .map(|(player, pd, b, rr, r)| (player, pd, b, rr, r, Some(WinOrLose::Lose(multiplier))))
            .collect::<Vec<(
                Player,
                PlayerData,
                Bet,
                (u8, u8, u8),
                Rolls,
                Option<WinOrLose>,
            )>>()]
        .into_iter()
        .fold(std::iter::empty().collect(), |_, x| {
            let mut unpushed = x;
            let (bpl, bpd, bbet, brr, br) = &bank;

            unpushed.insert(0, (bpl.clone(), bpd.clone(), *bbet, *brr, br.clone(), None));
            unpushed
        }),
        Rolls::Point {
            point: bank_point,
            other: _,
        } => {
            let mut win_and_losses = Vec::new();
            for (player, pd, b, rr, player_roll) in players {
                match player_roll {
                    Rolls::InstantWin { multiplier } => {
                        win_and_losses.push((
                            player,
                            pd,
                            b,
                            rr,
                            player_roll,
                            Some(WinOrLose::InstWin(multiplier)),
                        ));
                    }
                    Rolls::Point {
                        point: player_point,
                        other: _,
                    } => match player_point.cmp(&bank_point) {
                        std::cmp::Ordering::Less => {
                            win_and_losses.push((
                                player,
                                pd,
                                b,
                                rr,
                                player_roll,
                                Some(WinOrLose::Lose(1)),
                            ));
                        }
                        std::cmp::Ordering::Equal => {
                            win_and_losses.push((
                                player,
                                pd,
                                b,
                                rr,
                                player_roll,
                                Some(WinOrLose::Tie),
                            ));
                        }
                        std::cmp::Ordering::Greater => {
                            win_and_losses.push((
                                player,
                                pd,
                                b,
                                rr,
                                player_roll,
                                Some(WinOrLose::Win),
                            ));
                        }
                    },
                    Rolls::Loss => {
                        win_and_losses.push((
                            player,
                            pd,
                            b,
                            rr,
                            player_roll,
                            Some(WinOrLose::Lose(1)),
                        ));
                    }
                }
            }
            let (pl, pd, bet, rr, rolls) = bank;
            let new_bank = (pl, pd, bet, rr, rolls, None);
            win_and_losses.insert(0, new_bank);
            win_and_losses
        }
        // bank pays out in this situation
        Rolls::Loss => {
            let mut handled: Vec<(
                Player,
                PlayerData,
                u32,
                (u8, u8, u8),
                Rolls,
                Option<WinOrLose>,
            )> = players
                .into_iter()
                .map(|(player, pd, b, rr, r)| (player, pd, b, rr, r, Some(WinOrLose::InstWin(1))))
                .collect();
            let (pl, pd, bet, rr, rolls) = bank;
            let new_bank = (pl, pd, bet, rr, rolls, Some(WinOrLose::Lose(1)));
            handled.insert(0, new_bank);
            handled
        }
    }
}

impl WinOrLose {
    /// Helper predicate to seperate winners from losers. I decided it would be more fair to have the bank take money from losers first and then give to winners. This way, there's a lower likelihood that the bank will run out of money to pay out winners.
    #[must_use]
    pub const fn is_win(&self) -> bool {
        match self {
            Self::InstWin(_) | Self::Win | Self::Tie => true,
            Self::Lose(_) => false,
        }
    }
}

/// Seperates the bank from the players as they don't work the same way as regular players when paying out bets, since it revolves around them.
#[must_use]
pub fn wins_and_losses_no_bank(
    players: Vec<(
        Player,
        PlayerData,
        u32,
        (u8, u8, u8),
        Rolls,
        Option<WinOrLose>,
    )>,
) -> (
    (
        Player,
        PlayerData,
        u32,
        (u8, u8, u8),
        Rolls,
        Option<WinOrLose>,
    ),
    Vec<(Player, PlayerData, u32, (u8, u8, u8), Rolls, WinOrLose)>,
) {
    let mut the_players = players;
    let bank = the_players.remove(0);
    let some_players = the_players
        .into_iter()
        .filter_map(|(pl, pd, bet, rr, roll, won_or_lost)| {
            won_or_lost.map(|wol| (pl, pd, bet, rr, roll, wol))
        })
        .collect();
    (bank, some_players)
}

/// In this stage, players exchange money and a new bank is chosen if need be.
#[must_use]
pub fn payout(
    players: Vec<(
        Player,
        PlayerData,
        Bet,
        (u8, u8, u8),
        Rolls,
        Option<WinOrLose>,
    )>,
) -> Vec<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)> {
    let (mut bank, the_players) = wins_and_losses_no_bank(players);
    let losers_then_winners = {
        let (mut losers, mut winners): (
            Vec<(Player, PlayerData, u32, (u8, u8, u8), Rolls, WinOrLose)>,
            _,
        ) = the_players
            .into_iter()
            .partition(|player| player.5.is_win());

        losers.append(&mut winners);
        losers
    };
    let mut upd_players = vec![];
    let mut winners = 0usize;
    let mut instant_won = None;
    for (player, pd, bet, rr, roll, win_or_lose) in losers_then_winners {
        match win_or_lose {
            WinOrLose::InstWin(mult) => {
                let (bank_leftover, player_left_over) =
                    fade_bet(bank.1.points, bet.saturating_mul(mult.into()));
                bank.1.points = bank_leftover;
                let new_player = (
                    player.clone(),
                    PlayerData {
                        points: pd.points.saturating_add(player_left_over),
                        wager: pd.wager,
                    },
                    bet,
                    rr,
                    roll,
                );
                instant_won = Some(new_player.clone());
                upd_players.push(new_player);
            }
            WinOrLose::Win => {
                winners = winners.saturating_add(1);
                let (bank_leftover, player_leftover) = fade_bet(bank.1.points, bet);
                bank.1.points = bank_leftover;
                upd_players.push((
                    player,
                    PlayerData {
                        points: pd.points.saturating_add(player_leftover),
                        wager: pd.wager,
                    },
                    bet,
                    rr,
                    roll,
                ));
            }
            WinOrLose::Tie => upd_players.push((player, pd, bet, rr, roll)),
            WinOrLose::Lose(mult) => {
                let (player_leftover, player_loss) =
                    fade_bet(pd.points, bet.saturating_mul(mult.into()));
                bank.1.points = bank.1.points.saturating_add(player_loss);

                upd_players.push((
                    player,
                    PlayerData {
                        points: player_leftover,
                        wager: pd.wager,
                    },
                    bet,
                    rr,
                    roll,
                ));
            }
        }
    }
    let new_bank = {
        let (bank_player, bank_player_data, bbet, brr, brolls, ..) = bank;
        (bank_player, bank_player_data, bbet, brr, brolls)
    };

    if let Some(next_bank) = instant_won {
        upd_players.push(new_bank);
        // remove from front until front = next_bank if names match
        loop {
            let front = upd_players.remove(0);
            // make player the bank
            if front.0 == next_bank.0 {
                upd_players.insert(0, front);
                break;
            }
            upd_players.push(front);
        }
    } else if winners == upd_players.len().saturating_add(1) || bank.5.is_some() {
        upd_players.push(new_bank);
    } else {
        upd_players.insert(0, new_bank);
    }
    upd_players
}

/// Returns the only player standing or multiple players.
#[must_use]
pub fn winner(
    players: Vec<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)>,
) -> Either<
    (Player, PlayerData, Bet, (u8, u8, u8), Rolls),
    Vec<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)>,
> {
    match players {
        mut lone if lone.len() == 1 => Either::Left(lone.remove(0)),
        multiple => either::Right(multiple),
    }
}

/// Simple Alias for the history of the game.
pub type History = Vec<Vec<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)>>;

/// This is the game loop that decides the winner of the game. Returns the winning player and the game history.
#[must_use]
pub fn play_until_winner(
    mut players: Vec<(Player, PlayerData)>,
) -> ((Player, PlayerData, Bet, (u8, u8, u8), Rolls), History) {
    let mut history = vec![];
    loop {
        let payed = payout(wins_and_losses(everyone_roll(fade_bets(players.clone()))));
        history.push(payed.clone());
        // for (player, pd, bet, (r1, r2, r3), roll) in payed.clone() {
        //     println!("<{player}> <{pd}> <{bet}> <{roll}> <({r1}, {r2}, {r3})>");
        // }
        let maybe_winner = winner(payed);
        let mut the_winner: Option<(Player, PlayerData, Bet, (u8, u8, u8), Rolls)> = None;
        match maybe_winner {
            Either::Left(winner) => the_winner = Some(winner),
            Either::Right(not_winners) => {
                // println!("no winner");
                players = not_winners
                    .into_iter()
                    .map(|(player, pd, ..)| (player, pd))
                    .collect();
                players.retain(|player| player.1.points != 0);
            }
        }
        if let Some(winner) = the_winner {
            return (winner, history);
        }
    }
}

/// Wager struct for betting arbitrary amounts of money.
pub struct WagerN(
    /// Amount of money being bet each round.
    pub u32,
);

impl Wager for WagerN {
    /// Simply wagers the amount of money specified by `WagerN`
    fn wager(&self, _: WagerData) -> u32 {
        self.0
    }
}

/// Basic implementation of players wagering at a console.
pub struct WagerConsole;
impl Wager for WagerConsole {
    /// Wagers by parsing user input. Guarantees user input using loops.
    fn wager(&self, _data: WagerData) -> u32 {
        loop {
            let mut buffer = String::new();
            print!("Wager Here => ");
            let _ = std::io::stdout().flush();
            if std::io::stdin().read_line(&mut buffer).is_ok() {
                if let Ok(i) = buffer.trim().parse::<u32>() {
                    return i;
                }
                println!("Failed to parse");
            }
        }
    }
}

/// Implements wagers for all basic functions that return a `u32`. Example:
/// ```
/// fn random_wager(_: WagerData) -> u32 {
///     rand::random_range(0..500)
/// }
///
/// fn main() {
/// let pdata = PlayerData::new(Rc::new(random_wager), 300);
/// }
/// ```
impl<T: Fn(WagerData) -> u32> Wager for T {
    /// Simply calls the function on `WagerData`.
    fn wager(&self, data: WagerData) -> u32 {
        self(data)
    }
}

#[must_use]
pub const fn add(left: u64, right: u64) -> u64 {
    left.saturating_add(right)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}