mirror of
https://github.com/guezoloic/game-of-life.git
synced 2026-01-25 12:34:09 +00:00
feat: add generation function
This commit adds the generation function, which: - Takes the current grid arena as input. - Creates a new temporary grid. - Applies Conway's Game of Life rules to compute the next state. - Replaces the original grid with the updated one. Conway's Game of Life rules: - A live cell dies if it has fewer than 2 or more than 3 live neighbours. - A live cell survives if it has 2 or 3 live neighbours. - A dead cell becomes alive if it has exactly 3 live neighbours.
This commit is contained in:
20
src/main.rs
20
src/main.rs
@@ -40,11 +40,29 @@ fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 {
|
|||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn generation(grid: &[[bool; WIDTH]; HEIGHT]) -> [[bool; WIDTH]; HEIGHT] {
|
||||||
|
let mut new_grid = [[false; WIDTH]; HEIGHT];
|
||||||
|
|
||||||
|
for x in 0..HEIGHT {
|
||||||
|
for y in 0..WIDTH {
|
||||||
|
let count = count(grid, x, y);
|
||||||
|
new_grid[x][y] = match (grid[x][y], count) {
|
||||||
|
(true, 2) | (true, 3) => true,
|
||||||
|
(false, 3) => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new_grid;
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT];
|
let mut grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT];
|
||||||
let mut buffer: String = String::new();
|
let mut buffer: String = String::new();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
display(&grid, &mut buffer);
|
display(&grid, &mut buffer);
|
||||||
|
grid = generation(&grid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user