Created
September 19, 2015 21:33
-
-
Save cschneid/ba764e7ec4c3f2ce93c4 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
fn main() { | |
let mut g = Game::new(10, 10); | |
g.alive(0,0); | |
g.alive(2,2); | |
let ns = g.neighbors(1,1); | |
println!("{:?}", ns); | |
println!("{}", g.format()); | |
} | |
#[derive(Debug)] | |
enum CellType { | |
Alive, | |
Dead | |
} | |
#[derive(Debug)] | |
struct Cell { | |
cell_type: CellType, | |
} | |
#[derive(Debug)] | |
struct Game { | |
cells: Vec<Vec<Cell>>, | |
x_size: usize, | |
y_size: usize | |
} | |
impl Game { | |
fn new(x_size: usize, y_size: usize) -> Game { | |
let mut x = Vec::new(); | |
for _ in 0..x_size { | |
let mut y = Vec::new(); | |
for _ in 0..y_size { | |
y.push(Cell { cell_type: CellType::Dead }) | |
} | |
x.push(y); | |
} | |
Game { cells: x, x_size: x_size, y_size: y_size } | |
} | |
fn alive(& mut self, x: usize, y: usize) -> bool { | |
if self.x_size > x && self.y_size > y { | |
self.cells[x][y] = Cell { cell_type : CellType::Alive }; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
fn format(&self) -> String { | |
let mut s = String::new(); | |
for x in 0..self.x_size { | |
for y in 0..self.y_size { | |
s.push_str(self.cells[x][y].format()); | |
s.push_str(" "); | |
} | |
s.push_str("\n"); | |
} | |
return s; | |
} | |
// Return all the neighbor cells of a given cell | |
fn neighbors(&self, x: usize, y: usize) -> Vec<&Cell> { | |
// [-1, -1] [ 0, -1 ] [1, -1] | |
// [-1, 0] [ 0, 0 ] [1, 0] | |
// [-1, 1] [ 0, 1 ] [1, 1] | |
let mut v = Vec::new(); | |
// Top Row | |
v.push(self.cells.get(x - 1).and_then(|ys| ys.get(y - 1)) ); | |
v.push(self.cells.get(x + 0).and_then(|ys| ys.get(y - 1)) ); | |
v.push(self.cells.get(x + 1).and_then(|ys| ys.get(y - 1)) ); | |
// Middle Row ( skipping our own cell ) | |
v.push(self.cells.get(x - 1).and_then(|ys| ys.get(y + 0)) ); | |
v.push(self.cells.get(x + 1).and_then(|ys| ys.get(y + 0)) ); | |
// Bottom Row | |
v.push(self.cells.get(x - 1).and_then(|ys| ys.get(y + 1)) ); | |
v.push(self.cells.get(x + 0).and_then(|ys| ys.get(y + 1)) ); | |
v.push(self.cells.get(x + 1).and_then(|ys| ys.get(y + 1)) ); | |
v.iter().filter_map(|x| *x).collect() | |
} | |
} | |
impl Cell { | |
fn format(&self) -> &'static str { | |
match self.cell_type { | |
CellType::Alive => "X", | |
CellType::Dead => "0" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment