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