Add exemple
Some checks failed
Rust Checks / checks (push) Failing after 19s
Rust Checks / checks (pull_request) Failing after 4s

This commit is contained in:
CoCo_Sol 2024-02-14 10:44:17 +01:00
parent 23d839ea34
commit 471f516150

View file

@ -22,6 +22,17 @@ impl HexPosition {
/// Hexagonal grid using the [cube](https://www.redblobgames.com/grids/hexagons/#coordinates) coordinate system, /// Hexagonal grid using the [cube](https://www.redblobgames.com/grids/hexagons/#coordinates) coordinate system,
/// is like a cube in 2D space. /// 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) /// The Manhattan distance between two positions is equal to: the half of the sum of abs(dx) + abs(dy) + abs(dz)
///
/// # Example:
///
/// ```no_run
/// use border_wars::hex::HexPosition;
///
/// let a = HexPosition { q: 0, r: 0 };
/// let b = HexPosition { q: 1, r: 1 };
///
/// assert_eq!(a.distance_to(&b), 2.0);
/// ```
pub fn distance_to(&self, other: &HexPosition) -> f32 { pub fn distance_to(&self, other: &HexPosition) -> f32 {
// dx = |x1 - x2| and x = q // dx = |x1 - x2| and x = q
let dq = self.q - other.q; let dq = self.q - other.q;
@ -36,7 +47,25 @@ impl HexPosition {
(dq.abs() + dr.abs() + ds.abs()) as f32 / 2. (dq.abs() + dr.abs() + ds.abs()) as f32 / 2.
} }
/// Returns all positions in a given `range`. /// Returns all positions within a given `range` from the current 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.
///
/// for more details: https://www.redblobgames.com/grids/hexagons/#range
///
/// # Example:
///
/// ```no_run
/// use border_wars::hex::HexPosition;
///
/// let position = HexPosition { q: 0, r: 0 };
///
/// let positions = position.range(1);
///
/// assert_eq!(positions.len(), 7);
/// ```
pub fn range(&self, range: i32) -> HashSet<HexPosition> { pub fn range(&self, range: i32) -> HashSet<HexPosition> {
let mut result_positions = HashSet::new(); let mut result_positions = HashSet::new();
for q in (-range)..=range { for q in (-range)..=range {
@ -46,6 +75,7 @@ impl HexPosition {
} }
result_positions result_positions
} }
} }
impl ops::Add<HexPosition> for HexPosition { impl ops::Add<HexPosition> for HexPosition {