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