75 lines
2.0 KiB
Rust
75 lines
2.0 KiB
Rust
use std::cmp;
|
|
|
|
use super::{Cell, Engine, WHITE, BLACK};
|
|
|
|
pub struct LifeEngine {
|
|
grid: Vec<Vec<bool>>,
|
|
}
|
|
|
|
|
|
pub fn new(size: usize) -> LifeEngine {
|
|
let mut life = LifeEngine{grid: vec![vec![false; size]; size]};
|
|
|
|
// r pemento
|
|
let centery = size/2;
|
|
let centerx = size/2;
|
|
|
|
life.grid[centery][centerx] = true;
|
|
life.grid[centery+1][centerx] = true;
|
|
life.grid[centery-1][centerx] = true;
|
|
|
|
life.grid[centery-1][centerx-1] = true;
|
|
life.grid[centery][centerx+1] = true;
|
|
|
|
life
|
|
}
|
|
|
|
|
|
impl Engine for LifeEngine {
|
|
fn evolve(&mut self) -> Vec<Vec<Cell>> {
|
|
let mut new_render_grid = vec![vec![Cell{color: BLACK}; self.grid.len()]; self.grid.len()];
|
|
let mut new_life_grid = vec![vec![false; self.grid.len()]; self.grid.len()];
|
|
|
|
for y in 0..self.grid.len() {
|
|
for x in 0..self.grid[y].len() {
|
|
let mut nalive = 0;
|
|
|
|
let mut ylow = 0;
|
|
if y > 1 {
|
|
ylow = y-1;
|
|
}
|
|
let yhigh = cmp::min(self.grid.len()-1, y+1);
|
|
|
|
let mut xlow = 0;
|
|
if x > 1 {
|
|
xlow = x-1;
|
|
}
|
|
let xhigh = cmp::min(self.grid.len()-1, x+1);
|
|
|
|
for i in ylow..yhigh+1 {
|
|
for j in xlow..xhigh+1 {
|
|
if i == y && j == x {
|
|
continue;
|
|
}
|
|
if self.grid[i][j] {
|
|
nalive += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
if self.grid[y][x] {
|
|
if nalive == 2 || nalive == 3 {
|
|
new_render_grid[y][x] = Cell{color: WHITE};
|
|
new_life_grid[y][x] = true;
|
|
}
|
|
} else if nalive == 3 {
|
|
new_render_grid[y][x] = Cell{color: WHITE};
|
|
new_life_grid[y][x] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
self.grid = new_life_grid;
|
|
new_render_grid
|
|
}
|
|
} |