marble-machinations/src/marble_engine/board.rs

88 lines
1.5 KiB
Rust
Raw Normal View History

2024-10-03 22:59:49 +02:00
use super::tile::*;
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct Pos {
pub x: isize,
pub y: isize,
}
impl From<(usize, usize)> for Pos {
fn from(value: (usize, usize)) -> Self {
Self {
x: value.0 as isize,
y: value.1 as isize,
}
}
}
#[derive(Debug)]
pub struct Board {
rows: Vec<Vec<Tile>>,
width: usize,
height: usize,
}
impl Board {
pub fn new_empty(width: usize, height: usize) -> Self {
let rows = vec![vec![Tile::Blank; width]; height];
Self {
rows,
width,
height,
}
}
pub fn new(rows: Vec<Vec<Tile>>) -> Self {
Self {
width: rows[0].len(),
height: rows.len(),
rows,
}
}
pub fn in_bounds(&self, p: Pos) -> bool {
p.x >= 0 && p.y >= 0 && p.x < self.width as isize && p.y < self.height as isize
}
pub fn get(&self, p: Pos) -> Option<Tile> {
if self.in_bounds(p) {
Some(self.rows[p.y as usize][p.x as usize])
} else {
None
}
}
pub fn get_or_blank(&self, p: Pos) -> Tile {
if self.in_bounds(p) {
self.rows[p.y as usize][p.x as usize]
} else {
Tile::default()
}
}
pub fn get_mut(&mut self, p: Pos) -> &mut Tile {
if self.in_bounds(p) {
&mut self.rows[p.y as usize][p.x as usize]
} else {
panic!(
"position {p:?} out of bounds, size is {}x{}",
self.width, self.height
);
}
}
pub fn set(&mut self, p: Pos, tile: Tile) {
if self.in_bounds(p) {
self.rows[p.y as usize][p.x as usize] = tile;
}
}
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
}