Last active
February 6, 2018 15:22
-
-
Save permil/d92f10e5d28e7b8e7273386c69e8f818 to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rand; | |
use std::thread; | |
use std::time::Duration; | |
use rand::Rng; | |
struct Field { | |
width: usize, | |
height: usize, | |
grids: Vec<Vec<bool>> | |
} | |
impl Field { | |
fn new(width: usize, height: usize) -> Field { | |
// let grids = vec![vec![false; height]; width]; | |
let mut grids = Vec::with_capacity(height); | |
for j in 0..height { | |
let mut row = Vec::with_capacity(width); | |
for i in 0..width { | |
row.push(rand::thread_rng().gen()); | |
} | |
grids.push(row); | |
} | |
Field { | |
width: width, | |
height: height, | |
grids: grids | |
} | |
} | |
fn step(&self) -> Field { | |
let mut grids = Vec::with_capacity(self.height); | |
for j in 0..self.height { | |
let mut row = Vec::with_capacity(self.width); | |
for i in 0..self.width { | |
let mut count = 0; | |
for jj in 0..3 { | |
for ii in 0..3 { | |
if ii == 1 && jj == 1 { continue; } | |
if self.grids[(j+jj+self.height-1)%self.height][(i+ii+self.width-1)%self.width] { | |
count += 1; | |
} | |
} | |
} | |
row.push((self.grids[j][i] && (count == 2 || count == 3)) || (!self.grids[j][i] && count == 3)); | |
} | |
grids.push(row); | |
} | |
Field { | |
width: self.width, | |
height: self.height, | |
grids: grids | |
} | |
} | |
} | |
fn main() { | |
let mut field = Field::new(24, 16); | |
for i in 0..1000 { | |
println!("{}[2J", 27 as char); | |
for row in &field.grids { | |
for grid in row { | |
print!("{}", if *grid { "*" } else { "." }); | |
} | |
println!(); | |
} | |
field = field.step(); | |
thread::sleep(Duration::from_millis(50)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment