fair/games/
keno.rs

1//! # provably fair keno
2//!
3
4/*
5Keno
6Traditional Keno games require the selection of 10 possible game events in the form of hits on a
7board. To achieve this, we multiply each float by the number of possible unique squares that exist.
8Once a hit has been placed, it cannot be chosen again, which changes the pool size of the possible
9outcomes. This is done by subtracting the size of possible maximum outcomes by 1 for each iteration
10of game event result generated using the corresponding float provided, using the following index:
11
12// Index of 0 to 39 : 1 to 40
13const SQUARES = [
14  1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
15  11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
16  21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
17  31, 32, 33, 34, 35, 36, 37, 38, 39, 40 ];
18
19const hit = SQUARES[Math.floor(float * 40)];
20
21The fisher-yates shuffle implementation is utilised to prevent duplicate possible hits being generated.
22*/
23
24pub use crate::rng::{ProvablyFairConfig, ProvablyFairRNG};
25use std::fmt;
26
27#[derive(Debug)]
28pub struct SimulationResult {
29    pub squares: Vec<u8>,
30}
31
32impl fmt::Display for SimulationResult {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        write!(f, "Squares: {:?}", self.squares)
35    }
36}
37
38pub fn simulate(config: ProvablyFairConfig) -> SimulationResult {
39    let mut rng: ProvablyFairRNG<f64> = ProvablyFairRNG::from_config(config);
40
41    let mut remaining_squares: Vec<u8> = (1..41).collect();
42
43    let picked_squares: Vec<_> = (0..10)
44        .map(|_| {
45            let f = rng.next().unwrap();
46            let idx = (f * remaining_squares.len() as f64) as usize;
47            // println!("idx: {}, remaining: {:?}", idx, remaining_squares);
48            let n = *remaining_squares.get(idx).unwrap();
49            remaining_squares.remove(idx);
50            n
51        })
52        .collect();
53
54    SimulationResult {
55        squares: picked_squares,
56    }
57}
58
59#[cfg(test)]
60mod test {
61    use super::*;
62
63    #[test]
64    fn simulate_plinko_test() {
65        let config = ProvablyFairConfig::new("client seed", "server seed", 1);
66        assert_eq!(
67            simulate(config).squares,
68            vec![30, 26, 10, 37, 22, 35, 25, 24, 39, 4]
69        );
70        let config = ProvablyFairConfig::new("client seed", "server seed", 2);
71        assert_eq!(
72            simulate(config).squares,
73            vec![22, 26, 8, 4, 3, 19, 9, 2, 34, 10]
74        );
75    }
76}