Created
September 3, 2016 21:48
-
-
Save greyblake/fcba7eea4841d17c31535d6c2482d1b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 rand::Rng; | |
const WIDTH : usize = 80; | |
const HEIGH : usize = 40; | |
const SIZE : usize = WIDTH * HEIGH; | |
type MatrixLine = [bool; WIDTH]; | |
type Matrix = [MatrixLine; HEIGH]; | |
fn matrix_init() -> Matrix { | |
let mut matrix : Matrix = [[false; WIDTH]; HEIGH]; | |
let mut rng = rand::thread_rng(); | |
for _ in 0..(SIZE / 2) { | |
let x = rng.gen_range(0, WIDTH); | |
let y = rng.gen_range(0, HEIGH); | |
matrix[y][x] = true; | |
} | |
matrix | |
} | |
fn matrix_render(matrix : Matrix) { | |
for row in matrix.iter() { | |
for cell in row.iter() { | |
let ch = match *cell { | |
true => "#", | |
false => " ", | |
}; | |
print!("{}", ch); | |
} | |
println!(""); | |
} | |
} | |
fn matrix_next(matrix : Matrix) -> Matrix { | |
let mut result: Matrix = [[false; WIDTH]; HEIGH]; | |
for (ri, row) in matrix.iter().enumerate() { | |
for (ci, cell) in row.iter().enumerate() { | |
let alive_count = matrix_count_cell_neighbors(matrix, ri as i32, ci as i32); | |
let new_val = | |
if *cell { | |
if alive_count < 2 { | |
false | |
} else if alive_count == 2 || alive_count == 3 { | |
true | |
} else { | |
false | |
} | |
} else { | |
alive_count == 3 | |
}; | |
result[ri][ci] = new_val; | |
} | |
} | |
result | |
} | |
fn matrix_count_cell_neighbors(matrix: Matrix, ri: i32, ci: i32) -> i32 { | |
let mut count = 0; | |
let offsets = [ | |
(-1, -1), (-1, 0), (-1, 1), | |
(0, -1) , (0, 1), | |
(1, -1) , (1, 0) , (1, 1) | |
]; | |
for offset in offsets.iter() { | |
let &(ro, co) = offset; | |
let r = ri + ro; | |
let c = ci + co; | |
if r < 0 || c < 0 || r >= HEIGH as i32 || c >= WIDTH as i32 { | |
continue; | |
} else if matrix[r as usize][c as usize] { | |
count += 1; | |
} | |
} | |
count | |
} | |
fn main() { | |
let mut matrix = matrix_init(); | |
loop { | |
print!("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); | |
matrix_render(matrix); | |
matrix = matrix_next(matrix); | |
std::thread::sleep_ms(100); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment