mirror of
https://github.com/guezoloic/game-of-life.git
synced 2026-01-25 06:34:07 +00:00
feat: add count function
It introduces a new `count` function that take: - the grid arena - X and Y as `isize` It counts how many nearby cells are alive at a specified position and returns the total.
This commit is contained in:
29
src/main.rs
29
src/main.rs
@@ -15,9 +15,36 @@ fn display(grid: &[[bool; WIDTH]; HEIGHT], buffer: &mut String) {
|
|||||||
println!("{}", buffer);
|
println!("{}", buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 {
|
||||||
|
let near:[(isize, isize); 8] = [
|
||||||
|
(-1, -1), (-1, 0), (-1, 1),
|
||||||
|
(0, -1), (0, 1),
|
||||||
|
( 1, -1), (1, 0), (1, 1)
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut count = 0;
|
||||||
|
|
||||||
|
for (i, j) in near {
|
||||||
|
let nx: isize = x as isize + i;
|
||||||
|
let ny: isize = y as isize + j;
|
||||||
|
|
||||||
|
if (nx > 0 && (WIDTH as isize) > nx &&
|
||||||
|
ny > 0 && (HEIGHT as isize) > ny) {
|
||||||
|
|
||||||
|
if (grid[nx as usize][nx as usize]) {
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT];
|
let grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT];
|
||||||
let mut buffer: String = String::new();
|
let mut buffer: String = String::new();
|
||||||
|
|
||||||
display(&grid, &mut buffer);
|
loop {
|
||||||
|
display(&grid, &mut buffer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user