wasm4fun-random 0.1.0

Random number generators primitives and subsystems for WASM-4 fantasy console
Documentation
// Copyright Claudio Mattera 2022.
//
// Distributed under the MIT License or the Apache 2.0 License at your option.
// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
// online at
// https://opensource.org/licenses/MIT
// https://opensource.org/licenses/Apache-2.0

use core::ops::Range;

use rand_core::{RngCore, SeedableRng};
use rand_xorshift::XorShiftRng;

use wasm4fun_log::debug;
use wasm4fun_time::Ticker;

#[derive(Debug)]
pub struct Generator(XorShiftRng);

impl Generator {
    pub fn new_from_user_interaction() -> Self {
        let frames_from_beginning: u64 = Ticker.since_startup();
        let seed = frames_from_beginning;

        debug!("Initializing random generator with seed {}", seed);
        Self::new(seed)
    }

    pub fn new(seed: u64) -> Self {
        Self(XorShiftRng::seed_from_u64(seed))
    }

    #[allow(unused)]
    pub fn gen_range(&mut self, range: Range<i32>) -> i32 {
        let range_length = (range.end - range.start) as u32;
        let random_u32 = self.0.next_u32();
        let random_ranged = random_u32 % range_length;
        random_ranged as i32 + range.start
    }
}