dzura/game/src/util/hex.rs
2024-08-17 19:08:02 -07:00

69 lines
1.4 KiB
Rust

const ROWS :[u8; 10] = [ 0, 5, 11, 18, 26, 35, 43, 50, 56, 61 ];
pub struct Hex {
x:u8,
y:u8,
tile:u8,
}
impl Hex {
pub fn new() -> Self
{
Self {
x:0,
y:0,
tile:0,
}
}
pub fn from_hex(x:u8, y:u8) -> Self
{
let x = x as i32;
let y = y as i32;
let a = ((x + 4) * (x + 5) / 2) - 10;
let b = (x > 4) as i32 * ((x - 4) + ((x - 5) * (x - 4)));
let tile = a - b + y;
Self {
x:x as u8,
y:y as u8,
tile:tile as u8,
}
}
pub fn from_tile(tile:u8) -> Self
{
let mut x = 0;
while tile >= ROWS[x as usize + 1] { x += 1; }
let y = tile - ROWS[x as usize] + ((x > 4) as u8 * (x - 4));
Self {
x,
y,
tile,
}
}
pub fn is_valid(x:i8, y:i8) -> bool
{
const COLUMNS :[(i8, i8); 9] = [
(0, 4),
(0, 5),
(0, 6),
(0, 7),
(0, 8),
(1, 8),
(2, 8),
(3, 8),
(4, 8),
];
let valid = x >= 0 && x < 9;
if valid {
let (min, max) = COLUMNS[x as usize];
y >= min && y <= max
} else { false }
}
pub fn x(&self) -> u8 { self.x }
pub fn y(&self) -> u8 { self.y }
pub fn tile(&self) -> u8 { self.tile }
}