Vec<Vec<bool>>, counts each cell's 8 neighbours
with bounds checks, and renders live cells as █ block
characters, clearing the terminal between generations using ANSI escape
codes.The simulation runs in the Rust Playground below. Click Run to start it — the grid will evolve each generation using block characters. Best viewed in the playground's output pane.
Vec<Vec<bool>>, counts each cell's 8 neighbours
with bounds checks, and renders live cells as █ block
characters, clearing the terminal between generations using ANSI escape
codes.
use std::{thread, time::Duration};
fn print_grid(grid: &Vec<Vec<bool>>) {
for row in grid {
for &cell in row {
print!("{}", if cell { "█" } else { " " }); }
println!();
}
}
fn next_generation(grid: &Vec<Vec<bool>>) ->
Vec<Vec<bool>> {
let (height, width) = (grid.len(),
grid[0].len());
let mut new_grid = vec![vec![false; width];
height];
for y in 0..height {
for x in 0..width {
let
n = count_neighbours(grid, y, x);
new_grid[y][x]
= matches!((grid[y][x], n), (true, 2) | (true, 3) | (false, 3));
}
}
new_grid
}
fn main() {
let mut grid = vec![vec![false; 30]; 50];
grid[15][14] = true; grid[15][15] = true;
grid[15][16] = true;
loop {
print!("\x1B[2J\x1B[H");
print_grid(&grid);
thread::sleep(Duration::from_millis(200));
grid =
next_generation(&grid);
}
}