Here is a simple implementation of Conway's Game of Life in Rust:
use std::fmt;
#[derive(Clone)]
struct Universe {
width: usize,
height: usize,
cells: Vec<bool>,
}
impl Universe {
fn new(width: usize, height: usize) -> Universe {
let size = width * height;
Universe {
width,
height,
cells: vec![false; size],
}
}
fn live_cells(&self) -> impl Iterator<Item = (usize, usize)> + DoubleEndedIterator {
self.cells.iter().enumerate().filter(|&(i, &c)| c)
}
fn get_index(&self, x: usize, y: usize) -> usize {
assert!(x < self.width && y < self.height);
y * self.width + x
}
fn set_alive(&mut self, x: usize, y: usize) {
let i = self.get_index(x, y);
self.cells[i] = true;
}
fn set_dead(&mut self, x: usize, y: usize) {
let i = self.get_index(x, y);
self.cells[i] = false;
}
fn is_alive(&self, x: usize, y: usize) -> bool {
let i = self.get_index(x, y);
self.cells[i]
}
fn tick(&mut self) {
let mut new_cells = self.cells.clone();
for (x, y) in self.live_cells() {
for (dx, dy) in &[(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)] {
let x2 = (x as i32 + dx) as usize % self.width;
let y2 = (y as i32 + dy) as usize % self.height;
let idx = self.get_index(x2, y2);
new_cells[idx] ^= true; // toggle
}
}
self.cells = new_cells;
}
}
impl fmt::Debug for Universe {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..self.height {
for x in 0..self.width {
let alive = self.is_alive(x, y);
write!(f, "{}", if alive { 'O' } else { '.' })?;
}
writeln!(f)?;
}
Ok(())
}
}
fn main() {
let mut universe = Universe::new(30, 15);
for y in 0..universe.height {
for x in 0..universe.width {
if (x + y) % 2 == 0 {
universe.set_alive(x, y);
}
}
}
for _ in 0..5 {
println!("{:?}", universe);
universe.tick();
}
}
This code defines a Universe struct to represent the grid of cells, and provides methods to set individual cells alive or dead, as well as a tick() method to advance the simulation by one generation. It also provides a live_cells() method that returns an iterator over all currently live cells, which can be used to easily count the number of live neighbors around any given cell.
The main() function creates a new Universe, initializes it with a checkerboard pattern of live cells, and then advances the simulation by 5 generations, printing out the state of the grid after each tick.