Initial commit
This commit is contained in:
86
board-shared/src/board.rs
Normal file
86
board-shared/src/board.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
use crate::tile::Tile;
|
||||
|
||||
const BOARD_SIZE: usize = 25;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Board {
|
||||
tiles: [Option<Tile>; BOARD_SIZE * BOARD_SIZE],
|
||||
}
|
||||
|
||||
impl Board {
|
||||
pub fn get(&self, x: usize, y: usize) -> Option<Tile> {
|
||||
self.tiles[y * BOARD_SIZE + x]
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: usize, y: usize, tile: Tile) {
|
||||
self.tiles[y * BOARD_SIZE + x] = Some(tile);
|
||||
}
|
||||
|
||||
pub fn difference(&self, other: &Board) -> Vec<(usize, usize)> {
|
||||
let mut diff = Vec::new();
|
||||
for x in 0..BOARD_SIZE {
|
||||
for y in 0..BOARD_SIZE {
|
||||
if self.get(x, y) != other.get(x, y) {
|
||||
diff.push((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
diff
|
||||
}
|
||||
|
||||
pub fn is_contiguous(positions: &[(usize, usize)]) -> Option<bool> {
|
||||
let mut it = positions.iter();
|
||||
let first = *it.next()?;
|
||||
let mut second = *it.next()?;
|
||||
if first.0 == second.0 {
|
||||
// Vertical
|
||||
for &(x, y) in it {
|
||||
if x != first.0 || y != second.1 + 1 {
|
||||
return Some(false);
|
||||
}
|
||||
second = (x, y);
|
||||
}
|
||||
Some(true)
|
||||
} else if first.1 == second.1 {
|
||||
// Horizontal
|
||||
for &(x, y) in it {
|
||||
if y != first.1 || x != second.0 + 1 {
|
||||
return Some(false);
|
||||
}
|
||||
second = (x, y);
|
||||
}
|
||||
Some(true)
|
||||
} else {
|
||||
Some(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Board {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tiles: [None; BOARD_SIZE * BOARD_SIZE],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_is_contiguous() {
|
||||
assert_eq!(Board::is_contiguous(&[]), None);
|
||||
assert_eq!(Board::is_contiguous(&[(0, 0)]), None);
|
||||
assert_eq!(Board::is_contiguous(&[(0, 0), (0, 1), (0, 2)]), Some(true));
|
||||
assert_eq!(
|
||||
Board::is_contiguous(&[(1, 0), (2, 0), (3, 0), (4, 0)]),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(Board::is_contiguous(&[(0, 0), (0, 1), (1, 3)]), Some(false));
|
||||
assert_eq!(
|
||||
Board::is_contiguous(&[(0, 0), (0, 1), (0, 2), (1, 2)]),
|
||||
Some(false)
|
||||
);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user