Created
March 10, 2016 05:17
-
-
Save fero23/304bfafbd5f049142cd3 to your computer and use it in GitHub Desktop.
A simple minesweeper board constructor using 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
#[derive(Clone, Copy)] | |
enum CellType { | |
Number(u32), | |
Bomb, | |
Empty | |
} | |
type InputBoard = [[u8; 8];8]; | |
type GameBoard = [[CellType; 8];8]; | |
fn main() { | |
let input = [ | |
[1,0,0,0,0,0,0,0], | |
[0,0,0,0,0,0,0,0], | |
[0,0,0,1,0,0,0,0], | |
[0,0,0,1,1,0,0,0], | |
[0,0,0,0,0,0,0,0], | |
[0,0,0,0,0,0,0,1], | |
[0,0,0,0,0,1,0,1], | |
[0,0,0,0,0,1,1,1] | |
]; | |
println!("{}", print_gameboard(get_board(input))); | |
} | |
fn get_board(input: InputBoard) -> GameBoard { | |
let mut gameboard: GameBoard = [[CellType::Empty;8];8]; | |
for row in 0i32..input.len() as i32 { | |
for col in 0i32..input[row as usize].len() as i32 { | |
if input[row as usize][col as usize] == 1 { | |
gameboard[row as usize][col as usize] = CellType::Bomb; | |
continue; | |
} | |
let mut bombs_around = 0; | |
macro_rules! check_around { | |
($inc_row: expr, $inc_col: expr) => { | |
if row + $inc_row >= 0 && | |
row + $inc_row < input.len() as i32 { | |
if col + $inc_col >= 0 && col + $inc_col < | |
input[(row + $inc_row) as usize].len() as i32 { | |
if input[(row + $inc_row) as usize] | |
[(col + $inc_col) as usize] == 1 { | |
bombs_around += 1; | |
} | |
} | |
} | |
} | |
} | |
check_around!(1, 1); | |
check_around!(1, -1); | |
check_around!(-1, 1); | |
check_around!(-1, -1); | |
check_around!(0, 1); | |
check_around!(0, -1); | |
check_around!(1, 0); | |
check_around!(-1, 0); | |
if bombs_around > 0 { | |
gameboard[row as usize][col as usize] = | |
CellType::Number(bombs_around); | |
} | |
} | |
} | |
gameboard | |
} | |
fn print_gameboard(board: GameBoard) -> String { | |
let mut repr = String::new(); | |
for row in board.iter() { | |
for cell in row.iter() { | |
repr.push_str(match *cell { | |
CellType::Number(ref n) => format!("{:2} ", n), | |
CellType::Bomb => "<> ".to_string(), | |
CellType::Empty=> "[] ".to_string() | |
}.as_ref()); | |
} | |
repr.push_str("\n"); | |
} | |
repr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment