Skip to content

Commit 5e34aae

Browse files
committed
Add Direction type
1 parent 84aaf3c commit 5e34aae

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
use std::fmt::Debug;
2+
3+
use rand::{prelude::Distribution, distributions::Standard};
4+
use serde::{Deserialize, Serialize};
5+
6+
use super::{Delta, Unity, Zero};
7+
8+
/// One of the four cardinal directions.
9+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10+
pub enum Direction {
11+
Up,
12+
Down,
13+
Left,
14+
Right,
15+
}
16+
17+
impl<T> TryFrom<Delta<T>> for Direction where T: Zero + Unity + PartialEq + Debug {
18+
type Error = String;
19+
20+
fn try_from(delta: Delta<T>) -> Result<Self, Self::Error> {
21+
if delta == Delta::UP {
22+
Ok(Direction::Up)
23+
} else if delta == Delta::DOWN {
24+
Ok(Direction::Down)
25+
} else if delta == Delta::LEFT {
26+
Ok(Direction::Left)
27+
} else if delta == Delta::RIGHT {
28+
Ok(Direction::Right)
29+
} else {
30+
Err(format!("Not a direction: {:?}", delta))
31+
}
32+
}
33+
}
34+
35+
impl<T> From<Direction> for Delta<T> where T: Zero + Unity {
36+
fn from(direction: Direction) -> Self {
37+
match direction {
38+
Direction::Up => Delta::UP,
39+
Direction::Down => Delta::DOWN,
40+
Direction::Left => Delta::LEFT,
41+
Direction::Right => Delta::RIGHT,
42+
}
43+
}
44+
}
45+
46+
impl Distribution<Direction> for Standard {
47+
fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Direction {
48+
match rng.gen_range(0..4) {
49+
0 => Direction::Up,
50+
1 => Direction::Down,
51+
2 => Direction::Left,
52+
3 => Direction::Right,
53+
_ => unreachable!(),
54+
}
55+
}
56+
}

lighthouse-protocol/src/utils/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod color;
2+
mod direction;
23
mod rect;
34
mod rem_euclid;
45
mod rotation;
@@ -7,6 +8,7 @@ mod vec2;
78
mod zero;
89

910
pub use color::*;
11+
pub use direction::*;
1012
pub use rect::*;
1113
pub use rem_euclid::*;
1214
pub use rotation::*;

0 commit comments

Comments
 (0)