From 23d839ea3415e9846598448d74f21df99be0c4b0 Mon Sep 17 00:00:00 2001 From: CoCoSol007 Date: Wed, 14 Feb 2024 01:52:23 +0100 Subject: [PATCH] WIP: Add docs --- crates/border-wars/src/hex.rs | 57 ++++++++++++++++------------------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/crates/border-wars/src/hex.rs b/crates/border-wars/src/hex.rs index 79969ad..c91027e 100644 --- a/crates/border-wars/src/hex.rs +++ b/crates/border-wars/src/hex.rs @@ -1,28 +1,10 @@ -//! This file contains utilities for working with hex coordinates. +//! All fonction related to calculations in hexagonal grid. use std::collections::HashSet; use std::ops; -/// Contains all "HexPosition" neighbors of "HexPosition" -pub struct GroupHexPosition(pub HashSet); - -impl GroupHexPosition { - /// TODO - pub fn new(hexes: HashSet) -> Self { - GroupHexPosition(hexes) - } - - /// Removes the origin (`HexPosition { q: 0, r: 0 }`) of a - /// "GroupHexPosition" - pub fn remove_origin(&mut self) -> &mut Self { - self.0.remove(&HexPosition { q: 0, r: 0 }); - self - } -} - -/// Hex position (in a hexagonal grid). -/// -/// usnig this doc : https://www.redblobgames.com/grids/hexagons/ +/// Hexagonal position (in a hexagonal grid). +/// We are using 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 { /// Q coordinate @@ -33,23 +15,36 @@ pub struct HexPosition { } impl HexPosition { - /// Returns the distance between two "HexPosition" + /// Returns the distance between two [HexPosition] + /// + /// # How does it work ? + /// + /// Hexagonal grid using the [cube](https://www.redblobgames.com/grids/hexagons/#coordinates) coordinate system, + /// 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) pub fn distance_to(&self, other: &HexPosition) -> f32 { - ((self.q - other.q).abs() - + (self.r - other.r).abs() - + (self.q + self.r - other.q - other.r).abs()) as f32 - / 2. + // dx = |x1 - x2| and x = q + let dq = self.q - other.q; + + // dy = |y1 - y2| and 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; + + // Manhattan distance = (abs(dq) + abs(dr) + abs(ds)) / 2 + (dq.abs() + dr.abs() + ds.abs()) as f32 / 2. } - /// Returns all positions in a given range - pub fn range(&self, range: i32) -> GroupHexPosition { - let mut positions = HashSet::new(); + /// Returns all positions in a given `range`. + pub fn range(&self, range: i32) -> HashSet { + let mut result_positions = HashSet::new(); for q in (-range)..=range { for r in (-range).max(-q - range)..=range.min(-q + range) { - positions.insert(HexPosition { q, r }); + result_positions.insert(HexPosition { q, r }); } } - GroupHexPosition(positions) + result_positions } }