Day 17

Conway's Game of Life in Rust

Try it!

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.



Open in full page

Description


Conway's Game of Life — a zero-player cellular automaton devised by mathematician John Conway in 1970. The grid starts with a handful of live cells and evolves each generation by four simple rules: a live cell with 2 or 3 neighbours survives; a dead cell with exactly 3 neighbours becomes alive; all other cells die or stay dead. Despite those four rules, the system produces staggering complexity — stable blocks, oscillators, gliders that move across the grid indefinitely. This implementation represents the grid as a 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.

View the source code


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);
}
}

Previous Day
Next Day