give me a rust code for game of life
- User
give me a rust code for game of life
- Assistant
Here's a simple implementation of Conway's Game of Life in Rust:
use std::{thread, time}; use rand::Rng; use ansi_term::{Colour, Style}; const WIDTH: usize = 60; const HEIGHT: usize = 20; type Grid = [[bool; WIDTH]; HEIGHT]; fn create_random_grid() -> Grid { let mut rng = rand::thread_rng(); (0..HEIGHT).map(|_| (0..WIDTH).map(|_| rng.gen()).collect()).collect() } fn print_grid(grid: &Grid) { for row in grid { for cell in row { print!("{}", if *cell { Colour::Green.bold().paint("#") } else { "." }); } println!(""); } println!("{}", Style::reset().paint("")); } fn count_neighbors(x: usize, y: usize, grid: &Grid) -> u8 { let mut count = 0; for dy in -1..=1 { for dx in -1..=1 { if dx == 0 && dy == 0 { continue; } let nx = (x as isize + dx) as usize; let ny = (y as isize + dy) as usize; if nx >= 0 && nx < WIDTH && ny >= 0 && ny < HEIGHT && grid[ny][nx] { count += 1; } } } count } fn next_generation(grid: &Grid) -> Grid { let mut next = Grid::new(); for y in 0..HEIGHT { for x in 0..WIDTH { let neighbors = count_neighbors(x, y, grid); next[y][x] = match (grid[y][x], neighbors) { (true, 2 | 3) => true, (false, 3) => true, _ => false, }; } } next } fn main() { let mut grid = create_random_grid(); loop { print_grid(&grid); thread::sleep(time::Duration::from_millis(500)); grid = next_generation(&grid); } }This code defines a
Gridtype as a 2D array of boolean values, wheretruerepresents a live cell andfalserepresents a dead cell. The functionscreate_random_grid,print_grid,count_neighbors, andnext_generationimplement the basic logic of the Game of Life. Themainfunction initializes a random grid and then enters an infinite loop where it prints the current generation, waits for 500 milliseconds, and then calculates the next generation.Note that this implementation uses the
rand,ansi_term, andtimecrates. You can add these dependencies to yourCargo.tomlfile:[dependencies] rand = "0.8.5" ansi_term = "0.12.1" time = "0.3.9"Then you can build and run the program with
cargo run.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.