chess/
direction.rs

1/// Describe 8 directions.
2#[derive(Copy, Clone, PartialEq, Eq, Debug)]
3pub enum Direction {
4    Up,
5    UpRight,
6    Right,
7    DownRight,
8    Down,
9    DownLeft,
10    Left,
11    UpLeft,
12}
13
14/// Numbers of line (vertical and horizontal).
15pub const NUM_LINES: usize = 4;
16
17/// Enumerate All [`Direction`] in line (vertical and horizontal).
18pub const ALL_LINE: [Direction; NUM_LINES] = [
19    Direction::Up,
20    Direction::Right,
21    Direction::Down,
22    Direction::Left,
23];
24
25/// Numbers of diagonal.
26pub const NUM_DIAGONAL: usize = 4;
27
28/// Enumerate all [`Direction`] in diagonal.
29pub const ALL_DIAGONAL: [Direction; NUM_DIAGONAL] = [
30    Direction::UpRight,
31    Direction::DownRight,
32    Direction::DownLeft,
33    Direction::UpLeft,
34];
35
36/// Numbers of [`Direction`].
37pub const NUM_DIRECTION: usize = NUM_LINES + NUM_DIAGONAL;
38
39/// Enumerate all [`Direction`].
40pub const ALL_DIRECTION: [Direction; NUM_DIRECTION] = [
41    Direction::Up,
42    Direction::UpRight,
43    Direction::Right,
44    Direction::DownRight,
45    Direction::Down,
46    Direction::DownLeft,
47    Direction::Left,
48    Direction::UpLeft,
49];
50
51impl Direction {
52    /// Verify if a direction is contain in another.
53    ///
54    /// # Examples
55    ///
56    /// ```
57    /// use chess::Direction;
58    ///
59    /// assert_eq!(Direction::Up.has(Direction::Up), true);
60    /// assert_eq!(Direction::Up.has(Direction::Right), false);
61    /// assert_eq!(Direction::UpRight.has(Direction::Up), true);
62    /// assert_eq!(Direction::UpRight.has(Direction::Right), true);
63    /// // but it's not symmetric
64    /// assert_eq!(Direction::Up.has(Direction::UpRight), false);
65    /// ```
66    pub fn has(&self, direction: Direction) -> bool {
67        if *self == direction {
68            return true;
69        }
70        match *self {
71            Direction::UpRight => matches!(direction, Direction::Up | Direction::Right),
72            Direction::DownRight => matches!(direction, Direction::Down | Direction::Right),
73            Direction::DownLeft => matches!(direction, Direction::Down | Direction::Left),
74            Direction::UpLeft => matches!(direction, Direction::Up | Direction::Left),
75            _ => false,
76        }
77    }
78}