Compare commits

...

12 Commits
v0.4.0 ... main

18 changed files with 802 additions and 475 deletions

View File

@ -9,76 +9,30 @@ env:
RUSTFLAGS: --deny warnings
RUSTDOCFLAGS: --deny warnings
jobs:
# Run tests.
test:
name: Tests
build-and-test:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
SCCACHE_GHA_ENABLED: "true"
RUSTC_WRAPPER: "sccache"
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
- name: Checkout code
uses: actions/checkout@v5
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev
- name: Populate target directory from cache
uses: Leafwing-Studios/cargo-cache@v2
with:
sweep-cache: true
- name: Run tests
toolchain: stable
components: clippy, rustfmt
- name: Run sccache-cache
uses: mozilla-actions/sccache-action@v0.0.9
- name: Install cargo-nextest
uses: taiki-e/install-action@cargo-nextest
- name: Run Clippy
run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
- name: Run formatting
run: cargo fmt --all --check
- name: Run Tests
run: |
cargo test --locked --workspace --all-features --all-targets
# Workaround for https://github.com/rust-lang/cargo/issues/6669
cargo nextest run --all-features --all-targets
cargo test --locked --workspace --all-features --doc
# Run clippy lints.
clippy:
name: Clippy
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- name: Install dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev
- name: Populate target directory from cache
uses: Leafwing-Studios/cargo-cache@v2
with:
sweep-cache: true
- name: Run clippy lints
run: cargo clippy --locked --workspace --all-features -- --deny warnings
# Check formatting.
format:
name: Format
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Run cargo fmt
run: cargo fmt --all -- --check
# Check documentation.
doc:
name: Docs
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Install dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev
- name: Populate target directory from cache
uses: Leafwing-Studios/cargo-cache@v2
with:
sweep-cache: true
- name: Check documentation
- name: Check Documentation
run: cargo doc --locked --workspace --all-features --document-private-items --no-deps

107
Cargo.lock generated
View File

@ -1248,7 +1248,7 @@ dependencies = [
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"rustc-hash 1.1.0",
"shlex",
"syn",
]
@ -1631,7 +1631,7 @@ dependencies = [
"log",
"rangemap",
"rayon",
"rustc-hash",
"rustc-hash 1.1.0",
"rustybuzz",
"self_cell",
"swash",
@ -1743,6 +1743,18 @@ version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2"
[[package]]
name = "deprecate-until"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a3767f826efbbe5a5ae093920b58b43b01734202be697e1354914e862e8e704"
dependencies = [
"proc-macro2",
"quote",
"semver",
"syn",
]
[[package]]
name = "derive_more"
version = "1.0.0"
@ -2014,21 +2026,6 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "futures"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.31"
@ -2036,7 +2033,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
@ -2045,17 +2041,6 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.31"
@ -2086,12 +2071,6 @@ dependencies = [
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
[[package]]
name = "futures-task"
version = "0.3.31"
@ -2110,13 +2089,9 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"pin-utils",
"slab",
@ -2375,7 +2350,7 @@ checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"
[[package]]
name = "hexlab"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"bevy",
"bevy_reflect",
@ -2383,6 +2358,7 @@ dependencies = [
"claims",
"glam",
"hexx",
"pathfinding",
"rand",
"rstest",
"serde",
@ -2391,9 +2367,9 @@ dependencies = [
[[package]]
name = "hexx"
version = "0.19.0"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b47b6f7ee46bba869534a92306b7e7f549bec38114a4ba0288b9321617db22"
checksum = "4b450e02a24a4a981c895be4cd2752e2401996c545971309730c4e812b984691"
dependencies = [
"bevy_reflect",
"glam",
@ -2457,6 +2433,15 @@ dependencies = [
"libc",
]
[[package]]
name = "integer-sqrt"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "276ec31bcb4a9ee45f58bec6f9ec700ae4cf4f4f8f2fa7e06cb406bd5ffdd770"
dependencies = [
"num-traits",
]
[[package]]
name = "io-kit-sys"
version = "0.4.1"
@ -2724,7 +2709,7 @@ dependencies = [
"indexmap",
"log",
"pp-rs",
"rustc-hash",
"rustc-hash 1.1.0",
"spirv",
"termcolor",
"thiserror 1.0.69",
@ -2745,7 +2730,7 @@ dependencies = [
"once_cell",
"regex",
"regex-syntax 0.8.5",
"rustc-hash",
"rustc-hash 1.1.0",
"thiserror 1.0.69",
"tracing",
"unicode-ident",
@ -3203,6 +3188,20 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pathfinding"
version = "4.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301ad6aa19104eeb9af172b3d6a4ab8a5ea26234890baf2fcb1cbbc3f05f674b"
dependencies = [
"deprecate-until",
"indexmap",
"integer-sqrt",
"num-traits",
"rustc-hash 2.1.0",
"thiserror 2.0.3",
]
[[package]]
name = "percent-encoding"
version = "2.3.1"
@ -3570,21 +3569,21 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "rstest"
version = "0.23.0"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035"
checksum = "03e905296805ab93e13c1ec3a03f4b6c4f35e9498a3d5fa96dc626d22c03cd89"
dependencies = [
"futures",
"futures-timer",
"futures-util",
"rstest_macros",
"rustc_version",
]
[[package]]
name = "rstest_macros"
version = "0.23.0"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a"
checksum = "ef0053bbffce09062bee4bcc499b0fbe7a57b879f1efe088d6d8d4c7adcdef9b"
dependencies = [
"cfg-if",
"glob",
@ -3604,6 +3603,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustc-hash"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
[[package]]
name = "rustc_version"
version = "0.4.1"
@ -4320,7 +4325,7 @@ dependencies = [
"parking_lot",
"profiling",
"raw-window-handle",
"rustc-hash",
"rustc-hash 1.1.0",
"smallvec",
"thiserror 1.0.69",
"wgpu-hal",
@ -4362,7 +4367,7 @@ dependencies = [
"range-alloc",
"raw-window-handle",
"renderdoc-sys",
"rustc-hash",
"rustc-hash 1.1.0",
"smallvec",
"thiserror 1.0.69",
"wasm-bindgen",

View File

@ -1,7 +1,7 @@
[package]
name = "hexlab"
authors = ["Kristofers Solo <dev@kristofers.xyz>"]
version = "0.4.0"
version = "0.6.1"
edition = "2021"
description = "A hexagonal maze generation and manipulation library"
repository = "https://github.com/kristoferssolo/hexlab"
@ -26,6 +26,7 @@ thiserror = "2.0"
bevy = { version = "0.15", optional = true }
bevy_utils = { version = "0.15", optional = true }
glam = { version = "0.29", optional = true }
pathfinding = { version = "4.13", optional = true }
[dependencies.bevy_reflect]
@ -36,7 +37,7 @@ features = ["glam"]
[dev-dependencies]
claims = "0.8"
rstest = "0.23"
rstest = "0.24"
[features]
default = []
@ -48,7 +49,8 @@ bevy_reflect = [
"hexx/bevy_reflect",
"dep:glam",
]
full = ["serde", "bevy"]
pathfinding = ["dep:pathfinding"]
full = ["serde", "bevy", "pathfinding"]
[profile.dev]
opt-level = 1 # Better compile times with some optimization

View File

@ -42,7 +42,7 @@ fn main() {
.with_radius(5)
.build()
.expect("Failed to create maze");
println!("Maze size: {}", maze.len());
println!("Maze size: {}", maze.count());
}
```

View File

@ -1,25 +1,5 @@
use crate::{GeneratorType, HexMaze};
use crate::{errors::MazeBuilderError, GeneratorType, Maze};
use hexx::Hex;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum MazeBuilderError {
/// Occurs when attempting to build a maze without specifying a radius.
#[error("Radius must be specified to build a maze")]
NoRadius,
/// Occurs when the specified radius is too large.
#[error("Radius {0} is too large. Maximum allowed radius is {1}")]
RadiusTooLarge(u32, u32),
/// Occurs when the specified start position is outside the maze bounds.
#[error("Start position {0:?} is outside maze bounds")]
InvalidStartPosition(Hex),
/// Occurs when maze generation fails.
#[error("Failed to generate maze: {0}")]
GenerationError(String),
}
/// A builder pattern for creating hexagonal mazes.
///
@ -40,7 +20,7 @@ pub enum MazeBuilderError {
///
/// // A radius of 5 creates 61 hexagonal tiles
/// assert!(!maze.is_empty());
/// assert_eq!(maze.len(), 91);
/// assert_eq!(maze.count(), 91);
/// ```
///
/// Using a seed for reproducible results:
@ -60,7 +40,7 @@ pub enum MazeBuilderError {
/// .expect("Failed to create maze");
///
/// // Same seed should produce identical mazes
/// assert_eq!(maze1.len(), maze2.len());
/// assert_eq!(maze1.count(), maze2.count());
/// assert_eq!(maze1, maze2);
/// ```
///
@ -85,7 +65,7 @@ pub struct MazeBuilder {
impl MazeBuilder {
/// Creates a new [`MazeBuilder`] instance with default settings.
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
@ -101,7 +81,7 @@ impl MazeBuilder {
/// # Arguments
///
/// - `radius` - The number of tiles from the center to the edge of the hexagon.
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn with_radius(mut self, radius: u16) -> Self {
self.radius = Some(radius);
@ -115,7 +95,7 @@ impl MazeBuilder {
/// # Arguments
///
/// - `seed` - The random seed value.
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn with_seed(mut self, seed: u64) -> Self {
self.seed = Some(seed);
@ -129,7 +109,7 @@ impl MazeBuilder {
/// # Arguments
///
/// - `generator_type` - The maze generation algorithm to use.
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn with_generator(mut self, generator_type: GeneratorType) -> Self {
self.generator_type = generator_type;
@ -140,7 +120,7 @@ impl MazeBuilder {
/// # Arguments
///
/// - `pos` - The hexagonal coordinates for the starting position.
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn with_start_position(mut self, pos: Hex) -> Self {
self.start_position = Some(pos);
@ -172,12 +152,12 @@ impl MazeBuilder {
/// let maze = result.unwrap();
/// assert!(!maze.is_empty());
/// ```
pub fn build(self) -> Result<HexMaze, MazeBuilderError> {
pub fn build(self) -> Result<Maze, MazeBuilderError> {
let radius = self.radius.ok_or(MazeBuilderError::NoRadius)?;
let mut maze = create_hex_maze(radius);
if let Some(start_pos) = self.start_position {
if maze.get_tile(&start_pos).is_none() {
if maze.get(&start_pos).is_none() {
return Err(MazeBuilderError::InvalidStartPosition(start_pos));
}
}
@ -190,8 +170,9 @@ impl MazeBuilder {
Ok(maze)
}
}
pub fn create_hex_maze(radius: u16) -> HexMaze {
let mut maze = HexMaze::new();
pub fn create_hex_maze(radius: u16) -> Maze {
let mut maze = Maze::new();
let radius = i32::from(radius);
for q in -radius..=radius {
@ -199,7 +180,7 @@ pub fn create_hex_maze(radius: u16) -> HexMaze {
let r2 = radius.min(-q + radius);
for r in r1..=r2 {
let pos = Hex::new(q, r);
maze.add_tile(pos);
maze.insert(pos);
}
}
@ -209,7 +190,7 @@ pub fn create_hex_maze(radius: u16) -> HexMaze {
#[cfg(test)]
mod test {
use super::*;
use claims::assert_gt;
use claims::{assert_gt, assert_some};
use rstest::rstest;
#[test]
@ -230,18 +211,18 @@ mod test {
#[case(100, 30301)]
fn create_hex_maze_various_radii(#[case] radius: u16, #[case] expected_size: usize) {
let maze = create_hex_maze(radius);
assert_eq!(maze.len(), expected_size);
assert_eq!(maze.count(), expected_size);
}
#[test]
fn create_hex_maze_large_radius() {
let large_radius = 1000;
let maze = create_hex_maze(large_radius);
assert_gt!(maze.len(), 0);
assert_gt!(maze.count(), 0);
// Calculate expected size for this radius
let expected_size = 3 * (large_radius as usize).pow(2) + 3 * large_radius as usize + 1;
assert_eq!(maze.len(), expected_size);
assert_eq!(maze.count(), expected_size);
}
#[test]
@ -268,8 +249,8 @@ mod test {
Hex::new(0, -2),
Hex::new(1, -2),
];
for pos in expected_positions.iter() {
assert!(maze.get_tile(pos).is_some(), "Expected tile at {:?}", pos);
for pos in &expected_positions {
assert_some!(maze.get(pos), "Expected tile at {pos:?}");
}
}
}

41
src/errors.rs Normal file
View File

@ -0,0 +1,41 @@
use hexx::{EdgeDirection, Hex};
use thiserror::Error;
use crate::Tile;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum MazeBuilderError {
/// Occurs when attempting to build a maze without specifying a radius.
#[error("Radius must be specified to build a maze")]
NoRadius,
/// Occurs when the specified start position is outside the maze bounds.
#[error("Start position {0:?} is outside maze bounds")]
InvalidStartPosition(Hex),
/// Occurs when maze generation fails.
#[error("Failed to generate maze: {0}")]
GenerationError(String),
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum MazeError {
/// Error when attempting to access or modify a tile at a non-existent coordinate.
#[error("Invalid coordinate: {0:?}")]
InvalidCoordinate(Hex),
/// Error when a tile's internal position doesn't match its insertion coordinate.
#[error("Tile position ({tile_pos:?}) does not match insertion coordinates ({insert_pos:?})")]
PositionMismatch { tile_pos: Hex, insert_pos: Hex },
/// Error when attempting to insert a tile at an already occupied position.
#[error("A tile {old_tile:?} already exists at position {pos:?}")]
TileAlreadyExists { pos: Hex, old_tile: Tile },
/// Error when a wall operation fails at the specified coordinate and direction.
#[error("Cannot add wall at {coord:?} in direction {direction:?}")]
WallOperationFailed {
coord: Hex,
direction: EdgeDirection,
},
}

View File

@ -1,9 +1,9 @@
use crate::HexMaze;
use crate::Maze;
use hexx::{EdgeDirection, Hex};
use rand::{rngs::StdRng, seq::SliceRandom, thread_rng, Rng, RngCore, SeedableRng};
use std::collections::HashSet;
pub(super) fn generate_backtracking(maze: &mut HexMaze, start_pos: Option<Hex>, seed: Option<u64>) {
pub(super) fn generate_backtracking(maze: &mut Maze, start_pos: Option<Hex>, seed: Option<u64>) {
if maze.is_empty() {
return;
}
@ -21,7 +21,7 @@ pub(super) fn generate_backtracking(maze: &mut HexMaze, start_pos: Option<Hex>,
}
fn recursive_backtrack<R: Rng>(
maze: &mut HexMaze,
maze: &mut Maze,
current: Hex,
visited: &mut HashSet<Hex>,
rng: &mut R,
@ -32,9 +32,9 @@ fn recursive_backtrack<R: Rng>(
for direction in directions {
let neighbor = current + direction;
if maze.get_tile(&neighbor).is_some() && !visited.contains(&neighbor) {
maze.remove_tile_wall(&current, direction);
maze.remove_tile_wall(&neighbor, direction.const_neg());
if maze.get(&neighbor).is_some() && !visited.contains(&neighbor) {
let _ = maze.remove_tile_wall(&current, direction);
let _ = maze.remove_tile_wall(&neighbor, direction.const_neg());
recursive_backtrack(maze, neighbor, visited, rng);
}
}
@ -44,6 +44,7 @@ fn recursive_backtrack<R: Rng>(
mod test {
use super::*;
use crate::builder::create_hex_maze;
use claims::assert_some;
use rstest::rstest;
#[rstest]
@ -72,7 +73,7 @@ mod test {
recursive_backtrack(&mut maze, start, &mut visited, &mut rng);
for &pos in maze.keys() {
let walls = maze.get_walls(&pos).unwrap();
let walls = assert_some!(maze.get_walls(&pos));
assert!(
walls.count() < 6,
"At least one wall should be removed for each tile"
@ -100,12 +101,16 @@ mod test {
for dir in EdgeDirection::ALL_DIRECTIONS {
let neighbor = current + dir;
if let Some(walls) = maze.get_walls(&current) {
if !walls.contains(dir) && maze.get_tile(&neighbor).is_some() {
if !walls.contains(dir) && maze.get(&neighbor).is_some() {
to_visit.push(neighbor);
}
}
}
}
assert_eq!(connected.len(), maze.len(), "All tiles should be connected");
assert_eq!(
connected.len(),
maze.count(),
"All tiles should be connected"
);
}
}

View File

@ -1,5 +1,5 @@
mod backtrack;
use crate::HexMaze;
use crate::Maze;
use backtrack::generate_backtracking;
#[cfg(feature = "bevy")]
use bevy::prelude::*;
@ -15,8 +15,9 @@ pub enum GeneratorType {
#[default]
RecursiveBacktracking,
}
impl GeneratorType {
pub fn generate(&self, maze: &mut HexMaze, start_pos: Option<Hex>, seed: Option<u64>) {
pub fn generate(&self, maze: &mut Maze, start_pos: Option<Hex>, seed: Option<u64>) {
match self {
Self::RecursiveBacktracking => generate_backtracking(maze, start_pos, seed),
}

View File

@ -7,7 +7,6 @@
//! - Efficient bit-flag representation of walls
//! - Multiple maze generation algorithms
//! - Maze builder pattern for easy maze creation
//!
//! # Examples
//!
@ -21,7 +20,7 @@
//! .build()
//! .expect("Failed to create maze");
//!
//! assert_eq!(maze.len(), 37); // A radius of 3 should create 37 tiles
//! assert_eq!(maze.count(), 37); // A radius of 3 should create 37 tiles
//!```
//!
//! Customizing maze generation:
@ -36,7 +35,7 @@
//! .build()
//! .expect("Failed to create maze");
//!
//! assert!(maze.get_tile(&Hex::new(1, -1)).is_some());
//! assert!(maze.get(&Hex::new(1, -1)).is_some());
//!```
//!
//! Manipulating walls:
@ -45,24 +44,30 @@
//! use hexlab::prelude::*;
//!
//! let mut walls = Walls::empty();
//! walls.add(EdgeDirection::FLAT_NORTH);
//! assert!(!walls.insert(EdgeDirection::FLAT_NORTH));
//! assert!(walls.contains(EdgeDirection::FLAT_NORTH));
//! assert!(!walls.contains(EdgeDirection::FLAT_SOUTH));
//!```
mod builder;
pub mod errors;
mod generator;
mod maze;
#[cfg(feature = "pathfinding")]
mod pathfinding;
mod tile;
pub mod traits;
mod walls;
pub use builder::{MazeBuilder, MazeBuilderError};
pub use builder::MazeBuilder;
pub use errors::*;
pub use generator::GeneratorType;
pub use maze::HexMaze;
pub use tile::HexTile;
pub use maze::Maze;
pub use tile::Tile;
pub use traits::*;
pub use walls::Walls;
/// Prelude module containing commonly used types
pub mod prelude {
pub use super::{GeneratorType, HexMaze, HexTile, MazeBuilder, MazeBuilderError, Walls};
pub use super::{errors::*, traits::*, GeneratorType, Maze, MazeBuilder, Tile, Walls};
pub use hexx::{EdgeDirection, Hex, HexLayout};
}

View File

@ -1,4 +1,8 @@
use super::{HexTile, Walls};
use super::{Tile, Walls};
use crate::{
errors::MazeError,
traits::{TilePosition, WallStorage},
};
#[cfg(feature = "bevy")]
use bevy::prelude::*;
#[cfg(feature = "bevy_reflect")]
@ -12,15 +16,14 @@ use std::ops::{Deref, DerefMut};
///
/// This struct stores the layout of a hexagonal maze, including the positions
/// of tiles and their associated walls.
#[allow(clippy::module_name_repetitions)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "bevy", derive(Component))]
#[cfg_attr(feature = "bevy", reflect(Component))]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HexMaze(HashMap<Hex, HexTile>);
pub struct Maze(HashMap<Hex, Tile>);
impl HexMaze {
impl Maze {
/// Creates a new empty maze
///
/// # Examples
@ -28,18 +31,23 @@ impl HexMaze {
/// ```
/// use hexlab::prelude::*;
///
/// let maze = HexMaze::new();
/// let maze = Maze::new();
///
/// assert!(maze.is_empty());
/// assert_eq!(maze.len(), 0);
/// assert_eq!(maze.count(), 0);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Adds a new tile at the specified coordinates
/// Inserts a new tile at the specified coordinates.
///
/// If the map did not have this key present, [`None`] is returned.
///
/// If the map did have this key present, the value is updated, and the old
/// value is returned.
///
/// # Arguments
///
@ -50,43 +58,70 @@ impl HexMaze {
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// let mut maze = Maze::new();
/// let coord = Hex::ZERO;
/// maze.add_tile(coord);
///
/// assert_eq!(maze.len(), 1);
/// assert!(!maze.is_empty());
/// assert_eq!(maze.insert(coord), None);
/// assert_eq!(maze.insert(coord), Some(Tile::new(coord)));
/// ```
pub fn add_tile(&mut self, coords: Hex) {
let tile = HexTile::new(coords);
self.0.insert(coords, tile);
pub fn insert(&mut self, coords: Hex) -> Option<Tile> {
let tile = Tile::new(coords);
self.0.insert(coords, tile)
}
/// Adds a wall in the specified direction at the given coordinates.
/// Adds a new tile at the specified coordinates. It is recommended to use [`insert`].
///
/// [`insert`]: Maze::insert
///
/// # Arguments
///
/// - `coord` - The hexagonal coordinates of the tile.
/// - `direction` - The direction in which to add the wall.
/// - `coords` - The hexagonal coordinates where the tile should be added.
/// - `tile` - The tile to insert to.
///
/// # Errors
///
/// Returns [`MazeError::PositionMismatch`] if the tile's position doesn't match the insertion coordinates.
/// Returns [`MazeError::TileAlreadyExists`] if a tile already exists at the specified coordinates.
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// let coord = Hex::ZERO;
/// maze.add_tile(coord);
/// let mut maze = Maze::new();
///
/// maze.add_wall(coord, EdgeDirection::FLAT_NORTH);
/// let walls = maze.get_walls(&coord);
/// assert!(walls.is_some());
/// assert!(walls.unwrap().contains(EdgeDirection::FLAT_NORTH));
/// assert_eq!(
/// maze.insert_with_tile(Hex::new(2, 2), Tile::new(Hex::ZERO)),
/// Err(MazeError::PositionMismatch {
/// tile_pos: Hex::ZERO,
/// insert_pos: Hex::new(2, 2)
/// })
/// );
/// let tile = Tile::new(Hex::ZERO);
/// assert_eq!(maze.insert_with_tile(Hex::ZERO, tile.clone()), Ok(tile.clone()));
/// assert_eq!(
/// maze.insert_with_tile(Hex::ZERO, tile.clone()),
/// Err(MazeError::TileAlreadyExists {
/// pos: Hex::ZERO,
/// old_tile: tile
/// })
/// );
/// ```
pub fn add_wall(&mut self, coord: Hex, direction: EdgeDirection) {
if let Some(tile) = self.0.get_mut(&coord) {
tile.walls.add(direction);
pub fn insert_with_tile(&mut self, coords: Hex, tile: Tile) -> Result<Tile, MazeError> {
if tile.pos != coords {
return Err(MazeError::PositionMismatch {
tile_pos: tile.pos,
insert_pos: coords,
});
}
self.0
.insert(coords, tile.clone())
.map_or(Ok(tile), |old_tile| {
Err(MazeError::TileAlreadyExists {
pos: coords,
old_tile,
})
})
}
/// Returns a reference to the tile at the specified coordinates.
@ -100,20 +135,26 @@ impl HexMaze {
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// let mut maze = Maze::new();
/// let coord = Hex::ZERO;
/// maze.add_tile(coord);
/// maze.insert(coord);
///
/// assert!(maze.get_tile(&coord).is_some());
/// assert!(maze.get_tile(&Hex::new(1, 1)).is_none());
/// assert!(maze.get(&coord).is_some());
/// assert!(maze.get(&Hex::new(1, 1)).is_none());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn get_tile(&self, coord: &Hex) -> Option<&HexTile> {
pub fn get(&self, coord: &Hex) -> Option<&Tile> {
self.0.get(coord)
}
/// Returns an optional reference to the walls at the specified coordinates.
#[inline]
#[must_use]
pub fn get_mut(&mut self, coord: &Hex) -> Option<&mut Tile> {
self.0.get_mut(coord)
}
/// Returns an optional mutable reference to the walls at the specified coordinates.
///
/// # Arguments
///
@ -124,16 +165,43 @@ impl HexMaze {
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// let mut maze = Maze::new();
/// let coord = Hex::new(0, 0);
/// maze.add_tile(coord);
/// maze.insert(coord);
///
/// maze.add_wall(coord, EdgeDirection::FLAT_NORTH);
/// maze.add_tile_wall(&coord, EdgeDirection::FLAT_NORTH);
/// let walls = maze.get_walls(&coord).unwrap();
/// assert!(walls.contains(EdgeDirection::FLAT_NORTH));
/// ```
#[inline]
#[must_use]
pub fn get_walls(&self, coord: &Hex) -> Option<&Walls> {
self.0.get(coord).map(HexTile::walls)
self.0.get(coord).map(Tile::walls)
}
/// Returns an optional mutable reference to the walls at the specified coordinates.
///
/// # Arguments
///
/// - `coord` - The hexagonal coordinates of the tile whose walls to retrieve.
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = Maze::new();
/// let coord = Hex::new(0, 0);
/// maze.insert(coord);
///
/// maze.add_tile_wall(&coord, EdgeDirection::FLAT_NORTH);
/// let mut walls = maze.get_walls_mut(&coord).unwrap();
/// assert!(walls.remove(EdgeDirection::FLAT_NORTH));
/// ```
#[inline]
#[must_use]
pub fn get_walls_mut(&mut self, coord: &Hex) -> Option<&mut Walls> {
self.0.get_mut(coord).map(Tile::walls_mut)
}
/// Returns the number of tiles in the maze.
@ -143,18 +211,18 @@ impl HexMaze {
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// assert_eq!(maze.len(), 0);
/// let mut maze = Maze::new();
/// assert_eq!(maze.count(), 0);
///
/// maze.add_tile(Hex::new(0, 0));
/// assert_eq!(maze.len(), 1);
/// maze.insert(Hex::new(0, 0));
/// assert_eq!(maze.count(), 1);
///
/// maze.add_tile(Hex::new(1, -1));
/// assert_eq!(maze.len(), 2);
/// maze.insert(Hex::new(1, -1));
/// assert_eq!(maze.count(), 2);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn len(&self) -> usize {
pub fn count(&self) -> usize {
self.0.len()
}
@ -165,54 +233,147 @@ impl HexMaze {
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// let mut maze = Maze::new();
/// assert!(maze.is_empty());
///
/// maze.add_tile(Hex::ZERO);
/// maze.insert(Hex::ZERO);
/// assert!(!maze.is_empty());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Adds a wall from a tile in the specified direction.
///
/// # Arguments
///
/// - `coord` - The hexagonal coordinates of the tile.
/// - `direction` - The direction of the wall to remove.
///
/// # Errors
///
/// Returns `MazeError::InvalidCoordinate` if the specified coordinate does not exist in the maze.
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// // Create a maze with a single tile at the origin
/// let mut tile = Tile::new(Hex::ZERO);
/// tile.walls_mut().toggle(Walls::all_directions());
/// let mut maze = Maze::from([tile]);
///
/// // Initially, the tile should have no walls
/// assert!(maze.get_walls(&Hex::ZERO).unwrap().is_empty());
///
/// // Add a wall to the north
/// assert!(maze.add_tile_wall(&Hex::ZERO, EdgeDirection::FLAT_NORTH).is_ok());
///
/// // Check that the wall was added
/// let walls = maze.get_walls(&Hex::ZERO).unwrap();
/// assert!(walls.contains(EdgeDirection::FLAT_NORTH));
/// assert_eq!(walls.count(), 1);
///
/// // Adding the same wall again should return true (no change)
/// assert_eq!(maze.add_tile_wall(&Hex::ZERO, EdgeDirection::FLAT_NORTH), Ok(true));
///
/// // Adding a wall to a non-existent tile should return an error
/// let invalid_coord = Hex::new(1, 1);
/// assert_eq!(
/// maze.add_tile_wall(&invalid_coord, EdgeDirection::FLAT_NORTH),
/// Err(MazeError::InvalidCoordinate(invalid_coord))
/// );
/// ```
pub fn add_tile_wall(
&mut self,
coord: &Hex,
direction: EdgeDirection,
) -> Result<bool, MazeError> {
self.0
.get_mut(coord)
.map(|tile| tile.walls.insert(direction))
.ok_or(MazeError::InvalidCoordinate(*coord))
}
/// Removes a wall from a tile in the specified direction.
///
/// # Arguments
///
/// - `coord` - The hexagonal coordinates of the tile.
/// - `direction` - The direction of the wall to remove.
///
/// # Errors
///
/// Returns `MazeError::InvalidCoordinate` if the specified coordinate does not exist in the maze.
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let mut maze = HexMaze::new();
/// let mut maze = Maze::new();
/// let coord = Hex::ZERO;
/// maze.add_tile(coord);
/// maze.insert(coord);
///
/// maze.add_wall(coord, EdgeDirection::FLAT_NORTH);
/// maze.add_tile_wall(&coord, EdgeDirection::FLAT_NORTH);
/// maze.remove_tile_wall(&coord, EdgeDirection::FLAT_NORTH);
///
/// let walls = maze.get_walls(&coord).unwrap();
/// assert!(!walls.contains(EdgeDirection::FLAT_NORTH));
/// ```
pub fn remove_tile_wall(&mut self, coord: &Hex, direction: EdgeDirection) {
if let Some(tile) = self.0.get_mut(coord) {
tile.walls.remove(direction);
}
pub fn remove_tile_wall(
&mut self,
coord: &Hex,
direction: EdgeDirection,
) -> Result<bool, MazeError> {
self.0
.get_mut(coord)
.map(|tile| tile.walls.remove(direction))
.ok_or(MazeError::InvalidCoordinate(*coord))
}
}
impl Deref for HexMaze {
type Target = HashMap<Hex, HexTile>;
impl FromIterator<Hex> for Maze {
fn from_iter<T: IntoIterator<Item = Hex>>(iter: T) -> Self {
Self(iter.into_iter().map(|hex| (hex, Tile::new(hex))).collect())
}
}
impl FromIterator<Tile> for Maze {
fn from_iter<T: IntoIterator<Item = Tile>>(iter: T) -> Self {
Self(iter.into_iter().map(|tile| (tile.pos(), tile)).collect())
}
}
impl FromIterator<(Hex, Tile)> for Maze {
fn from_iter<T: IntoIterator<Item = (Hex, Tile)>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl<const N: usize> From<[Hex; N]> for Maze {
fn from(value: [Hex; N]) -> Self {
value.into_iter().collect()
}
}
impl<const N: usize> From<[Tile; N]> for Maze {
fn from(value: [Tile; N]) -> Self {
value.into_iter().collect()
}
}
impl Deref for Maze {
type Target = HashMap<Hex, Tile>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for HexMaze {
impl DerefMut for Maze {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}

84
src/pathfinding.rs Normal file
View File

@ -0,0 +1,84 @@
//! Maze pathfinding implementation for hexagonal grids.
//!
//! This module provides functionality for finding paths through a hexagonal maze
//! using the A* pathfinding algorithm. The maze is represented as a collection of
//! hexagonal cells, where each cell may have walls on any of its six edges.
//!
//! # Examples
//!
//! ```
//! use hexlab::prelude::*;
//!
//! let maze = MazeBuilder::new()
//! .with_radius(3)
//! .with_seed(12345)
//! .build()
//! .expect("Failed to create maze");
//! assert!(maze.find_path(Hex::ZERO, Hex::new(-1, 3)).is_some());
//! ```
//!
//! # Implementation Details
//!
//! The pathfinding algorithm uses Manhattan distance as a heuristic and considers
//! walls between cells when determining valid paths. Each step between adjacent
//! cells has a cost of 1.
use hexx::{EdgeDirection, Hex};
use pathfinding::prelude::*;
use crate::Maze;
impl Maze {
#[must_use]
/// Finds the shortest path between two hexagonal positions in the maze using A* pathfinding.
///
/// This function calculates the optimal path while taking into account walls between cells.
/// The path cost between adjacent cells is always 1, and Manhattan distance is used as the
/// heuristic for pathfinding.
///
/// # Arguments
///
/// * `from` - The starting hexagonal position
/// * `to` - The target hexagonal position
///
/// # Returns
///
/// * `Some(Vec<Hex>)` - A vector of hexagonal positions representing the path from start to target
/// * `None` - If no valid path exists between the positions
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let maze = MazeBuilder::new()
/// .with_radius(3)
/// .with_seed(12345)
/// .build()
/// .expect("Failed to create maze");
/// assert!(maze.find_path(Hex::ZERO, Hex::new(-1, 3)).is_some());
/// ```
pub fn find_path(&self, from: Hex, to: Hex) -> Option<Vec<Hex>> {
let successors = |pos: &Hex| {
{
EdgeDirection::ALL_DIRECTIONS.iter().filter_map(|&dir| {
let neighbor = pos.neighbor(dir);
if let Some(current_tile) = self.get(pos) {
if self.get(&neighbor).is_some() && !current_tile.walls.contains(dir) {
return Some((neighbor, 1)); // Cost of 1 for each step
}
}
None
})
}
.collect::<Vec<_>>()
};
let heuristic = |pos: &Hex| {
// Manhatan distance
let diff = *pos - to;
(diff.x.abs() + diff.y.abs() + diff.z().abs()) / 2
};
astar(&from, successors, heuristic, |pos| *pos == to).map(|(path, _)| path)
}
}

View File

@ -1,4 +1,7 @@
use super::Walls;
#[cfg(feature = "bevy_reflect")]
use crate::traits::WorldPositionable;
use crate::traits::{TilePosition, WallStorage};
#[cfg(feature = "bevy")]
use bevy::prelude::*;
use hexx::Hex;
@ -9,18 +12,90 @@ use std::fmt::Display;
/// Represents a single hexagonal tile in the maze
///
/// Each tile has a position and a set of walls defining its boundaries.
#[allow(clippy::module_name_repetitions)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "bevy", derive(Component))]
#[cfg_attr(feature = "bevy", reflect(Component))]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HexTile {
pub struct Tile {
pub(crate) pos: Hex,
pub(crate) walls: Walls,
}
impl HexTile {
impl TilePosition for Tile {
/// Returns position of the tile
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let tile = Tile::new(Hex::new(2, -2));
/// assert_eq!(tile.pos(), Hex::new(2, -2));
/// ```
#[inline]
fn pos(&self) -> Hex {
self.pos
}
}
impl WallStorage for Tile {
/// Returns an immutable reference to the tile's walls
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let tile = Tile::new(Hex::ZERO);
/// assert_eq!(*tile.walls(), Walls::default());
/// ```
#[inline]
fn walls(&self) -> &Walls {
&self.walls
}
/// Returns a mutable reference to the tile's walls
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let tile = Tile::new(Hex::ZERO);
/// assert_eq!(*tile.walls(), Walls::default());
/// ```
#[inline]
fn walls_mut(&mut self) -> &mut Walls {
&mut self.walls
}
}
#[cfg(feature = "bevy_reflect")]
impl WorldPositionable for Tile {
/// Converts the tile's position to a 2D vector based on the given layout.
///
/// # Arguments
///
/// - `layout` - The hexagonal layout used for conversion.
#[inline]
fn to_vec2(&self, layout: &HexLayout) -> glam::Vec2 {
layout.hex_to_world_pos(self.pos)
}
/// Converts the tile's position to a 3D vector based on the given layout.
///
/// # Arguments
///
/// - `layout` - The hexagonal layout used for conversion.
#[inline]
fn to_vec3(&self, layout: &HexLayout) -> glam::Vec3 {
let pos = self.to_vec2(layout);
glam::Vec3::new(pos.x, 0., pos.y)
}
}
impl Tile {
/// Creates a new tile with the given position and default walls.
///
/// # Arguments
@ -32,7 +107,7 @@ impl HexTile {
/// ```
/// use hexlab::prelude::*;
///
/// let tile = HexTile::new(Hex::new(1, -1));
/// let tile = Tile::new(Hex::new(1, -1));
/// assert_eq!(tile.pos(), Hex::new(1, -1));
/// assert_eq!(*tile.walls(), Walls::default());
/// ```
@ -43,68 +118,9 @@ impl HexTile {
walls: Walls::default(),
}
}
/// Returns a reference to the tile's walls
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let tile = HexTile::new(Hex::ZERO);
/// assert_eq!(*tile.walls(), Walls::default());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[must_use]
pub const fn walls(&self) -> &Walls {
&self.walls
}
/// Returns position of the tile
///
/// # Examples
///
/// ```
/// use hexlab::prelude::*;
///
/// let tile = HexTile::new(Hex::new(2, -2));
/// assert_eq!(tile.pos(), Hex::new(2, -2));
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[must_use]
pub const fn pos(&self) -> Hex {
self.pos
}
/// Converts the tile's position to a 2D vector based on the given layout.
///
/// # Arguments
///
/// - `layout` - The hexagonal layout used for conversion.
#[cfg(feature = "bevy_reflect")]
#[cfg_attr(not(debug_assertions), inline)]
#[must_use]
pub fn to_vec2(&self, layout: &HexLayout) -> glam::Vec2 {
layout.hex_to_world_pos(self.pos)
}
/// Converts the tile's position to a 3D vector based on the given layout.
///
/// # Arguments
///
/// - `layout` - The hexagonal layout used for conversion.
#[cfg(feature = "bevy_reflect")]
#[cfg_attr(not(debug_assertions), inline)]
#[must_use]
pub fn to_vec3(&self, layout: &HexLayout) -> glam::Vec3 {
use glam::Vec3;
let pos = self.to_vec2(layout);
Vec3::new(pos.x, 0., pos.y)
}
}
impl From<Hex> for HexTile {
impl From<Hex> for Tile {
fn from(value: Hex) -> Self {
Self {
pos: value,
@ -113,7 +129,7 @@ impl From<Hex> for HexTile {
}
}
impl Display for HexTile {
impl Display for Tile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({},{})", self.pos.x, self.pos.y)
}
@ -130,19 +146,6 @@ mod test {
Hex::new(rng.gen(), rng.gen())
}
#[test]
fn tile_modification() {
let hex = random_hex();
let mut tile = HexTile::new(hex);
// Modify walls
tile.walls.remove(EdgeDirection::FLAT_TOP);
assert!(!tile.walls.contains(EdgeDirection::FLAT_TOP));
tile.walls.add(EdgeDirection::FLAT_TOP);
assert!(tile.walls.contains(EdgeDirection::FLAT_TOP));
}
#[test]
fn different_positions() {
let positions = [Hex::ZERO, Hex::new(1, 0), Hex::new(-1, 1), Hex::new(2, -2)];
@ -150,7 +153,7 @@ mod test {
// Create tiles at different positions
let tiles = positions
.iter()
.map(|&pos| HexTile::new(pos))
.map(|&pos| Tile::new(pos))
.collect::<Vec<_>>();
// Verify each tile has correct position
@ -170,7 +173,7 @@ mod test {
];
for pos in extreme_positions {
let tile = HexTile::new(pos);
let tile = Tile::new(pos);
assert_eq!(tile.pos, pos);
}
}
@ -178,7 +181,7 @@ mod test {
#[test]
fn hex_tile_creation_and_properties() {
let hex = random_hex();
let tile = HexTile::new(hex);
let tile = Tile::new(hex);
assert_eq!(tile.pos(), hex);
assert!(tile.walls().is_enclosed());
@ -187,7 +190,7 @@ mod test {
#[test]
fn hex_tile_from_hex() {
let hex = random_hex();
let tile = HexTile::from(hex);
let tile = Tile::from(hex);
assert_eq!(tile.pos, hex);
assert_eq!(tile.walls, Walls::default());
@ -196,7 +199,7 @@ mod test {
#[test]
fn hex_hex_into_tile() {
let hex = random_hex();
let tile: HexTile = hex.into();
let tile: Tile = hex.into();
assert_eq!(tile.pos, hex);
assert_eq!(tile.walls, Walls::default());
@ -204,16 +207,16 @@ mod test {
#[test]
fn hex_tile_display() {
let tile = HexTile::new(Hex::new(3, -3));
let tile = Tile::new(Hex::new(3, -3));
assert_eq!(format!("{tile}"), "(3,-3)");
}
#[test]
fn hex_tile_wall_modifications() {
let mut tile = HexTile::new(Hex::ZERO);
let mut tile = Tile::new(Hex::ZERO);
for direction in EdgeDirection::ALL_DIRECTIONS {
tile.walls.add(direction);
tile.walls.insert(direction);
}
assert_eq!(tile.walls.count(), 6);
@ -231,17 +234,17 @@ mod test {
#[test]
fn hex_tile_to_vec2() {
let layout = HexLayout::default();
let tile = HexTile::new(Hex::new(1, 0));
let tile = Tile::new(Hex::new(1, 0));
let vec2 = tile.to_vec2(&layout);
assert_eq!(vec2, Vec2::new(1.5, -0.8660254));
assert_eq!(vec2, Vec2::new(1.5, -0.866_025_4));
}
#[test]
fn hex_tile_to_vec3() {
let layout = HexLayout::default();
let tile = HexTile::new(Hex::new(0, 1));
let tile = Tile::new(Hex::new(0, 1));
let vec3 = tile.to_vec3(&layout);
assert_eq!(vec3, Vec3::new(0.0, 0.0, -1.7320508));
assert_eq!(vec3, Vec3::new(0.0, 0.0, -1.732_050_8));
}
}
}

22
src/traits.rs Normal file
View File

@ -0,0 +1,22 @@
use crate::Walls;
use hexx::Hex;
pub trait TilePosition {
/// Returns position of the tile
#[must_use]
fn pos(&self) -> Hex;
}
#[cfg(feature = "bevy_reflect")]
pub trait WorldPositionable {
#[must_use]
fn to_vec2(&self, layout: &hexx::HexLayout) -> glam::Vec2;
#[must_use]
fn to_vec3(&self, layout: &hexx::HexLayout) -> glam::Vec3;
}
pub trait WallStorage {
#[must_use]
fn walls(&self) -> &Walls;
fn walls_mut(&mut self) -> &mut Walls;
}

View File

@ -16,15 +16,15 @@ use hexx::EdgeDirection;
///
/// // Create a hexagon with all walls
/// let walls = Walls::new();
/// assert!(walls.is_closed());
/// assert!(walls.is_enclosed());
///
/// // Create a hexagon with no walls
/// let mut walls = Walls::empty();
/// assert!(walls.is_empty());
///
/// // Add specific walls
/// walls.add(EdgeDirection::FLAT_NORTH);
/// walls.add(EdgeDirection::FLAT_SOUTH);
/// walls.insert(EdgeDirection::FLAT_NORTH);
/// walls.insert(EdgeDirection::FLAT_SOUTH);
/// assert_eq!(walls.count(), 2);
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@ -47,7 +47,7 @@ impl Walls {
/// let walls = Walls::new();
/// assert!(walls.is_enclosed());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
@ -63,7 +63,7 @@ impl Walls {
/// let walls = Walls::empty();
/// assert!(walls.is_empty());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn empty() -> Self {
Self(0)
@ -79,17 +79,21 @@ impl Walls {
/// let walls = Walls::empty();
/// assert!(walls.is_empty());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
/// Adds a wall in the specified direction.
/// Insert a wall in the specified direction.
///
/// # Arguments
///
/// - `direction` - The direction in which to add the wall.
/// - `direction` - The direction in which to insert the wall.
///
/// # Returns
///
/// Returns `true` if a wall was present, `false` otherwise.
///
/// # Examples
///
@ -99,22 +103,24 @@ impl Walls {
/// let mut walls = Walls::empty();
/// assert_eq!(walls.count(), 0);
///
/// walls.add(1);
/// assert!(!walls.insert(1));
/// assert_eq!(walls.count(), 1);
///
/// walls.add(1);
/// assert!(walls.insert(1));
/// assert_eq!(walls.count(), 1);
///
/// walls.add(EdgeDirection::FLAT_NORTH);
/// assert!(!walls.insert(EdgeDirection::FLAT_NORTH));
/// assert_eq!(walls.count(), 2);
///
/// ```
#[cfg_attr(not(debug_assertions), inline)]
pub fn add<T>(&mut self, direction: T)
#[inline]
pub fn insert<T>(&mut self, direction: T) -> bool
where
T: Into<Self> + Copy,
T: Into<Self>,
{
self.0 |= direction.into().0;
let mask = direction.into().0;
let was_present = self.0 & mask != 0;
self.0 |= mask;
was_present
}
/// Removes a wall in the specified direction.
@ -123,6 +129,10 @@ impl Walls {
///
/// - `direction` - The direction from which to remove the wall.
///
/// # Returns
///
/// Returns `true` if a wall was present and removed, `false` otherwise.
///
/// # Examples
///
/// ```
@ -139,16 +149,15 @@ impl Walls {
/// assert!(walls.remove(EdgeDirection::FLAT_NORTH));
/// assert_eq!(walls.count(), 4);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
pub fn remove<T>(&mut self, direction: T) -> bool
where
T: Into<Self> + Copy,
T: Into<Self>,
{
let was_removed = self.contains(direction);
if was_removed {
self.0 &= !direction.into().0;
}
was_removed
let mask = direction.into().0;
let was_present = self.0 & mask != 0;
self.0 &= !mask;
was_present
}
/// Checks if there is a wall in the specified direction.
@ -163,17 +172,17 @@ impl Walls {
/// use hexlab::prelude::*;
///
/// let mut walls = Walls::empty();
/// walls.add(EdgeDirection::FLAT_NORTH);
/// walls.insert(EdgeDirection::FLAT_NORTH);
///
/// assert!(walls.contains(EdgeDirection::FLAT_NORTH));
/// assert!(!walls.contains(EdgeDirection::FLAT_SOUTH));
/// ```
#[cfg_attr(not(debug_assertions), inline)]
pub fn contains<T>(&self, other: T) -> bool
#[inline]
pub fn contains<T>(&self, direction: T) -> bool
where
T: Into<Self> + Copy,
T: Into<Self>,
{
self.0 & other.into().0 != 0
self.0 & direction.into().0 != 0
}
/// Returns the raw bit representation of the walls
@ -189,7 +198,7 @@ impl Walls {
/// let walls = Walls::empty();
/// assert_eq!(walls.as_bits(), 0);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn as_bits(&self) -> u8 {
self.0
@ -205,13 +214,13 @@ impl Walls {
/// let mut walls = Walls::empty();
/// assert!(walls.is_empty());
///
/// walls.add(0);
/// walls.insert(0);
/// assert_eq!(walls.count(), 1);
///
/// walls.add(1);
/// walls.insert(1);
/// assert_eq!(walls.count(), 2);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn count(&self) -> u8 {
u8::try_from(self.0.count_ones()).unwrap_or_default()
@ -226,7 +235,7 @@ impl Walls {
///
/// assert_eq!(Walls::all_directions().as_bits(), 0b11_1111);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub const fn all_directions() -> Self {
Self(0b11_1111)
@ -262,29 +271,10 @@ impl Walls {
where
T: Into<Self> + Copy,
{
let is_present = self.contains(direction);
if is_present {
self.remove(direction);
} else {
self.add(direction);
}
is_present
}
/// Checks if walls are present in all six directions.
///
/// # Returns
///
/// `true` if the hexagon has all possible walls, making it completely enclosed.
///
/// # Deprecated
///
/// This method is deprecated since version 0.4.0. Use `is_enclosed()` instead.
#[cfg_attr(not(debug_assertions), inline)]
#[must_use]
#[deprecated(since = "0.4.0", note = "use `walls::Walls::is_enclosed()`")]
pub fn is_closed(&self) -> bool {
self.is_enclosed()
let mask = direction.into().0;
let was_present = self.0 & mask != 0;
self.0 ^= mask;
was_present
}
/// Checks if walls are present in all six directions.
@ -304,7 +294,7 @@ impl Walls {
/// walls.remove(0);
/// assert!(!walls.is_enclosed());
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
#[must_use]
pub fn is_enclosed(&self) -> bool {
self.count() == 6
@ -317,7 +307,7 @@ impl Walls {
///
/// # Arguments
///
/// - `other` - The walls to add, specified as a `Walls` instance or any type
/// - `other` - The walls to insert, specified as a `Walls` instance or any type
/// that can be converted into `Walls`.
///
///
@ -332,7 +322,7 @@ impl Walls {
/// assert!(walls.contains(EdgeDirection::FLAT_SOUTH));
/// assert_eq!(walls.count(), 3);
/// ```
#[cfg_attr(not(debug_assertions), inline)]
#[inline]
pub fn fill<T>(&mut self, other: T)
where
T: Into<Self>,
@ -385,7 +375,7 @@ mod test {
let walls = Walls::all_directions();
assert!(walls.is_enclosed());
assert!(!walls.is_empty());
assert_eq!(walls.as_bits(), 0b111111);
assert_eq!(walls.as_bits(), 0b11_1111);
}
// as_bits
@ -398,22 +388,22 @@ mod test {
#[test]
fn as_bits_single_wall() {
let mut walls = Walls::empty();
walls.add(EdgeDirection::FLAT_NORTH);
assert_eq!(walls.as_bits(), 0b010000);
walls.insert(EdgeDirection::FLAT_NORTH);
assert_eq!(walls.as_bits(), 0b01_0000);
}
#[test]
fn as_bits_multiple_walls() {
let mut walls = Walls::empty();
walls.add(EdgeDirection::FLAT_NORTH);
walls.add(EdgeDirection::FLAT_SOUTH);
assert_eq!(walls.as_bits(), 0b010010);
walls.insert(EdgeDirection::FLAT_NORTH);
walls.insert(EdgeDirection::FLAT_SOUTH);
assert_eq!(walls.as_bits(), 0b01_0010);
}
#[test]
fn as_bits_all_walls() {
let walls = Walls::new();
assert_eq!(walls.as_bits(), 0b111111);
assert_eq!(walls.as_bits(), 0b11_1111);
}
// new
@ -421,7 +411,7 @@ mod test {
fn new_created_closed_walls() {
let walls = Walls::new();
assert!(walls.is_enclosed());
assert_eq!(walls.as_bits(), 0b111111);
assert_eq!(walls.as_bits(), 0b11_1111);
}
// empty
@ -432,11 +422,11 @@ mod test {
assert_eq!(walls.as_bits(), 0);
}
// add
// insert
#[test]
fn add_single_wall() {
fn insert_single_wall() {
let mut walls = Walls::empty();
walls.add(EdgeDirection::FLAT_NORTH);
walls.insert(EdgeDirection::FLAT_NORTH);
assert!(walls.contains(EdgeDirection::FLAT_NORTH));
assert_eq!(walls.count(), 1);
}
@ -453,13 +443,13 @@ mod test {
fn remove_nonexistent_wall() {
let mut walls = Walls::empty();
assert!(!walls.remove(EdgeDirection::FLAT_NORTH));
walls.add(EdgeDirection::FLAT_NORTH);
walls.insert(EdgeDirection::FLAT_NORTH);
assert!(walls.remove(EdgeDirection::FLAT_NORTH));
}
// toggle
#[test]
fn toggle_adds_wall() {
fn toggle_wall() {
let mut walls = Walls::empty();
assert!(!walls.toggle(EdgeDirection::FLAT_NORTH));
assert!(walls.contains(EdgeDirection::FLAT_NORTH));
@ -485,7 +475,7 @@ mod test {
#[test]
fn fill_preserves_existing_walls() {
let mut walls = Walls::empty();
walls.add(EdgeDirection::FLAT_NORTH);
walls.insert(EdgeDirection::FLAT_NORTH);
walls.fill([EdgeDirection::FLAT_SOUTH, EdgeDirection::FLAT_SOUTH_EAST]);
assert!(walls.contains(EdgeDirection::FLAT_NORTH));
assert!(walls.contains(EdgeDirection::FLAT_SOUTH));
@ -530,7 +520,7 @@ mod test {
fn default_creates_closed_walls() {
let walls = Walls::default();
assert!(walls.is_enclosed());
assert_eq!(walls.as_bits(), 0b111111);
assert_eq!(walls.as_bits(), 0b11_1111);
}
#[test]
@ -551,54 +541,54 @@ mod test {
let mut walls = Walls::empty();
// Test single bit operations
walls.add(EdgeDirection::FLAT_NORTH);
assert_eq!(walls.as_bits(), 0b010000);
walls.insert(EdgeDirection::FLAT_NORTH);
assert_eq!(walls.as_bits(), 0b01_0000);
walls.add(EdgeDirection::FLAT_SOUTH);
assert_eq!(walls.as_bits(), 0b010010);
walls.insert(EdgeDirection::FLAT_SOUTH);
assert_eq!(walls.as_bits(), 0b01_0010);
// Test removing middle bit
walls.add(EdgeDirection::FLAT_SOUTH_EAST);
assert_eq!(walls.as_bits(), 0b010011);
walls.insert(EdgeDirection::FLAT_SOUTH_EAST);
assert_eq!(walls.as_bits(), 0b01_0011);
walls.remove(EdgeDirection::FLAT_SOUTH);
assert_eq!(walls.as_bits(), 0b010001);
assert_eq!(walls.as_bits(), 0b01_0001);
}
// From<EdgeDirection> tests
#[test]
fn from_edge_direction_flat_south_east() {
let walls = Walls::from(EdgeDirection::FLAT_SOUTH_EAST);
assert_eq!(walls.as_bits(), 0b000001);
assert_eq!(walls.as_bits(), 0b00_0001);
}
#[test]
fn from_edge_direction_flat_south() {
let walls = Walls::from(EdgeDirection::FLAT_SOUTH);
assert_eq!(walls.as_bits(), 0b000010);
assert_eq!(walls.as_bits(), 0b00_0010);
}
#[test]
fn from_edge_direction_flat_south_west() {
let walls = Walls::from(EdgeDirection::FLAT_SOUTH_WEST);
assert_eq!(walls.as_bits(), 0b000100);
assert_eq!(walls.as_bits(), 0b00_0100);
}
#[test]
fn from_edge_direction_flat_north_west() {
let walls = Walls::from(EdgeDirection::FLAT_NORTH_WEST);
assert_eq!(walls.as_bits(), 0b001000);
assert_eq!(walls.as_bits(), 0b00_1000);
}
#[test]
fn from_edge_direction_flat_north() {
let walls = Walls::from(EdgeDirection::FLAT_NORTH);
assert_eq!(walls.as_bits(), 0b010000);
assert_eq!(walls.as_bits(), 0b01_0000);
}
#[test]
fn from_edge_direction_flat_east() {
let walls = Walls::from(EdgeDirection::FLAT_NORTH_EAST);
assert_eq!(walls.as_bits(), 0b100000);
assert_eq!(walls.as_bits(), 0b10_0000);
}
// FromIterator tests
@ -613,7 +603,7 @@ mod test {
let walls = vec![EdgeDirection::FLAT_SOUTH]
.into_iter()
.collect::<Walls>();
assert_eq!(walls.as_bits(), 0b000010);
assert_eq!(walls.as_bits(), 0b00_0010);
}
#[test]
@ -621,7 +611,7 @@ mod test {
let walls = vec![EdgeDirection::FLAT_NORTH, EdgeDirection::FLAT_SOUTH]
.into_iter()
.collect::<Walls>();
assert_eq!(walls.as_bits(), 0b010010);
assert_eq!(walls.as_bits(), 0b01_0010);
}
#[test]
@ -633,13 +623,13 @@ mod test {
]
.into_iter()
.collect::<Walls>();
assert_eq!(walls.as_bits(), 0b010010);
assert_eq!(walls.as_bits(), 0b01_0010);
}
#[test]
fn from_iterator_all_directions() {
let walls = EdgeDirection::iter().collect::<Walls>();
assert_eq!(walls.as_bits(), 0b111111);
assert_eq!(walls.as_bits(), 0b11_1111);
}
// From<[EdgeDirection; N]> tests
@ -652,13 +642,13 @@ mod test {
#[test]
fn from_array_single() {
let walls = Walls::from([EdgeDirection::FLAT_NORTH]);
assert_eq!(walls.as_bits(), 0b010000);
assert_eq!(walls.as_bits(), 0b01_0000);
}
#[test]
fn from_array_multiple() {
let walls = Walls::from([EdgeDirection::FLAT_NORTH, EdgeDirection::FLAT_SOUTH]);
assert_eq!(walls.as_bits(), 0b010010);
assert_eq!(walls.as_bits(), 0b01_0010);
}
#[test]
@ -668,7 +658,7 @@ mod test {
EdgeDirection::FLAT_NORTH,
EdgeDirection::FLAT_SOUTH,
]);
assert_eq!(walls.as_bits(), 0b010010);
assert_eq!(walls.as_bits(), 0b01_0010);
}
#[test]
@ -681,6 +671,6 @@ mod test {
EdgeDirection::FLAT_SOUTH_WEST,
EdgeDirection::FLAT_NORTH_WEST,
]);
assert_eq!(walls.as_bits(), 0b111111);
assert_eq!(walls.as_bits(), 0b11_1111);
}
}

View File

@ -10,7 +10,7 @@ use rstest::rstest;
#[case(5, 91)]
fn maze_size(#[case] radius: u16, #[case] expected_size: usize) {
let maze = assert_ok!(MazeBuilder::new().with_radius(radius).build());
assert_eq!(maze.len(), expected_size);
assert_eq!(maze.count(), expected_size);
}
#[test]
@ -29,7 +29,7 @@ fn valid_start_position(#[case] start_pos: Hex) {
.with_radius(3)
.with_start_position(start_pos)
.build());
assert_some!(maze.get_tile(&start_pos));
assert_some!(maze.get(&start_pos));
}
#[test]
@ -67,28 +67,24 @@ fn maze_connectivity() {
let maze = assert_ok!(MazeBuilder::new().with_radius(3).build());
// Helper function to count accessible neighbors
fn count_accessible_neighbors(maze: &HexMaze, pos: Hex) -> usize {
let count_accessible_neighbors = |pos: Hex| -> usize {
hexx::EdgeDirection::ALL_DIRECTIONS
.iter()
.filter(|&&dir| {
let neighbor = pos + dir;
if let Some(walls) = maze.get_walls(&pos) {
!walls.contains(dir) && maze.get_tile(&neighbor).is_some()
} else {
false
}
maze.get_walls(&pos)
.is_some_and(|walls| !walls.contains(dir) && maze.get(&neighbor).is_some())
})
.count()
}
};
// Check that each tile has at least one connection
for &pos in maze.keys() {
let accessible_neighbors = count_accessible_neighbors(&maze, pos);
claims::assert_gt!(
let accessible_neighbors = count_accessible_neighbors(pos);
assert_gt!(
accessible_neighbors,
0,
"Tile at {:?} has no accessible neighbors",
pos
"Tile at {pos:?} has no accessible neighbors",
);
}
}
@ -96,10 +92,9 @@ fn maze_connectivity() {
#[test]
fn maze_boundaries() {
let radius = 3;
let maze = MazeBuilder::new()
.with_radius(radius as u16)
.build()
.unwrap();
let maze = assert_ok!(MazeBuilder::new().with_radius(radius).build());
let radius = i32::from(radius);
// Test that tiles exist within the radius
for q in -radius..=radius {
@ -107,9 +102,8 @@ fn maze_boundaries() {
let pos = Hex::new(q, r);
if q.abs() + r.abs() <= radius {
assert!(
maze.get_tile(&pos).is_some(),
"Expected tile at {:?} to exist",
pos
maze.get(&pos).is_some(),
"Expected tile at {pos:?} to exist",
);
}
}
@ -126,5 +120,5 @@ fn generate_maze_with_different_types(#[case] generator: GeneratorType) {
.with_generator(generator)
.build());
assert_gt!(maze.len(), 0);
assert_gt!(maze.count(), 0);
}

View File

@ -1,3 +1,4 @@
use claims::assert_some;
use hexlab::prelude::*;
use rstest::rstest;
@ -10,20 +11,20 @@ fn generator_type(
#[case] start_pos: Option<Hex>,
#[case] seed: Option<u64>,
) {
let mut maze = HexMaze::new();
let mut maze = Maze::new();
for q in -3..=3 {
for r in -3..=3 {
let hex = Hex::new(q, r);
if hex.length() <= 3 {
maze.add_tile(hex);
maze.insert(hex);
}
}
}
let initial_size = maze.len();
let initial_size = maze.count();
generator.generate(&mut maze, start_pos, seed);
assert_eq!(maze.len(), initial_size, "Maze size should not change");
assert_eq!(maze.count(), initial_size, "Maze size should not change");
// Check maze connectivity
let start = start_pos.unwrap_or(Hex::ZERO);
@ -36,28 +37,27 @@ fn generator_type(
for dir in EdgeDirection::ALL_DIRECTIONS {
let neighbor = current + dir;
if let Some(walls) = maze.get_walls(&current) {
if !walls.contains(dir) && maze.get_tile(&neighbor).is_some() {
if !walls.contains(dir) && maze.get(&neighbor).is_some() {
to_visit.push(neighbor);
}
}
}
}
assert_eq!(visited.len(), maze.len(), "All tiles should be connected");
assert_eq!(visited.len(), maze.count(), "All tiles should be connected");
// Check that each tile has at least one open wall
for &pos in maze.keys() {
let walls = maze.get_walls(&pos).unwrap();
let walls = assert_some!(maze.get_walls(&pos));
assert!(
walls.count() < 6,
"Tile at {:?} should have at least one open wall",
pos
"Tile at {pos:?} should have at least one open wall",
);
}
}
#[test]
fn test_empty_maze() {
let mut maze = HexMaze::new();
let mut maze = Maze::new();
GeneratorType::RecursiveBacktracking.generate(&mut maze, None, None);
assert!(
maze.is_empty(),

View File

@ -1,68 +1,68 @@
use claims::assert_some;
use hexlab::prelude::*;
#[test]
fn hex_maze_creation_and_basic_operations() {
let mut maze = HexMaze::new();
let mut maze = Maze::new();
assert!(maze.is_empty());
let center = Hex::ZERO;
maze.add_tile(center);
assert_eq!(maze.len(), 1);
maze.insert(center);
assert_eq!(maze.count(), 1);
assert!(!maze.is_empty());
let tile = maze.get_tile(&center);
assert!(tile.is_some());
assert_eq!(tile.unwrap().pos(), center);
let tile = assert_some!(maze.get(&center));
assert_eq!(tile.pos(), center);
}
#[test]
fn hex_maze_wall_operations() {
let mut maze = HexMaze::new();
let mut maze = Maze::new();
let center = Hex::ZERO;
maze.add_tile(center);
maze.insert(center);
// Add walls
for direction in EdgeDirection::ALL_DIRECTIONS {
maze.add_wall(center, direction);
let _ = maze.add_tile_wall(&center, direction);
}
let walls = maze.get_walls(&center).unwrap();
let walls = assert_some!(maze.get_walls(&center));
assert_eq!(walls.count(), 6);
// Remove walls
for direction in EdgeDirection::ALL_DIRECTIONS {
maze.remove_tile_wall(&center, direction);
let _ = maze.remove_tile_wall(&center, direction);
}
let walls = maze.get_walls(&center).unwrap();
let walls = assert_some!(maze.get_walls(&center));
assert_eq!(walls.count(), 0);
}
#[test]
fn hex_maze_multiple_tiles() {
let mut maze = HexMaze::new();
let mut maze = Maze::new();
let tiles = [Hex::ZERO, Hex::new(1, -1), Hex::new(0, 1), Hex::new(-1, 1)];
for &tile in &tiles {
maze.add_tile(tile);
maze.insert(tile);
}
assert_eq!(maze.len(), tiles.len());
assert_eq!(maze.count(), tiles.len());
for &tile in &tiles {
assert!(maze.get_tile(&tile).is_some());
assert!(maze.get(&tile).is_some());
}
}
#[test]
fn hex_maze_edge_cases() {
let mut maze = HexMaze::new();
let mut maze = Maze::new();
let non_existent = Hex::new(10, 10);
// Operations on non-existent tiles should not panic
maze.add_wall(non_existent, EdgeDirection::FLAT_NORTH);
maze.remove_tile_wall(&non_existent, EdgeDirection::FLAT_NORTH);
let _ = maze.add_tile_wall(&non_existent, EdgeDirection::FLAT_NORTH);
let _ = maze.remove_tile_wall(&non_existent, EdgeDirection::FLAT_NORTH);
assert!(maze.get_tile(&non_existent).is_none());
assert!(maze.get(&non_existent).is_none());
assert!(maze.get_walls(&non_existent).is_none());
}

79
tests/pathfinding.rs Normal file
View File

@ -0,0 +1,79 @@
use claims::*;
use hexlab::MazeBuilder;
use hexx::{hex, EdgeDirection, Hex};
#[test]
fn basic_path() {
let maze = assert_ok!(MazeBuilder::new().with_seed(12345).with_radius(5).build());
let start = Hex::new(0, 0);
let goal = Hex::new(2, 0);
assert_some_eq!(
maze.find_path(start, goal),
vec![start, hex(1, 0), hex(1, 1), hex(2, 1), goal]
);
}
#[test]
fn path_with_walls() {
let mut maze = assert_ok!(MazeBuilder::new().with_seed(12345).with_radius(5).build());
let start = Hex::new(0, 0);
let goal = Hex::new(2, 0);
// Block direct path with wall
assert_ok!(maze.add_tile_wall(&start, EdgeDirection::FLAT_SOUTH));
// Should find alternative path or no path
let path = maze.find_path(start, goal);
if let Some(path) = path {
// If path exists, verify it's valid
assert!(path.len() > 3); // Should be longer than direct path
assert_eq!(path.first(), Some(&start));
assert_eq!(path.last(), Some(&goal));
}
}
#[test]
fn path_to_self() {
let maze = assert_ok!(MazeBuilder::new().with_seed(12345).with_radius(5).build());
let pos = Hex::new(0, 0);
assert_some_eq!(maze.find_path(pos, pos), vec![pos]);
}
#[test]
fn no_path_exists() {
let mut maze = assert_ok!(MazeBuilder::new().with_seed(12345).with_radius(5).build());
let start = Hex::new(0, 0);
let goal = Hex::new(2, 0);
// Surround start with walls
for dir in EdgeDirection::ALL_DIRECTIONS {
assert_ok!(maze.add_tile_wall(&start, dir));
}
assert_none!(maze.find_path(start, goal));
}
#[test]
fn path_in_larger_maze() {
let maze = assert_ok!(MazeBuilder::new().with_seed(12345).with_radius(10).build());
let start = Hex::new(-5, -5);
let goal = Hex::new(5, 5);
let path = assert_some!(maze.find_path(start, goal));
// Basic path properties
assert_eq!(path.first(), Some(&start));
assert_eq!(path.last(), Some(&goal));
// Path should be continuous
for window in path.windows(2) {
let current = window[0];
let next = window[1];
assert!(EdgeDirection::ALL_DIRECTIONS
.iter()
.any(|&dir| current.neighbor(dir) == next));
}
}