Add utils for hexagonal grild #50

Merged
tipragot merged 23 commits from hex-utils into main 2024-02-14 17:49:08 +00:00
Showing only changes of commit 1f0083bba8 - Show all commits

View file

@ -1,10 +1,10 @@
//! All fonction related to calculations in hexagonal grid.
//! All functions related to calculations in a hexagonal grid.
use std::collections::HashSet;
use std::ops;
/// Hexagonal position (in a hexagonal grid).
/// We are using the axial coordinate system explained in this
/// Represents a position in a hexagonal grid.
/// We use the axial coordinate system explained in this
/// [documentation](https://www.redblobgames.com/grids/hexagons/#coordinates).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct HexPosition {
@ -16,19 +16,20 @@ pub struct HexPosition {
}
impl HexPosition {
/// Returns the distance between two [HexPosition]
/// Returns the distance between two [HexPosition]s.
///
/// # How does it work ?
/// # How it works
///
/// Hexagonal grid using the
/// In the hexagonal grid, using the
/// [cube coordinate system](https://www.redblobgames.com/grids/hexagons/#coordinates),
/// is like a cube in 2D space.
/// The Manhattan distance between two positions is equal to: the half of
/// the sum of abs(dx) + abs(dy) + abs(dz)
/// it's akin to a cube in 3D space.
/// The Manhattan distance between two positions is equal to half of
/// the sum of abs(dx) + abs(dy) + abs(dz).
/// However, in hexagonal grids, z is defined as -q - r.
///
/// # Example:
/// # Example
///
/// ```no_run
/// ```
/// use border_wars::hex::HexPosition;
///
/// let a = HexPosition { q: 0, r: 0 };
@ -37,32 +38,31 @@ impl HexPosition {
/// assert_eq!(a.distance_to(&b), 2.0);
/// ```
pub fn distance_to(&self, other: &Self) -> f32 {
// dx = |x1 - x2| and x = q
// dx = |x1 - x2| where x = q
let dq = self.q - other.q;
// dy = |y1 - y2| and y = r
// dy = |y1 - y2| where y = r
let dr = self.r - other.r;
// dz = |z1 - z2| and z = -q - r
let ds = self.q + self.r - other.q - other.r;
// dz = |z1 - z2| where z = -q - r
let dz = self.q + self.r - other.q - other.r;
// Manhattan distance = (abs(dq) + abs(dr) + abs(ds)) / 2
(dq.abs() + dr.abs() + ds.abs()) as f32 / 2.
(dq.abs() + dr.abs() + dz.abs()) as f32 / 2.0
}
/// Returns all positions within a given `range` from the current
/// HexPosition.
/// `HexPosition`.
///
/// This function iterates over the possible q and r values within the
/// specified range and inserts HexPositions into a HashSet, ensuring
/// that each generated position is within the given range from the
/// current position.
/// specified range.
/// Note that the original position is also returned.
///
/// for more details: https://www.redblobgames.com/grids/hexagons/#range
/// For more details, refer to: https://www.redblobgames.com/grids/hexagons/#range
///
/// # Example:
/// # Example
///
/// ```no_run
/// ```
/// use border_wars::hex::HexPosition;
///
/// let position = HexPosition { q: 0, r: 0 };