tetris/src/random.rs

43 lines
987 B
Rust

use crate::Tetromino;
use rand::{rngs::ThreadRng, seq::SliceRandom, thread_rng};
pub struct RandomSystem {
rng: ThreadRng,
bag: [Tetromino; 7],
cur_pos: usize,
}
impl RandomSystem {
pub fn new() -> Self {
let rng = thread_rng();
RandomSystem {
rng: rng,
bag: [Tetromino::I; 7], // Default value, should get init on first get
cur_pos: 0,
}
}
pub fn get_tetrino(&mut self) -> Tetromino {
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 = [
Tetromino::I,
Tetromino::O,
Tetromino::T,
Tetromino::S,
Tetromino::Z,
Tetromino::J,
Tetromino::L,
];
self.bag.shuffle(&mut self.rng);
self.cur_pos = 0;
}
}