1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
//! A library for hexmap operations.
use std::ops::{Add, Sub};


/// A hex coordinate using a cubic coordinate scheme.
///
/// See http://www.redblobgames.com/grids/hexagons/#coordinates for more detail.
///
/// All three coordinates must sum to zero.
#[derive(Debug,PartialEq,PartialOrd,Clone,Copy)]
pub struct Coordinate {
    x: i64,
    y: i64,
    z: i64,
}

impl Coordinate {
    /// Create a new Coordinate at 0, 0, 0.
    ///
    /// This returns a `Result` to match `at`, but always succeeds.
    pub fn new() -> Result<Self, &'static str> {
        Ok(Coordinate { x: 0, y: 0, z: 0 })
    }

    /// Create a new Coordinate at the specified location, if that location is
    /// valid.
    pub fn at(x: i64, y: i64, z: i64) -> Result<Self, &'static str> {
        if x + y + z == 0 {
            Ok(Coordinate { x: x, y: y, z: z })
        } else {
            Err("Invalid cubic coordinates")
        }
    }

    /// Get the six neighbors of a given Coordinate.
    pub fn neighbors(&self) -> Vec<Coordinate> {
        vec![
            Coordinate::at(self.x + 1, self.y, self.z - 1).unwrap(),
            Coordinate::at(self.x + 1, self.y - 1, self.z).unwrap(),
            Coordinate::at(self.x, self.y - 1, self.z + 1).unwrap(),
            Coordinate::at(self.x, self.y + 1, self.z - 1).unwrap(),
            Coordinate::at(self.x - 1, self.y, self.z + 1).unwrap(),
            Coordinate::at(self.x - 1, self.y + 1, self.z).unwrap(),
        ]
    }

    /// Get the neighbor in `direction`. Valid directions are in [0, 5].
    pub fn neighbor(&self, direction: usize) -> Result<Coordinate, &'static str> {
        let neighbors = self.neighbors();
        match neighbors.get(direction) {
            Some(val) => Ok(val.to_owned()),
            None => Err("Invalid direction"),
        }
    }

    /// Get the distance between two coordinates, in grid tiles.
    pub fn distance_to(&self, other: Coordinate) -> i64 {
        (
            (self.x - other.x).abs()
            + (self.y - other.y).abs()
            + (self.z - other.z).abs()
        ) / 2
    }
}

impl Add for Coordinate {
    type Output = Coordinate;

    fn add(self, other: Coordinate) -> Coordinate {
        Coordinate {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z,
        }
    }
}

impl Sub for Coordinate {
    type Output = Coordinate;

    fn sub(self, other: Coordinate) -> Coordinate {
        Coordinate {
            x: self.x - other.x,
            y: self.y - other.y,
            z: self.z - other.z,
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_makes_a_new_one() {
        let coord = Coordinate::new().unwrap();
        assert_eq!(coord.x, 0);
        assert_eq!(coord.y, 0);
        assert_eq!(coord.z, 0);
    }

    #[test]
    fn it_accepts_args_in_constructor() {
        let coord = Coordinate::at(-3, -1, 4).unwrap();
        assert_eq!(coord.x, -3);
        assert_eq!(coord.y, -1);
        assert_eq!(coord.z, 4);
    }

    #[test]
    fn it_rejects_invalid_cube_coordinates() {
        let coord = Coordinate::at(3, 1, 4);
        assert!(coord.is_err());
    }

    #[test]
    fn it_generates_a_list_of_neighbors() {
        let coord = Coordinate::new().unwrap();
        let expected = vec![
            Coordinate::at(1, 0, -1).unwrap(),
            Coordinate::at(1, -1, 0).unwrap(),
            Coordinate::at(0, -1, 1).unwrap(),
            Coordinate::at(0, 1, -1).unwrap(),
            Coordinate::at(-1, 0, 1).unwrap(),
            Coordinate::at(-1, 1, 0).unwrap(),
        ];
        assert_eq!(coord.neighbors(), expected);
    }

    #[test]
    fn it_calcuates_distances() {
        let coord_a = Coordinate::at(-3, -1, 4).unwrap();
        let coord_b = Coordinate::at(2, 7, -9).unwrap();
        assert_eq!(coord_a.distance_to(coord_b), 13);
    }

    #[test]
    fn it_supports_addition() {
        let coord_a = Coordinate::at(-3, -1, 4).unwrap();
        let coord_b = Coordinate::at(2, 7, -9).unwrap();
        let expected = Coordinate::at(-1, 6, -5).unwrap();
        assert_eq!(coord_a + coord_b, expected);
    }

    #[test]
    fn it_supports_subtraction() {
        let coord_a = Coordinate::at(-3, -1, 4).unwrap();
        let coord_b = Coordinate::at(2, 7, -9).unwrap();
        let expected = Coordinate::at(-5, -8, 13).unwrap();
        assert_eq!(coord_a - coord_b, expected);
    }

    #[test]
    fn it_produces_neighbors_given_a_direction() {
        let coord = Coordinate::at(-3, -1, 4).unwrap();
        let expected = Ok(Coordinate::at(-2, -1, 3).unwrap());
        assert_eq!(coord.neighbor(0), expected);
    }

    #[test]
    fn it_produces_no_neighbors_given_a_bad_direction() {
        let coord = Coordinate::at(-3, -1, 4).unwrap();
        let expected = Err("Invalid direction");
        assert_eq!(coord.neighbor(6), expected);
    }
}