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 4da153b626 - Show all commits

View file

@ -34,7 +34,7 @@ impl HexPosition {
///
/// assert_eq!(a.distance_to(&b), 2.0);
/// ```
pub fn distance_to(&self, other: &HexPosition) -> f32 {
pub fn distance_to(&self, other: &Self) -> f32 {
// dx = |x1 - x2| and x = q
let dq = self.q - other.q;
@ -61,7 +61,7 @@ impl HexPosition {
/// # Example:
///
/// ```no_run
/// use border_wars::hex::HexPosition;
/// use border_wars::hex::Self;
///
/// let position = HexPosition { q: 0, r: 0 };
///
@ -69,56 +69,56 @@ impl HexPosition {
///
/// assert_eq!(positions.len(), 7);
/// ```
pub fn range(&self, range: i32) -> HashSet<HexPosition> {
pub fn range(&self, range: i32) -> HashSet<Self> {
let mut result_positions = HashSet::new();
for q in (-range)..=range {
for r in (-range).max(-q - range)..=range.min(-q + range) {
result_positions.insert(HexPosition { q, r });
result_positions.insert(Self { q, r });
}
}
result_positions
}
}
impl ops::Add<HexPosition> for HexPosition {
type Output = HexPosition;
impl ops::Add<Self> for HexPosition {
type Output = Self;
fn add(self, other: HexPosition) -> HexPosition {
HexPosition {
fn add(self, other: Self) -> Self::Output {
Self {
q: self.q + other.q,
r: self.r + other.r,
}
}
}
impl ops::AddAssign<HexPosition> for HexPosition {
fn add_assign(&mut self, other: HexPosition) {
impl ops::AddAssign<Self> for HexPosition {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl ops::Sub<HexPosition> for HexPosition {
type Output = HexPosition;
impl ops::Sub<Self> for HexPosition {
type Output = Self;
fn sub(self, other: HexPosition) -> HexPosition {
HexPosition {
fn sub(self, other: Self) -> Self {
Self {
q: self.q - other.q,
r: self.r - other.r,
}
}
CoCo_Sol marked this conversation as resolved Outdated

Don't make a new allocation. Use the += operator

Don't make a new allocation. Use the += operator
}
impl ops::SubAssign<HexPosition> for HexPosition {
fn sub_assign(&mut self, other: HexPosition) {
impl ops::SubAssign<Self> for HexPosition {
fn sub_assign(&mut self, other: Self) {
*self = *self - other;
}
}
impl ops::Mul<i32> for HexPosition {
type Output = HexPosition;
type Output = Self;
fn mul(self, other: i32) -> HexPosition {
HexPosition {
fn mul(self, other: i32) -> Self {
Self {
q: self.q * other,
r: self.r * other,
}
@ -132,10 +132,10 @@ impl ops::MulAssign<i32> for HexPosition {
}
impl ops::Div<i32> for HexPosition {
type Output = HexPosition;
type Output = Self;
fn div(self, other: i32) -> HexPosition {
HexPosition {
fn div(self, other: i32) -> Self {
Self {
q: self.q / other,
r: self.r / other,
}