chess/
piece.rs

1use crate::color::Color;
2use std::fmt;
3
4/// Represent a chess piece as a very simple enum
5#[derive(PartialEq, Eq, Ord, PartialOrd, Copy, Clone, Debug, Hash)]
6pub enum Piece {
7    Pawn,
8    Knight,
9    Bishop,
10    Rook,
11    Queen,
12    King,
13}
14
15/// How many piece types are there?
16pub const NUM_PIECES: usize = 6;
17
18/// An array representing each piece type, in order of ascending value.
19pub const ALL_PIECES: [Piece; NUM_PIECES] = [
20    Piece::Pawn,
21    Piece::Knight,
22    Piece::Bishop,
23    Piece::Rook,
24    Piece::Queen,
25    Piece::King,
26];
27
28/// How many ways can I promote?
29pub const NUM_PROMOTION_PIECES: usize = 4;
30
31/// What pieces can I promote to?
32pub const PROMOTION_PIECES: [Piece; 4] = [Piece::Queen, Piece::Knight, Piece::Rook, Piece::Bishop];
33
34impl Piece {
35    /// Convert the `Piece` to a `usize` for table lookups.
36    #[inline]
37    pub fn to_index(&self) -> usize {
38        *self as usize
39    }
40
41    /// Convert a piece with a color to a string.  White pieces are uppercase, black pieces are
42    /// lowercase.
43    ///
44    /// ```
45    /// use chess::{Piece, Color};
46    ///
47    /// assert_eq!(Piece::King.to_string(Color::White), "K");
48    /// assert_eq!(Piece::Knight.to_string(Color::Black), "n");
49    /// ```
50    #[inline]
51    pub fn to_string(&self, color: Color) -> String {
52        let piece = format!("{}", self);
53        if color == Color::White {
54            piece.to_uppercase()
55        } else {
56            piece
57        }
58    }
59}
60
61impl fmt::Display for Piece {
62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63        write!(
64            f,
65            "{}",
66            match *self {
67                Piece::Pawn => "p",
68                Piece::Knight => "n",
69                Piece::Bishop => "b",
70                Piece::Rook => "r",
71                Piece::Queen => "q",
72                Piece::King => "k",
73            }
74        )
75    }
76}