Last active
November 12, 2020 02:49
-
-
Save thara/8a7f45f1b02a122987b9d3c5c16672cd to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Rust
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
use std::collections::HashSet; | |
use std::io::{self, stdout, Write}; | |
type Point = (i8, i8); | |
type Board = HashSet<(i8, i8)>; | |
fn neighbors(point: Point) -> [Point; 8] { | |
let (x, y) = point; | |
[ | |
(x + 1, y), | |
(x - 1, y), | |
(x, y + 1), | |
(x, y - 1), | |
(x + 1, y + 1), | |
(x + 1, y - 1), | |
(x - 1, y + 1), | |
(x - 1, y - 1), | |
] | |
} | |
fn is_living(point: Point, board: &Board) -> bool { | |
let count = neighbors(point) | |
.iter() | |
.filter(|p| board.contains(&p)) | |
.count(); | |
count == 3 || (count == 2 && board.contains(&point)) | |
} | |
fn advance(board: Board) -> Board { | |
let neighbors: Board = board | |
.iter() | |
.cloned() | |
.flat_map(|p| neighbors(p).to_vec()) | |
.collect(); | |
let recalc = board.union(&neighbors); | |
recalc.filter(|&p| is_living(*p, &board)).cloned().collect() | |
} | |
fn print_board(board: &Board) { | |
for x in 0..10 { | |
for y in 0..10 { | |
let mark = if board.contains(&(x, y)) { "*" } else { "-" }; | |
print!("{}", mark); | |
} | |
println!(); | |
} | |
} | |
fn main() -> io::Result<()> { | |
let mut state: Board = [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)] | |
.iter() | |
.cloned() | |
.collect(); | |
print_board(&state); | |
loop { | |
let mut b = String::new(); | |
io::stdin().read_line(&mut b)?; | |
print!("\x1b[11A\r"); | |
stdout().flush().unwrap(); | |
state = advance(state); | |
print_board(&state); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment