hive/engine/grid/coordinate/
hex.rs1use std::fmt::{Display, Formatter, Result};
2
3use crate::engine::grid::coordinate::cube::Cube;
4
5#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy, Ord, PartialOrd)]
6pub struct Hex {
7 pub q: i64,
8 pub r: i64,
9}
10
11impl Hex {
12 pub fn new(q: i64, r: i64) -> Hex {
13 Hex { q, r }
14 }
15
16 pub fn zero() -> Hex {
17 Hex { q: 0, r: 0 }
18 }
19
20 pub fn neighbors(&self) -> Vec<Hex> {
21 let q = self.q;
22 let r = self.r;
23
24 let neighbors: Vec<Hex> = vec![
25 Hex::new(q + 1, r - 1),
26 Hex::new(q + 1, r),
27 Hex::new(q, r + 1),
28 Hex::new(q - 1, r + 1),
29 Hex::new(q - 1, r),
30 Hex::new(q, r - 1),
31 ];
32
33 neighbors
34 }
35}
36
37impl From<Cube> for Hex {
38 fn from(cube: Cube) -> Self {
39 Hex {
40 q: cube.x,
41 r: cube.z,
42 }
43 }
44}
45
46impl Display for Hex {
47 fn fmt(&self, f: &mut Formatter) -> Result {
48 let mut str: String = self.q.to_string() + "," + self.r.to_string().as_str();
49
50 if str.len() <= 6 {
51 for i in str.len()..8 {
52 if i % 2 == 1 {
53 str = " ".to_owned() + &str;
54 } else {
55 str += " ";
56 }
57 }
58 write!(f, "{}", str)
59 } else {
60 write!(f, " ?,? ")
61 }
62 }
63}