tetris/src/random.rs

43 lines
918 B
Rust

use crate::Tetrino;
use rand::{rngs::ThreadRng, seq::SliceRandom, thread_rng};
pub struct RandomSystem {
rng: ThreadRng,
bag: [Tetrino; 7],
cur_pos: usize,
}
impl RandomSystem {
pub fn new() -> Self {
let rng = thread_rng();
RandomSystem {
rng: rng,
bag: [Tetrino::I; 7],
cur_pos: 0,
}
}
pub fn get_tetrino(&mut self) -> Tetrino {
if self.cur_pos == 0 {
self.refresh_bag();
}
let to_return = self.bag[self.cur_pos];
self.cur_pos = (self.cur_pos + 1) % 7;
to_return
}
fn refresh_bag(&mut self) {
self.bag = [
Tetrino::I,
Tetrino::O,
Tetrino::T,
Tetrino::S,
Tetrino::Z,
Tetrino::J,
Tetrino::L,
];
self.bag.shuffle(&mut self.rng);
self.cur_pos = 0;
}
}