tetris/src/random.rs

44 lines
1.0 KiB
Rust
Raw Normal View History

2020-03-21 04:05:39 +00:00
use crate::tetromino::TetrominoType;
2019-10-28 06:42:09 +00:00
use rand::{rngs::ThreadRng, seq::SliceRandom, thread_rng};
2020-03-30 16:28:53 +00:00
#[derive(Clone, Copy, Debug)]
2019-10-28 06:42:09 +00:00
pub struct RandomSystem {
rng: ThreadRng,
2020-03-21 04:05:39 +00:00
bag: [TetrominoType; 7],
2019-10-28 06:42:09 +00:00
cur_pos: usize,
}
impl RandomSystem {
pub fn new() -> Self {
let rng = thread_rng();
RandomSystem {
rng: rng,
2020-03-21 04:05:39 +00:00
bag: [TetrominoType::I; 7], // Default value, should get init on first get
2019-10-28 06:42:09 +00:00
cur_pos: 0,
}
}
2020-03-22 06:47:17 +00:00
pub fn get_tetromino(&mut self) -> TetrominoType {
2019-10-28 06:42:09 +00:00
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 = [
2020-03-21 04:05:39 +00:00
TetrominoType::I,
TetrominoType::O,
TetrominoType::T,
TetrominoType::S,
TetrominoType::Z,
TetrominoType::J,
TetrominoType::L,
2019-10-28 06:42:09 +00:00
];
self.bag.shuffle(&mut self.rng);
self.cur_pos = 0;
}
}