feat: add basic grid random generation
This commit is contained in:
parent
07437890c9
commit
568fad35d7
3 changed files with 113 additions and 1 deletions
1
src/gen.rs
Normal file
1
src/gen.rs
Normal file
|
@ -0,0 +1 @@
|
|||
mod basic;
|
110
src/gen/basic.rs
Normal file
110
src/gen/basic.rs
Normal file
|
@ -0,0 +1,110 @@
|
|||
//! Basic grid generation given a height, width and a seed.
|
||||
|
||||
use crate::grid::Grid;
|
||||
use rand::{Rng, SeedableRng};
|
||||
use rand_chacha::ChaCha8Rng;
|
||||
|
||||
/// Basic grid generator.
|
||||
///
|
||||
/// TODO: Make width and height integer type generic?
|
||||
pub struct BasicGridGenerator {
|
||||
width: u8,
|
||||
height: u8,
|
||||
seed: u64,
|
||||
}
|
||||
|
||||
impl BasicGridGenerator {
|
||||
pub fn new(width: u8, height: u8, seed: u64) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
seed,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate(&self) -> Grid {
|
||||
let mut rng = ChaCha8Rng::seed_from_u64(self.seed);
|
||||
|
||||
let cells: Vec<_> = (0..self.width)
|
||||
.into_iter()
|
||||
.map(|_| {
|
||||
(0..self.height)
|
||||
.into_iter()
|
||||
.map(|_| rng.gen())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
Grid::with_cells(cells)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::grid::{Cell, Grid};
|
||||
|
||||
use super::BasicGridGenerator;
|
||||
|
||||
#[test]
|
||||
fn ensure_grid_5x5_0_is_reproducible() {
|
||||
let gen = BasicGridGenerator::new(5, 5, 0);
|
||||
let grid = gen.generate();
|
||||
println!("grid {:#?}", grid);
|
||||
let expected_grid = Grid::with_cells(vec![
|
||||
vec![
|
||||
Cell::Empty,
|
||||
Cell::Filled,
|
||||
Cell::Empty,
|
||||
Cell::Filled,
|
||||
Cell::Empty,
|
||||
],
|
||||
vec![
|
||||
Cell::Filled,
|
||||
Cell::Empty,
|
||||
Cell::Empty,
|
||||
Cell::Empty,
|
||||
Cell::Filled,
|
||||
],
|
||||
vec![
|
||||
Cell::Empty,
|
||||
Cell::Empty,
|
||||
Cell::Filled,
|
||||
Cell::Filled,
|
||||
Cell::Empty,
|
||||
],
|
||||
vec![
|
||||
Cell::Filled,
|
||||
Cell::Filled,
|
||||
Cell::Filled,
|
||||
Cell::Filled,
|
||||
Cell::Empty,
|
||||
],
|
||||
vec![
|
||||
Cell::Empty,
|
||||
Cell::Empty,
|
||||
Cell::Filled,
|
||||
Cell::Empty,
|
||||
Cell::Empty,
|
||||
],
|
||||
]);
|
||||
|
||||
assert_eq!(grid, expected_grid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_5x5_u64_max_hints() {
|
||||
let gen = BasicGridGenerator::new(5, 5, u64::MAX);
|
||||
let grid = gen.generate();
|
||||
println!("grid {:#?}", grid);
|
||||
|
||||
let (r_hints, c_hints) = grid.hints();
|
||||
assert_eq!(
|
||||
r_hints,
|
||||
[vec![4], vec![1, 1], vec![1, 1], vec![1, 2], vec![1, 2]]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
c_hints,
|
||||
[vec![1], vec![3, 1], vec![1, 1], vec![2, 2], vec![1, 1, 1]]
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1 +1,2 @@
|
|||
mod core;
|
||||
mod gen;
|
||||
mod grid;
|
||||
|
|
Loading…
Reference in a new issue