Skip to content

Instantly share code, notes, and snippets.

@mugi-uno
Last active May 9, 2020 05:18
Show Gist options
  • Save mugi-uno/12248f3c0c374b837ad78d24ddf1bc38 to your computer and use it in GitHub Desktop.
Save mugi-uno/12248f3c0c374b837ad78d24ddf1bc38 to your computer and use it in GitHub Desktop.
lifegame.rs
use std::{thread, time};
const BOARD_SIZE: usize = 10;
fn main() {
let mut board: Vec<Vec<i32>> = vec![
vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
vec![0, 1, 0, 0, 0, 1, 1, 1, 1, 0],
vec![0, 1, 0, 0, 0, 0, 1, 1, 0, 0],
vec![0, 1, 0, 1, 1, 1, 0, 0, 0, 0],
vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
vec![0, 1, 1, 0, 1, 1, 0, 0, 0, 0],
vec![0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
vec![0, 0, 1, 1, 0, 1, 0, 0, 0, 0],
vec![0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
vec![0, 0, 1, 1, 0, 0, 1, 1, 0, 0]
];
loop {
print_board(&board);
thread::sleep(time::Duration::from_millis(1000));
board = next_board(&board);
}
}
fn next_board(board: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut new_board: Vec<Vec<i32>> = vec![vec![0; BOARD_SIZE]; BOARD_SIZE];
for (rowi, row) in board.iter().enumerate() {
for (coli, _) in row.iter().enumerate() {
new_board[rowi][coli] = next_generation(&board, rowi, coli);
}
}
new_board
}
fn next_generation(board: &Vec<Vec<i32>>, org_rowi: usize, org_coli: usize) -> i32 {
let mut arround: i32 = 0;
let current: i32 = board[org_rowi][org_coli];
let rowi: i32 = org_rowi as i32;
let coli: i32 = org_coli as i32;
arround = arround + get_cell(&board, rowi - 1, coli - 1);
arround += get_cell(&board, rowi - 1, coli);
arround += get_cell(&board, rowi - 1, coli + 1);
arround += get_cell(&board, rowi, coli - 1);
arround += get_cell(&board, rowi, coli + 1);
arround += get_cell(&board, rowi + 1, coli - 1);
arround += get_cell(&board, rowi + 1, coli);
arround += get_cell(&board, rowi + 1, coli + 1);
if current == 0 && arround == 3 { return 1 }
if current == 1 && arround == 1 { return 0 }
if current == 1 && (arround == 2 || arround == 3) { return 1 }
if current == 1 && arround == 4 { return 0 }
0
}
fn get_cell(board: &Vec<Vec<i32>>, rowi: i32, coli: i32) -> i32 {
if rowi < 0 || rowi >= BOARD_SIZE as i32 || coli < 0 || coli >= BOARD_SIZE as i32 { return 0 }
board[rowi as usize][coli as usize]
}
fn print_board(board: &Vec<Vec<i32>>) {
print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
let board_text = board.iter().map(|row| {
let row_text = row.iter().map(|&col| format!("{}", if col == 0 { "□" } else { "■" })).collect::<Vec<_>>().join("");
format!("{}\n", row_text)
}).collect::<Vec<_>>().join("");
print!("{}", board_text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment