wasm4fun_random/
random.rs

1// Copyright Claudio Mattera 2022.
2//
3// Distributed under the MIT License or the Apache 2.0 License at your option.
4// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
5// online at
6// https://opensource.org/licenses/MIT
7// https://opensource.org/licenses/Apache-2.0
8
9use core::ops::Range;
10
11use rand_core::{RngCore, SeedableRng};
12use rand_xorshift::XorShiftRng;
13
14use wasm4fun_log::debug;
15use wasm4fun_time::Ticker;
16
17#[derive(Debug)]
18pub struct Generator(XorShiftRng);
19
20impl Generator {
21    pub fn new_from_user_interaction() -> Self {
22        let frames_from_beginning: u64 = Ticker.since_startup();
23        let seed = frames_from_beginning;
24
25        debug!("Initializing random generator with seed {}", seed);
26        Self::new(seed)
27    }
28
29    pub fn new(seed: u64) -> Self {
30        Self(XorShiftRng::seed_from_u64(seed))
31    }
32
33    #[allow(unused)]
34    pub fn gen_range(&mut self, range: Range<i32>) -> i32 {
35        let range_length = (range.end - range.start) as u32;
36        let random_u32 = self.0.next_u32();
37        let random_ranged = random_u32 % range_length;
38        random_ranged as i32 + range.start
39    }
40}