chess/
color.rs

1use crate::rank::Rank;
2use std::ops::Not;
3
4/// Represent a color.
5#[derive(PartialOrd, PartialEq, Eq, Copy, Clone, Debug, Hash)]
6pub enum Color {
7    White,
8    Black,
9}
10
11/// How many colors are there?
12pub const NUM_COLORS: usize = 2;
13/// List all colors
14pub const ALL_COLORS: [Color; NUM_COLORS] = [Color::White, Color::Black];
15
16impl Color {
17    /// Convert the `Color` to a `usize` for table lookups.
18    #[inline]
19    pub fn to_index(&self) -> usize {
20        *self as usize
21    }
22
23    /// Convert a `Color` to my backrank, which represents the starting rank
24    /// for my pieces.
25    #[inline]
26    pub fn to_my_backrank(&self) -> Rank {
27        match *self {
28            Color::White => Rank::First,
29            Color::Black => Rank::Eighth,
30        }
31    }
32
33    /// Convert a `Color` to my opponents backrank, which represents the starting rank for the
34    /// opponents pieces.
35    #[inline]
36    pub fn to_their_backrank(&self) -> Rank {
37        match *self {
38            Color::White => Rank::Eighth,
39            Color::Black => Rank::First,
40        }
41    }
42
43    /// Convert a `Color` to my second rank, which represents the starting rank for my pawns.
44    #[inline]
45    pub fn to_second_rank(&self) -> Rank {
46        match *self {
47            Color::White => Rank::Second,
48            Color::Black => Rank::Seventh,
49        }
50    }
51
52    /// Convert a `Color` to my fourth rank, which represents the rank of my pawns when
53    /// moving two squares forward.
54    #[inline]
55    pub fn to_fourth_rank(&self) -> Rank {
56        match *self {
57            Color::White => Rank::Fourth,
58            Color::Black => Rank::Fifth,
59        }
60    }
61
62    /// Convert a `Color` to my seventh rank, which represents the rank before pawn promotion.
63    #[inline]
64    pub fn to_seventh_rank(&self) -> Rank {
65        match *self {
66            Color::White => Rank::Seventh,
67            Color::Black => Rank::Second,
68        }
69    }
70}
71
72impl Not for Color {
73    type Output = Color;
74
75    /// Get the other color.
76    #[inline]
77    fn not(self) -> Color {
78        if self == Color::White {
79            Color::Black
80        } else {
81            Color::White
82        }
83    }
84}