From 0b2fa63941d1b5f449ad878058ed1c403ea41e7b Mon Sep 17 00:00:00 2001 From: clfreville2 Date: Fri, 10 Feb 2023 20:42:01 +0100 Subject: [PATCH] Add additional helper functions to test if the tiles are aligned or not --- board-shared/src/board.rs | 49 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/board-shared/src/board.rs b/board-shared/src/board.rs index 8fa433d..ff60056 100644 --- a/board-shared/src/board.rs +++ b/board-shared/src/board.rs @@ -1,4 +1,4 @@ -use crate::position::{Grid2d, Position2d}; +use crate::position::{Alignment, Grid2d, Position2d}; use crate::tile::Tile; const DEFAULT_BOARD_SIZE: usize = 25; @@ -55,6 +55,23 @@ impl Board { Some(true) } + + /// Determines whether the given positions are aligned. + pub fn is_aligned(positions: &[Position2d], alignement: Alignment) -> bool { + if let Some(&first) = positions.first() { + positions + .iter() + .all(|&pos| alignement.is_aligned(first, pos)) + } else { + true + } + } + + /// Determines whether the given positions have any alignment. + pub fn has_alignment(positions: &[Position2d]) -> bool { + Self::is_aligned(positions, Alignment::Horizontal) + || Self::is_aligned(positions, Alignment::Vertical) + } } impl Grid2d for Board { @@ -120,4 +137,34 @@ mod tests { Some(false) ); } + + #[test] + fn test_is_aligned() { + assert!(Board::is_aligned(&[], Alignment::Horizontal)); + assert!(Board::is_aligned(&[], Alignment::Vertical)); + assert!(Board::is_aligned( + &positions(&[(0, 0)]), + Alignment::Horizontal + )); + assert!(Board::is_aligned( + &positions(&[(0, 0)]), + Alignment::Vertical + )); + assert!(Board::is_aligned( + &positions(&[(0, 0), (0, 1)]), + Alignment::Horizontal + )); + assert!(Board::is_aligned( + &positions(&[(0, 0), (1, 0)]), + Alignment::Vertical + )); + assert!(!Board::is_aligned( + &positions(&[(0, 0), (1, 0)]), + Alignment::Horizontal + )); + assert!(!Board::is_aligned( + &positions(&[(0, 0), (0, 1)]), + Alignment::Vertical + )); + } }