Skip to main content

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] = [Piece::Pawn, Piece::Knight, Piece::Bishop, Piece::Rook, Piece::Queen, Piece::King];
20
21/// How many ways can I promote?
22pub const NUM_PROMOTION_PIECES: usize = 4;
23
24/// What pieces can I promote to?
25pub const PROMOTION_PIECES: [Piece; 4] = [Piece::Queen, Piece::Knight, Piece::Rook, Piece::Bishop];
26
27impl Piece {
28	/// Convert the `Piece` to a `usize` for table lookups.
29	#[inline]
30	pub fn to_index(self) -> usize {
31		self as usize
32	}
33
34	/// Convert a piece with a color to a string.  White pieces are uppercase, black pieces are
35	/// lowercase.
36	///
37	/// ```
38	/// use chess::{Piece, Color};
39	///
40	/// assert_eq!(Piece::King.to_string(Color::White), "K");
41	/// assert_eq!(Piece::Knight.to_string(Color::Black), "n");
42	/// ```
43	#[inline]
44	pub fn to_string(self, color: Color) -> String {
45		let piece = format!("{}", self);
46		if color == Color::White { piece.to_uppercase() } else { piece }
47	}
48}
49
50impl fmt::Display for Piece {
51	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52		write!(
53			f,
54			"{}",
55			match *self {
56				Piece::Pawn => "p",
57				Piece::Knight => "n",
58				Piece::Bishop => "b",
59				Piece::Rook => "r",
60				Piece::Queen => "q",
61				Piece::King => "k",
62			}
63		)
64	}
65}