eschac
This commit is contained in:
commit
faccfbc1c5
16 changed files with 5154 additions and 0 deletions
134
src/array_vec.rs
Normal file
134
src/array_vec.rs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
use std::iter::ExactSizeIterator;
|
||||
use std::iter::FusedIterator;
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ArrayVec<T: Copy, const N: usize> {
|
||||
len: usize,
|
||||
array: [MaybeUninit<T>; N],
|
||||
}
|
||||
impl<T: Copy, const N: usize> ArrayVec<T, N> {
|
||||
#[inline]
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
len: 0,
|
||||
array: [const { MaybeUninit::uninit() }; N],
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) unsafe fn push_unchecked(&mut self, m: T) {
|
||||
debug_assert!(self.len < N);
|
||||
unsafe {
|
||||
self.array.get_unchecked_mut(self.len).write(m);
|
||||
self.len = self.len.unchecked_add(1);
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn get(&self, index: usize) -> Option<&T> {
|
||||
if index < self.len {
|
||||
Some(unsafe { self.array.as_slice().get_unchecked(index).assume_init_ref() })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn as_slice_mut(&mut self) -> &mut [T] {
|
||||
unsafe { std::mem::transmute::<_, &mut [T]>(self.array.get_unchecked_mut(0..self.len)) }
|
||||
}
|
||||
}
|
||||
impl<'l, T: Copy, const N: usize> IntoIterator for &'l ArrayVec<T, N> {
|
||||
type Item = T;
|
||||
type IntoIter = ArrayVecIter<'l, T, N>;
|
||||
#[inline]
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
ArrayVecIter {
|
||||
array: self,
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) struct ArrayVecIter<'l, T: Copy, const N: usize> {
|
||||
array: &'l ArrayVec<T, N>,
|
||||
index: usize,
|
||||
}
|
||||
impl<'l, T: Copy, const N: usize> Iterator for ArrayVecIter<'l, T, N> {
|
||||
type Item = T;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.index < self.array.len {
|
||||
unsafe {
|
||||
let item = self
|
||||
.array
|
||||
.array
|
||||
.get_unchecked(self.index)
|
||||
.assume_init_read();
|
||||
self.index = self.index.unchecked_add(1);
|
||||
Some(item)
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len();
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
impl<'l, T: Copy, const N: usize> FusedIterator for ArrayVecIter<'l, T, N> {}
|
||||
impl<'l, T: Copy, const N: usize> ExactSizeIterator for ArrayVecIter<'l, T, N> {
|
||||
#[inline]
|
||||
fn len(&self) -> usize {
|
||||
unsafe { self.array.len().unchecked_sub(self.index) }
|
||||
}
|
||||
}
|
||||
impl<T: Copy, const N: usize> IntoIterator for ArrayVec<T, N> {
|
||||
type Item = T;
|
||||
type IntoIter = ArrayVecIntoIter<T, N>;
|
||||
#[inline]
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
ArrayVecIntoIter {
|
||||
array: self,
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) struct ArrayVecIntoIter<T: Copy, const N: usize> {
|
||||
array: ArrayVec<T, N>,
|
||||
index: usize,
|
||||
}
|
||||
impl<T: Copy, const N: usize> Iterator for ArrayVecIntoIter<T, N> {
|
||||
type Item = T;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.index < self.array.len {
|
||||
unsafe {
|
||||
let item = self
|
||||
.array
|
||||
.array
|
||||
.get_unchecked(self.index)
|
||||
.assume_init_read();
|
||||
self.index = self.index.unchecked_add(1);
|
||||
Some(item)
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len();
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
impl<T: Copy, const N: usize> FusedIterator for ArrayVecIntoIter<T, N> {}
|
||||
impl<T: Copy, const N: usize> ExactSizeIterator for ArrayVecIntoIter<T, N> {
|
||||
#[inline]
|
||||
fn len(&self) -> usize {
|
||||
unsafe { self.array.len().unchecked_sub(self.index) }
|
||||
}
|
||||
}
|
||||
177
src/bitboard.rs
Normal file
177
src/bitboard.rs
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
use crate::board::*;
|
||||
|
||||
use std::iter::ExactSizeIterator;
|
||||
use std::iter::FusedIterator;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Bitboard(pub(crate) u64);
|
||||
|
||||
impl Bitboard {
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn first(&self) -> Option<Square> {
|
||||
let mask = self.0;
|
||||
match mask {
|
||||
0 => None,
|
||||
_ => Some(unsafe { Square::transmute(mask.trailing_zeros() as u8) }),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn pop(&mut self) -> Option<Square> {
|
||||
let Self(ref mut mask) = self;
|
||||
let square = match mask {
|
||||
0 => None,
|
||||
_ => Some(unsafe { Square::transmute(mask.trailing_zeros() as u8) }),
|
||||
};
|
||||
*mask &= mask.wrapping_sub(1);
|
||||
square
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn insert(&mut self, square: Square) {
|
||||
self.0 |= 1 << square as u8;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn trans(&self, direction: Direction) -> Self {
|
||||
match direction {
|
||||
Direction::North => Self(self.0 << 8),
|
||||
Direction::NorthEast => Self(self.0 << 9) & !File::A.bitboard(),
|
||||
Direction::East => Self(self.0 << 1) & !File::A.bitboard(),
|
||||
Direction::SouthEast => Self(self.0 >> 7) & !File::A.bitboard(),
|
||||
Direction::South => Self(self.0 >> 8),
|
||||
Direction::SouthWest => Self(self.0 >> 9) & !File::H.bitboard(),
|
||||
Direction::West => Self(self.0 >> 1) & !File::H.bitboard(),
|
||||
Direction::NorthWest => Self(self.0 << 7) & !File::H.bitboard(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn contains(&self, square: Square) -> bool {
|
||||
self.0 & (1 << square as u8) != 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn mirror(self) -> Bitboard {
|
||||
let [a, b, c, d, e, f, g, h] = self.0.to_le_bytes();
|
||||
Self(u64::from_le_bytes([h, g, f, e, d, c, b, a]))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::BitOr for Bitboard {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn bitor(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 | rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::BitAnd for Bitboard {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn bitand(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 & rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::BitXor for Bitboard {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn bitxor(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 ^ rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::BitOrAssign for Bitboard {
|
||||
#[inline]
|
||||
fn bitor_assign(&mut self, rhs: Self) {
|
||||
self.0 |= rhs.0;
|
||||
}
|
||||
}
|
||||
impl std::ops::BitAndAssign for Bitboard {
|
||||
#[inline]
|
||||
fn bitand_assign(&mut self, rhs: Self) {
|
||||
self.0 &= rhs.0;
|
||||
}
|
||||
}
|
||||
impl std::ops::BitXorAssign for Bitboard {
|
||||
#[inline]
|
||||
fn bitxor_assign(&mut self, rhs: Self) {
|
||||
self.0 ^= rhs.0;
|
||||
}
|
||||
}
|
||||
impl std::ops::Not for Bitboard {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn not(self) -> Self::Output {
|
||||
Self(!self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for Bitboard {
|
||||
type Item = Square;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.pop()
|
||||
}
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len();
|
||||
(len, Some(len))
|
||||
}
|
||||
#[inline]
|
||||
fn for_each<F>(self, mut f: F)
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(Self::Item),
|
||||
{
|
||||
let mut mask = self.0;
|
||||
while mask != 0 {
|
||||
f(unsafe { Square::transmute(mask.trailing_zeros() as u8) });
|
||||
mask &= mask.wrapping_sub(1);
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn fold<B, F>(self, init: B, mut f: F) -> B
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(B, Self::Item) -> B,
|
||||
{
|
||||
let mut mask = self.0;
|
||||
let mut acc = init;
|
||||
while mask != 0 {
|
||||
acc = f(acc, unsafe {
|
||||
Square::transmute(mask.trailing_zeros() as u8)
|
||||
});
|
||||
mask &= mask.wrapping_sub(1);
|
||||
}
|
||||
acc
|
||||
}
|
||||
}
|
||||
impl FusedIterator for Bitboard {}
|
||||
impl ExactSizeIterator for Bitboard {
|
||||
#[inline]
|
||||
fn len(&self) -> usize {
|
||||
self.0.count_ones() as usize
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait BitboardIterExt {
|
||||
fn reduce_or(self) -> Bitboard;
|
||||
}
|
||||
impl<T> BitboardIterExt for T
|
||||
where
|
||||
T: Iterator<Item = Bitboard>,
|
||||
{
|
||||
#[inline]
|
||||
fn reduce_or(self) -> Bitboard {
|
||||
self.fold(Bitboard(0), |a, b| a | b)
|
||||
}
|
||||
}
|
||||
676
src/board.rs
Normal file
676
src/board.rs
Normal file
|
|
@ -0,0 +1,676 @@
|
|||
//! Chessboard vocabulary.
|
||||
|
||||
use crate::bitboard::*;
|
||||
|
||||
macro_rules! container {
|
||||
($a:ident, $b:ident, $n:literal) => {
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) struct $b<T>(pub(crate) [T; $n]);
|
||||
#[allow(unused)]
|
||||
impl<T> $b<T> {
|
||||
#[inline]
|
||||
pub fn new<F>(f: F) -> Self
|
||||
where
|
||||
F: FnMut($a) -> T,
|
||||
{
|
||||
Self($a::all().map(f))
|
||||
}
|
||||
#[inline]
|
||||
pub fn get(&self, k: $a) -> &T {
|
||||
unsafe { self.0.get_unchecked(k as usize) }
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_mut(&mut self, k: $a) -> &mut T {
|
||||
unsafe { self.0.get_unchecked_mut(k as usize) }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// The players.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum Color {
|
||||
White,
|
||||
Black,
|
||||
}
|
||||
|
||||
container!(Color, ByColor, 2);
|
||||
|
||||
impl Color {
|
||||
#[inline]
|
||||
pub fn all() -> [Self; 2] {
|
||||
[Self::White, Self::Black]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn home_rank(self) -> Rank {
|
||||
match self {
|
||||
Self::White => Rank::First,
|
||||
Self::Black => Rank::Eighth,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn promotion_rank(self) -> Rank {
|
||||
match self {
|
||||
Self::White => Rank::Eighth,
|
||||
Self::Black => Rank::First,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn forward(self) -> Direction {
|
||||
match self {
|
||||
Self::White => Direction::North,
|
||||
Self::Black => Direction::South,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Not for Color {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn not(self) -> Self::Output {
|
||||
match self {
|
||||
Self::Black => Self::White,
|
||||
Self::White => Self::Black,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of the board.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum File {
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
}
|
||||
|
||||
container!(File, ByFile, 8);
|
||||
|
||||
impl File {
|
||||
#[inline]
|
||||
pub fn all() -> [Self; 8] {
|
||||
[
|
||||
Self::A,
|
||||
Self::B,
|
||||
Self::C,
|
||||
Self::D,
|
||||
Self::E,
|
||||
Self::F,
|
||||
Self::G,
|
||||
Self::H,
|
||||
]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_char(self) -> char {
|
||||
self.to_ascii() as char
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_char(c: char) -> Option<Self> {
|
||||
Self::from_ascii(c as u8)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn to_ascii(self) -> u8 {
|
||||
self as u8 + b'a'
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_ascii(c: u8) -> Option<Self> {
|
||||
(c <= b'h')
|
||||
.then(|| c.checked_sub(b'a').map(|i| unsafe { Self::transmute(i) }))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn bitboard(self) -> Bitboard {
|
||||
Bitboard(0x0101010101010101 << (self as u8))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) unsafe fn transmute(value: u8) -> Self {
|
||||
debug_assert!(value < 8);
|
||||
std::mem::transmute(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for File {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "{}", self.to_char())
|
||||
}
|
||||
}
|
||||
|
||||
/// A row of the board.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum Rank {
|
||||
First,
|
||||
Second,
|
||||
Third,
|
||||
Fourth,
|
||||
Fifth,
|
||||
Sixth,
|
||||
Seventh,
|
||||
Eighth,
|
||||
}
|
||||
|
||||
container!(Rank, ByRank, 8);
|
||||
|
||||
impl Rank {
|
||||
#[inline]
|
||||
pub fn all() -> [Self; 8] {
|
||||
[
|
||||
Self::First,
|
||||
Self::Second,
|
||||
Self::Third,
|
||||
Self::Fourth,
|
||||
Self::Fifth,
|
||||
Self::Sixth,
|
||||
Self::Seventh,
|
||||
Self::Eighth,
|
||||
]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_char(self) -> char {
|
||||
self.to_ascii() as char
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_char(c: char) -> Option<Self> {
|
||||
Self::from_ascii(c as u8)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn mirror(self) -> Self {
|
||||
unsafe { Self::transmute(7_u8.unchecked_sub(self as u8)) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn to_ascii(self) -> u8 {
|
||||
self as u8 + b'1'
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_ascii(c: u8) -> Option<Self> {
|
||||
(c <= b'8')
|
||||
.then(|| c.checked_sub(b'1').map(|i| unsafe { Self::transmute(i) }))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn bitboard(self) -> Bitboard {
|
||||
Bitboard(0xFF << ((self as u64) << 3))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) unsafe fn transmute(value: u8) -> Self {
|
||||
debug_assert!(value < 8);
|
||||
std::mem::transmute(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Rank {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "{}", self.to_char())
|
||||
}
|
||||
}
|
||||
|
||||
/// A square of the board.
|
||||
#[rustfmt::skip]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum Square{
|
||||
A1, B1, C1, D1, E1, F1, G1, H1,
|
||||
A2, B2, C2, D2, E2, F2, G2, H2,
|
||||
A3, B3, C3, D3, E3, F3, G3, H3,
|
||||
A4, B4, C4, D4, E4, F4, G4, H4,
|
||||
A5, B5, C5, D5, E5, F5, G5, H5,
|
||||
A6, B6, C6, D6, E6, F6, G6, H6,
|
||||
A7, B7, C7, D7, E7, F7, G7, H7,
|
||||
A8, B8, C8, D8, E8, F8, G8, H8,
|
||||
}
|
||||
|
||||
container!(Square, BySquare, 64);
|
||||
|
||||
impl Square {
|
||||
#[inline]
|
||||
#[rustfmt::skip]
|
||||
pub fn all() -> [Self; 64] {
|
||||
[
|
||||
Self::A1, Self::B1, Self::C1, Self::D1, Self::E1, Self::F1, Self::G1, Self::H1,
|
||||
Self::A2, Self::B2, Self::C2, Self::D2, Self::E2, Self::F2, Self::G2, Self::H2,
|
||||
Self::A3, Self::B3, Self::C3, Self::D3, Self::E3, Self::F3, Self::G3, Self::H3,
|
||||
Self::A4, Self::B4, Self::C4, Self::D4, Self::E4, Self::F4, Self::G4, Self::H4,
|
||||
Self::A5, Self::B5, Self::C5, Self::D5, Self::E5, Self::F5, Self::G5, Self::H5,
|
||||
Self::A6, Self::B6, Self::C6, Self::D6, Self::E6, Self::F6, Self::G6, Self::H6,
|
||||
Self::A7, Self::B7, Self::C7, Self::D7, Self::E7, Self::F7, Self::G7, Self::H7,
|
||||
Self::A8, Self::B8, Self::C8, Self::D8, Self::E8, Self::F8, Self::G8, Self::H8,
|
||||
]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new(file: File, rank: Rank) -> Self {
|
||||
unsafe { Self::transmute(((rank as u8) << 3) + file as u8) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn file(self) -> File {
|
||||
unsafe { File::transmute((self as u8) & 7) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn rank(self) -> Rank {
|
||||
unsafe { Rank::transmute((self as u8) >> 3) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn mirror(self) -> Self {
|
||||
Self::new(self.file(), self.rank().mirror())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn bitboard(self) -> Bitboard {
|
||||
Bitboard(1 << self as u8)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[rustfmt::skip]
|
||||
pub(crate) fn to_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::A1 => "a1", Self::B1 => "b1", Self::C1 => "c1", Self::D1 => "d1", Self::E1 => "e1", Self::F1 => "f1", Self::G1 => "g1", Self::H1 => "h1",
|
||||
Self::A2 => "a2", Self::B2 => "b2", Self::C2 => "c2", Self::D2 => "d2", Self::E2 => "e2", Self::F2 => "f2", Self::G2 => "g2", Self::H2 => "h2",
|
||||
Self::A3 => "a3", Self::B3 => "b3", Self::C3 => "c3", Self::D3 => "d3", Self::E3 => "e3", Self::F3 => "f3", Self::G3 => "g3", Self::H3 => "h3",
|
||||
Self::A4 => "a4", Self::B4 => "b4", Self::C4 => "c4", Self::D4 => "d4", Self::E4 => "e4", Self::F4 => "f4", Self::G4 => "g4", Self::H4 => "h4",
|
||||
Self::A5 => "a5", Self::B5 => "b5", Self::C5 => "c5", Self::D5 => "d5", Self::E5 => "e5", Self::F5 => "f5", Self::G5 => "g5", Self::H5 => "h5",
|
||||
Self::A6 => "a6", Self::B6 => "b6", Self::C6 => "c6", Self::D6 => "d6", Self::E6 => "e6", Self::F6 => "f6", Self::G6 => "g6", Self::H6 => "h6",
|
||||
Self::A7 => "a7", Self::B7 => "b7", Self::C7 => "c7", Self::D7 => "d7", Self::E7 => "e7", Self::F7 => "f7", Self::G7 => "g7", Self::H7 => "h7",
|
||||
Self::A8 => "a8", Self::B8 => "b8", Self::C8 => "c8", Self::D8 => "d8", Self::E8 => "e8", Self::F8 => "f8", Self::G8 => "g8", Self::H8 => "h8",
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_str(s: &str) -> Option<Self> {
|
||||
match s.as_bytes() {
|
||||
[f, r] => Self::from_ascii(&[*f, *r]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_ascii(s: &[u8; 2]) -> Option<Self> {
|
||||
let [f, r] = *s;
|
||||
Some(Self::new(File::from_ascii(f)?, Rank::from_ascii(r)?))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn trans(self, direction: Direction) -> Option<Self> {
|
||||
self.check_trans(direction).then(|| unsafe {
|
||||
// SAFETY: condition is checked before doing the translation
|
||||
self.trans_unchecked(direction)
|
||||
})
|
||||
}
|
||||
|
||||
/// SAFETY: the translation must not move the square outside the board
|
||||
#[inline]
|
||||
pub(crate) unsafe fn trans_unchecked(self, direction: Direction) -> Self {
|
||||
debug_assert!(self.check_trans(direction));
|
||||
let i = self as u8;
|
||||
unsafe {
|
||||
Self::transmute(match direction {
|
||||
Direction::East => i.unchecked_add(1),
|
||||
Direction::NorthEast => i.unchecked_add(9),
|
||||
Direction::North => i.unchecked_add(8),
|
||||
Direction::NorthWest => i.unchecked_add(7),
|
||||
Direction::SouthEast => i.unchecked_sub(7),
|
||||
Direction::South => i.unchecked_sub(8),
|
||||
Direction::SouthWest => i.unchecked_sub(9),
|
||||
Direction::West => i.unchecked_sub(1),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `false` if the translation would move the square outside the board
|
||||
#[inline]
|
||||
fn check_trans(self, direction: Direction) -> bool {
|
||||
match direction {
|
||||
Direction::East => self.file() < File::H,
|
||||
Direction::NorthEast => self.file() < File::H && self.rank() < Rank::Eighth,
|
||||
Direction::North => self.rank() < Rank::Eighth,
|
||||
Direction::NorthWest => self.file() > File::A && self.rank() < Rank::Eighth,
|
||||
Direction::SouthEast => self.file() < File::H && self.rank() > Rank::First,
|
||||
Direction::South => self.rank() > Rank::First,
|
||||
Direction::SouthWest => self.file() > File::A && self.rank() > Rank::First,
|
||||
Direction::West => self.file() > File::A,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) unsafe fn transmute(value: u8) -> Self {
|
||||
debug_assert!(value < 64);
|
||||
std::mem::transmute(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Square {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str(self.to_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// An error while parsing a [`Square`].
|
||||
#[derive(Debug)]
|
||||
pub struct ParseSquareError;
|
||||
impl std::fmt::Display for ParseSquareError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("invalid square syntax")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ParseSquareError {}
|
||||
|
||||
impl std::str::FromStr for Square {
|
||||
type Err = ParseSquareError;
|
||||
#[inline]
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::from_str(s).ok_or(ParseSquareError)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
#[rustfmt::skip]
|
||||
pub(crate) enum OptionSquare {
|
||||
_A1, _B1, _C1, _D1, _E1, _F1, _G1, _H1,
|
||||
_A2, _B2, _C2, _D2, _E2, _F2, _G2, _H2,
|
||||
_A3, _B3, _C3, _D3, _E3, _F3, _G3, _H3,
|
||||
_A4, _B4, _C4, _D4, _E4, _F4, _G4, _H4,
|
||||
_A5, _B5, _C5, _D5, _E5, _F5, _G5, _H5,
|
||||
_A6, _B6, _C6, _D6, _E6, _F6, _G6, _H6,
|
||||
_A7, _B7, _C7, _D7, _E7, _F7, _G7, _H7,
|
||||
_A8, _B8, _C8, _D8, _E8, _F8, _G8, _H8,
|
||||
None,
|
||||
}
|
||||
|
||||
impl OptionSquare {
|
||||
#[inline]
|
||||
pub(crate) fn new(square: Option<Square>) -> OptionSquare {
|
||||
match square {
|
||||
Some(square) => Self::from_square(square),
|
||||
None => Self::None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn try_into_square(self) -> Option<Square> {
|
||||
unsafe {
|
||||
match self {
|
||||
Self::None => None,
|
||||
_ => Some(Square::transmute(self as u8)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_square(square: Square) -> Self {
|
||||
unsafe { std::mem::transmute(square) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A type of piece.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum Role {
|
||||
Pawn = 1,
|
||||
Knight,
|
||||
Bishop,
|
||||
Rook,
|
||||
Queen,
|
||||
King,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
#[inline]
|
||||
pub fn all() -> [Self; 6] {
|
||||
[
|
||||
Self::Pawn,
|
||||
Self::Knight,
|
||||
Self::Bishop,
|
||||
Self::Rook,
|
||||
Self::Queen,
|
||||
Self::King,
|
||||
]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn to_char_uppercase(self) -> char {
|
||||
match self {
|
||||
Self::Pawn => 'P',
|
||||
Self::Knight => 'N',
|
||||
Self::Bishop => 'B',
|
||||
Self::Rook => 'R',
|
||||
Self::Queen => 'Q',
|
||||
Self::King => 'K',
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn to_char_lowercase(self) -> char {
|
||||
match self {
|
||||
Self::Pawn => 'p',
|
||||
Self::Knight => 'n',
|
||||
Self::Bishop => 'b',
|
||||
Self::Rook => 'r',
|
||||
Self::Queen => 'q',
|
||||
Self::King => 'k',
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_ascii(x: u8) -> Option<Self> {
|
||||
Some(match x {
|
||||
b'p' | b'P' => Self::Pawn,
|
||||
b'n' | b'N' => Self::Knight,
|
||||
b'b' | b'B' => Self::Bishop,
|
||||
b'r' | b'R' => Self::Rook,
|
||||
b'q' | b'Q' => Self::Queen,
|
||||
b'k' | b'K' => Self::King,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) unsafe fn transmute(i: u8) -> Self {
|
||||
debug_assert!(i > 0 && i <= 6, "got {i}");
|
||||
unsafe { std::mem::transmute(i) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct ByRole<T>(pub(crate) [T; 6]);
|
||||
#[allow(unused)]
|
||||
impl<T> ByRole<T> {
|
||||
#[inline]
|
||||
pub fn new<F>(f: F) -> Self
|
||||
where
|
||||
F: FnMut(Role) -> T,
|
||||
{
|
||||
Self(Role::all().map(f))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get(&self, kind: Role) -> &T {
|
||||
unsafe { self.0.get_unchecked((kind as usize).unchecked_sub(1)) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_mut(&mut self, kind: Role) -> &mut T {
|
||||
unsafe { self.0.get_unchecked_mut((kind as usize).unchecked_sub(1)) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ByRole<T>
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
#[inline]
|
||||
pub(crate) fn pawn(&self) -> T {
|
||||
*self.get(Role::Pawn)
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn knight(&self) -> T {
|
||||
*self.get(Role::Knight)
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn bishop(&self) -> T {
|
||||
*self.get(Role::Bishop)
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn rook(&self) -> T {
|
||||
*self.get(Role::Rook)
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn queen(&self) -> T {
|
||||
*self.get(Role::Queen)
|
||||
}
|
||||
#[inline]
|
||||
pub(crate) fn king(&self) -> T {
|
||||
*self.get(Role::King)
|
||||
}
|
||||
}
|
||||
|
||||
/// A chess piece (i.e. its [`Role`] and [`Color`]).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Piece {
|
||||
pub role: Role,
|
||||
pub color: Color,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[repr(u8)]
|
||||
pub(crate) enum Direction {
|
||||
East,
|
||||
NorthEast,
|
||||
North,
|
||||
NorthWest,
|
||||
SouthEast,
|
||||
South,
|
||||
SouthWest,
|
||||
West,
|
||||
}
|
||||
|
||||
container!(Direction, ByDirection, 8);
|
||||
|
||||
impl Direction {
|
||||
#[inline]
|
||||
pub fn all() -> [Self; 8] {
|
||||
[
|
||||
Self::East,
|
||||
Self::NorthEast,
|
||||
Self::North,
|
||||
Self::NorthWest,
|
||||
Self::SouthEast,
|
||||
Self::South,
|
||||
Self::SouthWest,
|
||||
Self::West,
|
||||
]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn transmute(value: u8) -> Self {
|
||||
debug_assert!(value < 8);
|
||||
std::mem::transmute(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Not for Direction {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn not(self) -> Self::Output {
|
||||
unsafe { Self::transmute(self as u8 ^ 0b111) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A side of the board.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[repr(u8)]
|
||||
pub enum CastlingSide {
|
||||
/// King's side
|
||||
Short,
|
||||
/// Queen's side
|
||||
Long,
|
||||
}
|
||||
|
||||
container!(CastlingSide, ByCastlingSide, 2);
|
||||
|
||||
impl CastlingSide {
|
||||
#[inline]
|
||||
pub fn all() -> [Self; 2] {
|
||||
[Self::Short, Self::Long]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn rook_origin_file(self) -> File {
|
||||
match self {
|
||||
Self::Short => File::H,
|
||||
Self::Long => File::A,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) struct CastlingRights(u8);
|
||||
|
||||
impl CastlingRights {
|
||||
#[inline]
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) const fn full() -> Self {
|
||||
Self(15)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn get(&self, color: Color, side: CastlingSide) -> bool {
|
||||
(self.0 & Self::mask(color, side)) != 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn set(&mut self, color: Color, side: CastlingSide) {
|
||||
self.0 |= Self::mask(color, side);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn unset(&mut self, color: Color, side: CastlingSide) {
|
||||
self.0 &= !Self::mask(color, side);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn mirror(&self) -> Self {
|
||||
Self(((self.0 & 3) << 2) | (self.0 >> 2))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
const fn mask(color: Color, side: CastlingSide) -> u8 {
|
||||
match (color, side) {
|
||||
(Color::White, CastlingSide::Short) => 1,
|
||||
(Color::White, CastlingSide::Long) => 2,
|
||||
(Color::Black, CastlingSide::Short) => 4,
|
||||
(Color::Black, CastlingSide::Long) => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
90
src/lib.rs
Normal file
90
src/lib.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
//! # eschac - a library for computing chess moves
|
||||
//!
|
||||
//! eschac implements fast legal move generation and a copy-make interface that enforces at compile
|
||||
//! time that no illegal move is played, with no runtime checks and no potential panics.
|
||||
//!
|
||||
//! ## Overview
|
||||
//!
|
||||
//! The most important type in eschac is [`Position`](position::Position), it represents a chess
|
||||
//! position from which legal moves are generated. [`Position::new`](position::Position::new)
|
||||
//! returns the starting position of a chess game, and arbitrary positions can be built using the
|
||||
//! [`Setup`](setup::Setup) type, but they must be validated and converted to a
|
||||
//! [`Position`](position::Position) to generate moves as eschac does not handle certain illegal --
|
||||
//! as in unreachable in a normal game -- positions (see
|
||||
//! [`IllegalPositionReason`](setup::IllegalPositionReason) to know more). Legal moves are then
|
||||
//! generated using the [`Position::legal_moves`](position::Position::legal_moves) method or
|
||||
//! obtained from chess notation like [`UciMove`](uci::UciMove) or [`San`](san::San). Moves are
|
||||
//! represented with the [`Move<'l>`](position::Move) type, which holds a reference to the origin
|
||||
//! position (hence the lifetime), this ensures the move is played on the correct position.
|
||||
//! Finally, moves are played using the [`Move::make`](position::Move) method which returns a new
|
||||
//! [`Position`](position::Position), and on it goes.
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! ```
|
||||
//! # (|| -> Result<(), Box<dyn std::error::Error>> {
|
||||
//!
|
||||
//! use eschac::prelude::*;
|
||||
//!
|
||||
//! // read a position from a text record
|
||||
//! let setup = "7k/4P1rp/5Q2/5p2/1Pp1bP2/8/r4K1P/6R1 w - -".parse::<Setup>()?;
|
||||
//! let position = setup.validate()?;
|
||||
//!
|
||||
//! // read a move in algebraic notation
|
||||
//! let san = "Ke1".parse::<San>()?;
|
||||
//! let m = san.to_move(&position)?;
|
||||
//!
|
||||
//! // play the move (note the absence of error handling)
|
||||
//! let position = m.make();
|
||||
//!
|
||||
//! // generate all the legal moves on the new position
|
||||
//! let moves = position.legal_moves();
|
||||
//! for m in moves {
|
||||
//! // print the UCI notation of each move
|
||||
//! println!("{}", m.to_uci());
|
||||
//! }
|
||||
//! # Ok(()) });
|
||||
//! ```
|
||||
//!
|
||||
//! ## Comparison with [shakmaty](https://crates.io/crates/shakmaty)
|
||||
//!
|
||||
//! shakmaty is another Rust library for chess processing. It is written by Niklas Fiekas, whose
|
||||
//! work greatly inspired the development of eschac. For most purposes, shakmaty is probably a
|
||||
//! better option, as eschac comes short of its miriad of features.
|
||||
//!
|
||||
//! Both libraries have the same core features:
|
||||
//! - vocabulary to describe the chessboard (squares, pieces, etc.)
|
||||
//! - parsing and editing positions
|
||||
//! - parsing standard move notations
|
||||
//! - fast legal move generation and play
|
||||
//!
|
||||
//! **eschac** distinguishes itself with:
|
||||
//! - a focus on performance
|
||||
//! - a more compact board representation
|
||||
//! - its use of the borrow checker to guarantee only legal moves are played
|
||||
//!
|
||||
//! **shakmaty** will be more suitable for a lot of applications, with:
|
||||
//! - vocabulary to describe and work with games, not just positions
|
||||
//! - insufficient material detection
|
||||
//! - PGN parsing
|
||||
//! - Zobrist hashing
|
||||
//! - Syzygy endgame tablebases
|
||||
//! - chess960 and other variants
|
||||
//! - etc.
|
||||
|
||||
pub(crate) mod array_vec;
|
||||
pub(crate) mod bitboard;
|
||||
pub(crate) mod magics;
|
||||
pub(crate) mod rays;
|
||||
|
||||
pub mod board;
|
||||
pub mod lookup;
|
||||
pub mod position;
|
||||
pub mod san;
|
||||
pub mod setup;
|
||||
pub mod uci;
|
||||
|
||||
/// The eschac prelude.
|
||||
pub mod prelude {
|
||||
pub use crate::{position::Position, san::San, setup::Setup, uci::UciMove};
|
||||
}
|
||||
202
src/lookup.rs
Normal file
202
src/lookup.rs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
//! Lookup tables initialisation.
|
||||
//!
|
||||
//! Move generation in eschac requires about 1MB of precomputed lookup tables.
|
||||
|
||||
use crate::bitboard::*;
|
||||
use crate::board::*;
|
||||
use crate::magics::*;
|
||||
use crate::rays::*;
|
||||
|
||||
pub(crate) use init::InitialisedLookup;
|
||||
|
||||
/// Forces the initialisation of the lookup tables.
|
||||
///
|
||||
/// It is not necessary to call this function, as lookup tables are initialised lazily, but it can
|
||||
/// be used to ensure that they are initialised before a given time.
|
||||
pub fn init() {
|
||||
InitialisedLookup::init();
|
||||
}
|
||||
|
||||
pub(crate) struct Lookup {
|
||||
rays: Rays,
|
||||
lines: BySquare<BySquare<Bitboard>>,
|
||||
segments: BySquare<BySquare<Bitboard>>,
|
||||
pawn_attacks: ByColor<BySquare<Bitboard>>,
|
||||
king_moves: BySquare<Bitboard>,
|
||||
knight_moves: BySquare<Bitboard>,
|
||||
pub(crate) magics: Magics,
|
||||
}
|
||||
|
||||
impl Lookup {
|
||||
#[inline]
|
||||
pub(crate) fn line(&self, a: Square, b: Square) -> Bitboard {
|
||||
*self.lines.get(a).get(b)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn segment(&self, a: Square, b: Square) -> Bitboard {
|
||||
*self.segments.get(a).get(b)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ray(&self, square: Square, direction: Direction) -> Bitboard {
|
||||
self.rays.ray(square, direction)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn king(&self, square: Square) -> Bitboard {
|
||||
*self.king_moves.get(square)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn knight(&self, square: Square) -> Bitboard {
|
||||
*self.knight_moves.get(square)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn pawn_attack(&self, color: Color, square: Square) -> Bitboard {
|
||||
*self.pawn_attacks.get(color).get(square)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn bishop(&self, square: Square, blockers: Bitboard) -> Bitboard {
|
||||
self.magics.bishop(square, blockers)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn rook(&self, square: Square, blockers: Bitboard) -> Bitboard {
|
||||
self.magics.rook(square, blockers)
|
||||
}
|
||||
|
||||
/// `role != Pawn`
|
||||
#[inline]
|
||||
pub(crate) fn targets(&self, role: Role, from: Square, blockers: Bitboard) -> Bitboard {
|
||||
match role {
|
||||
Role::Pawn => unreachable!(),
|
||||
Role::Knight => self.knight(from),
|
||||
Role::Bishop => self.bishop(from, blockers),
|
||||
Role::Rook => self.rook(from, blockers),
|
||||
Role::Queen => self.bishop(from, blockers) | self.rook(from, blockers),
|
||||
Role::King => self.king(from),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn compute() -> Self {
|
||||
let rays = Rays::new();
|
||||
|
||||
let lines = BySquare::new(|a| {
|
||||
BySquare::new(|b| {
|
||||
for d in Direction::all() {
|
||||
let r = rays.ray(a, d);
|
||||
if r.contains(b) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
Bitboard::new()
|
||||
})
|
||||
});
|
||||
|
||||
let segments = BySquare::new(|a| {
|
||||
BySquare::new(|b| {
|
||||
for d in Direction::all() {
|
||||
let r = rays.ray(a, d);
|
||||
if r.contains(b) {
|
||||
return r & !rays.ray(b, d);
|
||||
}
|
||||
}
|
||||
b.bitboard()
|
||||
})
|
||||
});
|
||||
|
||||
let pawn_attacks = ByColor::new(|color| {
|
||||
let direction = match color {
|
||||
Color::White => Direction::North,
|
||||
Color::Black => Direction::South,
|
||||
};
|
||||
BySquare::new(|square| {
|
||||
let mut res = Bitboard::new();
|
||||
if let Some(square) = square.trans(direction) {
|
||||
square.trans(Direction::East).map(|s| res.insert(s));
|
||||
square.trans(Direction::West).map(|s| res.insert(s));
|
||||
}
|
||||
res
|
||||
})
|
||||
});
|
||||
|
||||
let king_moves = BySquare::new(|square| {
|
||||
let mut res = Bitboard::new();
|
||||
for direction in Direction::all() {
|
||||
if let Some(x) = square.trans(direction) {
|
||||
res |= x.bitboard();
|
||||
}
|
||||
}
|
||||
res
|
||||
});
|
||||
|
||||
let knight_moves = BySquare::new(|s| {
|
||||
let mut res = Bitboard::new();
|
||||
if let Some(s) = s.trans(Direction::North) {
|
||||
s.trans(Direction::NorthEast).map(|s| res.insert(s));
|
||||
s.trans(Direction::NorthWest).map(|s| res.insert(s));
|
||||
}
|
||||
if let Some(s) = s.trans(Direction::West) {
|
||||
s.trans(Direction::NorthWest).map(|s| res.insert(s));
|
||||
s.trans(Direction::SouthWest).map(|s| res.insert(s));
|
||||
}
|
||||
if let Some(s) = s.trans(Direction::South) {
|
||||
s.trans(Direction::SouthWest).map(|s| res.insert(s));
|
||||
s.trans(Direction::SouthEast).map(|s| res.insert(s));
|
||||
}
|
||||
if let Some(s) = s.trans(Direction::East) {
|
||||
s.trans(Direction::SouthEast).map(|s| res.insert(s));
|
||||
s.trans(Direction::NorthEast).map(|s| res.insert(s));
|
||||
}
|
||||
res
|
||||
});
|
||||
|
||||
let magics = Magics::compute(&rays);
|
||||
|
||||
Self {
|
||||
rays,
|
||||
lines,
|
||||
segments,
|
||||
pawn_attacks,
|
||||
king_moves,
|
||||
knight_moves,
|
||||
magics,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod init {
|
||||
use std::{mem::MaybeUninit, sync::LazyLock};
|
||||
|
||||
use super::Lookup;
|
||||
|
||||
static mut LOOKUP: MaybeUninit<Lookup> = MaybeUninit::uninit();
|
||||
|
||||
#[allow(static_mut_refs)]
|
||||
static INIT: LazyLock<()> = LazyLock::new(|| unsafe {
|
||||
LOOKUP.write(Lookup::compute());
|
||||
});
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) struct InitialisedLookup(());
|
||||
|
||||
impl InitialisedLookup {
|
||||
#[inline]
|
||||
pub(crate) fn init() -> Self {
|
||||
LazyLock::force(&INIT);
|
||||
Self(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for InitialisedLookup {
|
||||
type Target = Lookup;
|
||||
#[allow(static_mut_refs)]
|
||||
#[inline]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { LOOKUP.assume_init_ref() }
|
||||
}
|
||||
}
|
||||
}
|
||||
326
src/magics.rs
Normal file
326
src/magics.rs
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
use crate::bitboard::*;
|
||||
use crate::board::*;
|
||||
use crate::rays::Rays;
|
||||
|
||||
const BISHOP_SHR: u8 = 55;
|
||||
const ROOK_SHR: u8 = 52;
|
||||
|
||||
pub(crate) struct Magics {
|
||||
bishop: BySquare<Magic>,
|
||||
rook: BySquare<Magic>,
|
||||
table: Box<[Bitboard]>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Magic {
|
||||
premask: Bitboard,
|
||||
factor: u64,
|
||||
offset: isize,
|
||||
}
|
||||
|
||||
impl Magics {
|
||||
pub(crate) fn compute(rays: &Rays) -> Self {
|
||||
let mut data = Vec::new();
|
||||
|
||||
let mut aux =
|
||||
|shr,
|
||||
factors: fn(Square) -> u64,
|
||||
make_table: fn(&Rays, Square) -> (Bitboard, Vec<(Bitboard, Bitboard)>)| {
|
||||
BySquare::new(|square| {
|
||||
let (premask, table) = make_table(rays, square);
|
||||
let factor = factors(square);
|
||||
let offset = fill_table(&mut data, shr, factor, table);
|
||||
Magic {
|
||||
premask,
|
||||
factor,
|
||||
offset,
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
let bishop = aux(BISHOP_SHR, bishop_factors, make_bishop_table);
|
||||
let rook = aux(ROOK_SHR, rook_factors, make_rook_table);
|
||||
|
||||
let mut table = Box::new_uninit_slice(data.len());
|
||||
for (i, entry) in data.into_iter().enumerate() {
|
||||
table[i].write(entry);
|
||||
}
|
||||
|
||||
Self {
|
||||
bishop,
|
||||
rook,
|
||||
table: unsafe { table.assume_init() },
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn bishop(&self, square: Square, blockers: Bitboard) -> Bitboard {
|
||||
unsafe { self.get_unchecked(BISHOP_SHR, *self.bishop.get(square), blockers) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn rook(&self, square: Square, blockers: Bitboard) -> Bitboard {
|
||||
unsafe { self.get_unchecked(ROOK_SHR, *self.rook.get(square), blockers) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn get_unchecked(&self, shr: u8, magic: Magic, blockers: Bitboard) -> Bitboard {
|
||||
let Magic {
|
||||
premask,
|
||||
factor,
|
||||
offset,
|
||||
} = magic;
|
||||
*self.table.get_unchecked(
|
||||
((hash(shr, factor, blockers | premask) as isize).unchecked_add(offset)) as usize,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_table(
|
||||
data: &mut Vec<Bitboard>,
|
||||
shr: u8,
|
||||
factor: u64,
|
||||
table: Vec<(Bitboard, Bitboard)>,
|
||||
) -> isize {
|
||||
let offset = data.len() as isize
|
||||
- table
|
||||
.iter()
|
||||
.map(|(x, _)| hash(shr, factor, *x) as isize)
|
||||
.min()
|
||||
.unwrap();
|
||||
for (x, y) in &table {
|
||||
let i = (hash(shr, factor, *x) as isize + offset) as usize;
|
||||
while data.len() <= i {
|
||||
data.push(Bitboard::new());
|
||||
}
|
||||
if data[i] != Bitboard::new() && data[i] != *y {
|
||||
panic!();
|
||||
}
|
||||
data[i] = *y;
|
||||
}
|
||||
offset
|
||||
}
|
||||
|
||||
fn make_bishop_table(rays: &Rays, square: Square) -> (Bitboard, Vec<(Bitboard, Bitboard)>) {
|
||||
let mut premask = Bitboard::new();
|
||||
for direction in [
|
||||
Direction::NorthWest,
|
||||
Direction::SouthWest,
|
||||
Direction::SouthEast,
|
||||
Direction::NorthEast,
|
||||
] {
|
||||
premask |= rays.ray(square, direction);
|
||||
}
|
||||
premask &= !Rank::First.bitboard();
|
||||
premask &= !Rank::Eighth.bitboard();
|
||||
premask &= !File::A.bitboard();
|
||||
premask &= !File::H.bitboard();
|
||||
|
||||
let mut table = make_table(premask, |blockers| {
|
||||
let mut res = Bitboard::new();
|
||||
for direction in [
|
||||
Direction::NorthWest,
|
||||
Direction::SouthWest,
|
||||
Direction::SouthEast,
|
||||
Direction::NorthEast,
|
||||
] {
|
||||
res |= rays.blocked(square, direction, blockers);
|
||||
}
|
||||
res
|
||||
});
|
||||
|
||||
premask = !premask;
|
||||
for (x, _) in &mut table {
|
||||
*x |= premask;
|
||||
}
|
||||
|
||||
(premask, table)
|
||||
}
|
||||
|
||||
fn make_rook_table(rays: &Rays, square: Square) -> (Bitboard, Vec<(Bitboard, Bitboard)>) {
|
||||
let mut premask = Bitboard::new();
|
||||
premask |= rays.ray(square, Direction::North) & !Rank::Eighth.bitboard();
|
||||
premask |= rays.ray(square, Direction::West) & !File::A.bitboard();
|
||||
premask |= rays.ray(square, Direction::South) & !Rank::First.bitboard();
|
||||
premask |= rays.ray(square, Direction::East) & !File::H.bitboard();
|
||||
|
||||
let mut table = make_table(premask, |blockers| {
|
||||
let mut res = Bitboard::new();
|
||||
for direction in [
|
||||
Direction::North,
|
||||
Direction::West,
|
||||
Direction::South,
|
||||
Direction::East,
|
||||
] {
|
||||
res |= rays.blocked(square, direction, blockers);
|
||||
}
|
||||
res
|
||||
});
|
||||
|
||||
premask = !premask;
|
||||
for (x, _) in &mut table {
|
||||
*x |= premask;
|
||||
}
|
||||
|
||||
(premask, table)
|
||||
}
|
||||
|
||||
fn make_table<T, F>(premask: Bitboard, f: F) -> Vec<(Bitboard, T)>
|
||||
where
|
||||
F: Fn(Bitboard) -> T,
|
||||
{
|
||||
let mut res = Vec::new();
|
||||
let mut subset: u64 = 0;
|
||||
loop {
|
||||
subset = subset.wrapping_sub(premask.0) & premask.0;
|
||||
let x = Bitboard(subset);
|
||||
let y = f(x);
|
||||
res.push((x, y));
|
||||
if subset == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
fn hash(shr: u8, factor: u64, x: Bitboard) -> usize {
|
||||
(x.0.wrapping_mul(factor) >> shr) as usize
|
||||
}
|
||||
|
||||
fn bishop_factors(square: Square) -> u64 {
|
||||
match square {
|
||||
Square::A1 => 0x0000404040404040,
|
||||
Square::B1 => 0x0040C100081000E8,
|
||||
Square::C1 => 0x0000401020200000,
|
||||
Square::D1 => 0x0040802004000000,
|
||||
Square::E1 => 0x10403C0180000000,
|
||||
Square::F1 => 0x0040210100800000,
|
||||
Square::G1 => 0x0068104002008000,
|
||||
Square::H1 => 0x0048082080040080,
|
||||
Square::A2 => 0x0000004040404040,
|
||||
Square::B2 => 0x0000002020202020,
|
||||
Square::C2 => 0x00040080184001E4,
|
||||
Square::D2 => 0x0040008020040000,
|
||||
Square::E2 => 0x1040003C01800000,
|
||||
Square::F2 => 0x0078002001008000,
|
||||
Square::G2 => 0x0068001040020080,
|
||||
Square::H2 => 0x0068000820010040,
|
||||
Square::A3 => 0x0000400080808080,
|
||||
Square::B3 => 0x0000200040404040,
|
||||
Square::C3 => 0x0000400080808080,
|
||||
Square::D3 => 0x0000200200801000,
|
||||
Square::E3 => 0x0060200100080000,
|
||||
Square::F3 => 0x0000100021C60021,
|
||||
Square::G3 => 0x0000040010410040,
|
||||
Square::H3 => 0x0000020008208020,
|
||||
Square::A4 => 0x0000804000810100,
|
||||
Square::B4 => 0x0000402000408080,
|
||||
Square::C4 => 0x0000040800802080,
|
||||
Square::D4 => 0x000020100C010020,
|
||||
Square::E4 => 0x0000840000802000,
|
||||
Square::F4 => 0x0001801800240010,
|
||||
Square::G4 => 0x0000080800104100,
|
||||
Square::H4 => 0x0000040400082080,
|
||||
Square::A5 => 0x0000010278010040,
|
||||
Square::B5 => 0x000000813C004040,
|
||||
Square::C5 => 0x000001027A010040,
|
||||
Square::D5 => 0x0000018180280200,
|
||||
Square::E5 => 0x0000204018003080,
|
||||
Square::F5 => 0x0000202040008040,
|
||||
Square::G5 => 0x0000101010002080,
|
||||
Square::H5 => 0x0000080808001040,
|
||||
Square::A6 => 0x0000004100F90080,
|
||||
Square::B6 => 0x0000002080BC0040,
|
||||
Square::C6 => 0x0000004103440080,
|
||||
Square::D6 => 0x0000000080FD0080,
|
||||
Square::E6 => 0x0000020040100100,
|
||||
Square::F6 => 0x0000404040400080,
|
||||
Square::G6 => 0x000000206027D010,
|
||||
Square::H6 => 0x00000008400DE806,
|
||||
Square::A7 => 0x0000002101007200,
|
||||
Square::B7 => 0x0000001041003900,
|
||||
Square::C7 => 0x080000000F8080A0,
|
||||
Square::D7 => 0x0000000008003FC0,
|
||||
Square::E7 => 0x0000000100202000,
|
||||
Square::F7 => 0x0000004040802000,
|
||||
Square::G7 => 0x00000060401043D0,
|
||||
Square::H7 => 0x00000020200413F0,
|
||||
Square::A8 => 0x1400000F00410088,
|
||||
Square::B8 => 0x0000000010410039,
|
||||
Square::C8 => 0x000080000800807E,
|
||||
Square::D8 => 0x000C69003008003F,
|
||||
Square::E8 => 0x0000000001002020,
|
||||
Square::F8 => 0x0000000040408020,
|
||||
Square::G8 => 0x001980004010801F,
|
||||
Square::H8 => 0x0000404040404040,
|
||||
}
|
||||
}
|
||||
|
||||
fn rook_factors(square: Square) -> u64 {
|
||||
match square {
|
||||
Square::A1 => 0x002000A28110000C,
|
||||
Square::B1 => 0x0018000C01060001,
|
||||
Square::C1 => 0x0040080010004004,
|
||||
Square::D1 => 0x0028004084200028,
|
||||
Square::E1 => 0x0030018000900300,
|
||||
Square::F1 => 0x0020008020010202,
|
||||
Square::G1 => 0x001800410080001F,
|
||||
Square::H1 => 0x0068006801040004,
|
||||
Square::A2 => 0x000028010114000A,
|
||||
Square::B2 => 0x00000C0083000600,
|
||||
Square::C2 => 0x0000080401020008,
|
||||
Square::D2 => 0x0000200200040020,
|
||||
Square::E2 => 0x0000200100020020,
|
||||
Square::F2 => 0x00001800C0006018,
|
||||
Square::G2 => 0x0000180070400018,
|
||||
Square::H2 => 0x0000180030640018,
|
||||
Square::A3 => 0x00300018010C0004,
|
||||
Square::B3 => 0x0004001000080010,
|
||||
Square::C3 => 0x0001000804020008,
|
||||
Square::D3 => 0x0002002004002002,
|
||||
Square::E3 => 0x0001002002002001,
|
||||
Square::F3 => 0x0001001000801040,
|
||||
Square::G3 => 0x0000004040008001,
|
||||
Square::H3 => 0x0000802000200040,
|
||||
Square::A4 => 0x0040200010080008,
|
||||
Square::B4 => 0x0000080010040010,
|
||||
Square::C4 => 0x0001020008040008,
|
||||
Square::D4 => 0x0000020020040020,
|
||||
Square::E4 => 0x0000010020020020,
|
||||
Square::F4 => 0x0000008020010020,
|
||||
Square::G4 => 0x0000008020200040,
|
||||
Square::H4 => 0x0000200020004081,
|
||||
Square::A5 => 0x0000081C00380020,
|
||||
Square::B5 => 0x0000080400100010,
|
||||
Square::C5 => 0x0000400880410010,
|
||||
Square::D5 => 0x0000200200200400,
|
||||
Square::E5 => 0x0000200100200200,
|
||||
Square::F5 => 0x0000200080200100,
|
||||
Square::G5 => 0x0000008000404001,
|
||||
Square::H5 => 0x0000802000200040,
|
||||
Square::A6 => 0x0000010B14002800,
|
||||
Square::B6 => 0x0000030086000C00,
|
||||
Square::C6 => 0x0000084040804200,
|
||||
Square::D6 => 0x0000020004002020,
|
||||
Square::E6 => 0x0000009001803003,
|
||||
Square::F6 => 0x0000004001004002,
|
||||
Square::G6 => 0x000000100800A804,
|
||||
Square::H6 => 0x000000082800D002,
|
||||
Square::A7 => 0x00000109040200A8,
|
||||
Square::B7 => 0x000000808A050014,
|
||||
Square::C7 => 0x0000004048038018,
|
||||
Square::D7 => 0x0000020020040020,
|
||||
Square::E7 => 0x0000002030018030,
|
||||
Square::F7 => 0x0000001800E08018,
|
||||
Square::G7 => 0x0000000810580050,
|
||||
Square::H7 => 0x0000000C04600050,
|
||||
Square::A8 => 0x0000001020891046,
|
||||
Square::B8 => 0x00000080090015C1,
|
||||
Square::C8 => 0x0000004005489101,
|
||||
Square::D8 => 0x0000040810204002,
|
||||
Square::E8 => 0x000C040810002022,
|
||||
Square::F8 => 0x0008000404883002,
|
||||
Square::G8 => 0x0008000400548802,
|
||||
Square::H8 => 0x0000000224104486,
|
||||
}
|
||||
}
|
||||
1488
src/position.rs
Normal file
1488
src/position.rs
Normal file
File diff suppressed because it is too large
Load diff
44
src/rays.rs
Normal file
44
src/rays.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use crate::bitboard::*;
|
||||
use crate::board::*;
|
||||
|
||||
pub(crate) struct Rays(BySquare<ByDirection<Bitboard>>);
|
||||
|
||||
impl Rays {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(BySquare::new(|square| {
|
||||
ByDirection::new(|direction| {
|
||||
let mut square = square;
|
||||
let mut res = Bitboard::new();
|
||||
while let Some(x) = square.trans(direction) {
|
||||
square = x;
|
||||
res |= square.bitboard();
|
||||
}
|
||||
res
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ray(&self, square: Square, direction: Direction) -> Bitboard {
|
||||
*self.0.get(square).get(direction)
|
||||
}
|
||||
|
||||
pub(crate) fn blocked(
|
||||
&self,
|
||||
square: Square,
|
||||
direction: Direction,
|
||||
blockers: Bitboard,
|
||||
) -> Bitboard {
|
||||
let blockers = blockers & *self.0.get(square).get(direction);
|
||||
let square2 = if (direction as u8) < 4 {
|
||||
blockers.first()
|
||||
} else {
|
||||
blockers.last()
|
||||
};
|
||||
*self.0.get(square).get(direction)
|
||||
& !match square2 {
|
||||
Some(square2) => *self.0.get(square2).get(direction),
|
||||
None => Bitboard::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
219
src/san.rs
Normal file
219
src/san.rs
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
//! Standard algebraic notation.
|
||||
//!
|
||||
//! SAN notation is the FIDE standard for writing moves.
|
||||
//!
|
||||
//! In its simplest form, it consists of the type of the moving piece followed by the target
|
||||
//! square. This may be ambiguous, in which cases the origin file and/or rank is also specified.
|
||||
//! The notation is shortened for pawns, and extra information may be added, to specify a capture
|
||||
//! or a check.
|
||||
//!
|
||||
//! Examples: *`e4`*, *`Qxd8#`*, *`O-O`*, *`h7h8=Q`*
|
||||
|
||||
use crate::board::*;
|
||||
use crate::position::*;
|
||||
|
||||
/// **The standard algebraic notation of a move.**
|
||||
///
|
||||
///
|
||||
/// When converting [`San`] notation to a playable [`Move`], the optional capture flag (*x*) and
|
||||
/// suffix (*+* or *#*) are ignored (as they are redundant). Thus, conversion will not fail if they
|
||||
/// are incorrectly set. Similarly, conversion will not fail when the move is unnecessarily
|
||||
/// disambiguated. For example, *Ke1xd1* and *Kd1* will always be equivalent, even if there is no
|
||||
/// piece on *d1*.
|
||||
///
|
||||
/// SAN notation can be obtained from a legal move using the [`Move::to_san`] method.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct San {
|
||||
pub(crate) inner: SanInner,
|
||||
pub(crate) suffix: Option<SanSuffix>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum SanInner {
|
||||
Castle(CastlingSide),
|
||||
Normal {
|
||||
role: Role,
|
||||
file: Option<File>,
|
||||
rank: Option<Rank>,
|
||||
capture: bool,
|
||||
target: Square,
|
||||
promotion: Option<Role>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum SanSuffix {
|
||||
Check,
|
||||
Checkmate,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for San {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
match self.inner {
|
||||
SanInner::Castle(CastlingSide::Short) => write!(f, "O-O")?,
|
||||
SanInner::Castle(CastlingSide::Long) => write!(f, "O-O-O")?,
|
||||
SanInner::Normal {
|
||||
role,
|
||||
file,
|
||||
rank,
|
||||
capture,
|
||||
target,
|
||||
promotion,
|
||||
} => {
|
||||
if role != Role::Pawn {
|
||||
write!(f, "{}", role.to_char_uppercase())?;
|
||||
}
|
||||
if let Some(file) = file {
|
||||
write!(f, "{}", file.to_char())?;
|
||||
}
|
||||
if let Some(rank) = rank {
|
||||
write!(f, "{}", rank.to_char())?;
|
||||
}
|
||||
if capture {
|
||||
write!(f, "x")?;
|
||||
}
|
||||
write!(f, "{}", target)?;
|
||||
if let Some(promotion) = promotion {
|
||||
write!(f, "={}", promotion.to_char_uppercase())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.suffix {
|
||||
Some(SanSuffix::Check) => write!(f, "+")?,
|
||||
Some(SanSuffix::Checkmate) => write!(f, "#")?,
|
||||
None => (),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for San {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.debug_tuple("San").field(&self.to_string()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for San {
|
||||
type Err = ParseSanError;
|
||||
#[inline]
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
San::from_ascii(s.as_bytes()).ok_or(ParseSanError)
|
||||
}
|
||||
}
|
||||
|
||||
/// A syntax error when parsing [`San`] notation.
|
||||
#[derive(Debug)]
|
||||
pub struct ParseSanError;
|
||||
impl std::fmt::Display for ParseSanError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("invalid SAN syntax")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ParseSanError {}
|
||||
|
||||
/// An error while converting [`San`] notation to a playable [`Move`].
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum InvalidSan {
|
||||
/// There is no move on the position that matches the SAN notation.
|
||||
Illegal,
|
||||
/// There is more than one move on the position that matches the SAN notation.
|
||||
Ambiguous,
|
||||
}
|
||||
impl std::fmt::Display for InvalidSan {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let details = match self {
|
||||
Self::Illegal => "illegal move",
|
||||
Self::Ambiguous => "ambiguous move",
|
||||
};
|
||||
write!(f, "invalid SAN ({details})")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for InvalidSan {}
|
||||
|
||||
impl San {
|
||||
/// Tries to convert SAN notation to a playable move.
|
||||
///
|
||||
/// This function ignores the suffix and the capture flag. It also accepts unnecessarily
|
||||
/// desambiguated moves.
|
||||
#[inline]
|
||||
pub fn to_move<'l>(&self, position: &'l Position) -> Result<Move<'l>, InvalidSan> {
|
||||
position.move_from_san(self)
|
||||
}
|
||||
|
||||
/// Tries to read SAN notation from ascii text.
|
||||
pub fn from_ascii(s: &[u8]) -> Option<Self> {
|
||||
let mut r = s.iter().copied().rev();
|
||||
let mut cur = r.next()?;
|
||||
|
||||
let suffix = match cur {
|
||||
b'+' => {
|
||||
cur = r.next()?;
|
||||
Some(SanSuffix::Check)
|
||||
}
|
||||
b'#' => {
|
||||
cur = r.next()?;
|
||||
Some(SanSuffix::Checkmate)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let inner = match cur {
|
||||
b'O' => SanInner::Castle({
|
||||
let b'-' = r.next()? else { return None };
|
||||
let b'O' = r.next()? else { return None };
|
||||
match r.next() {
|
||||
None => CastlingSide::Short,
|
||||
Some(b'-') => {
|
||||
let b'O' = r.next()? else { return None };
|
||||
r.next().is_none().then_some(())?;
|
||||
CastlingSide::Long
|
||||
}
|
||||
Some(_) => return None,
|
||||
}
|
||||
}),
|
||||
_ => {
|
||||
let promotion = Role::from_ascii(cur);
|
||||
if promotion.is_some() {
|
||||
(r.next()? == b'=').then_some(())?;
|
||||
cur = r.next()?;
|
||||
}
|
||||
let target_rank = Rank::from_ascii(cur)?;
|
||||
let target_file = File::from_ascii(r.next()?)?;
|
||||
let target = Square::new(target_file, target_rank);
|
||||
let mut cur = r.next();
|
||||
let capture = cur == Some(b'x');
|
||||
if capture {
|
||||
cur = r.next();
|
||||
}
|
||||
let rank = cur.and_then(Rank::from_ascii);
|
||||
if rank.is_some() {
|
||||
cur = r.next();
|
||||
}
|
||||
let file = cur.and_then(File::from_ascii);
|
||||
if file.is_some() {
|
||||
cur = r.next();
|
||||
}
|
||||
let role = match cur {
|
||||
Some(a) => {
|
||||
cur = r.next();
|
||||
Role::from_ascii(a)?
|
||||
}
|
||||
None => Role::Pawn,
|
||||
};
|
||||
cur.is_none().then_some(())?;
|
||||
(role != Role::Pawn || file.is_some() || !capture).then_some(())?;
|
||||
(role == Role::Pawn || promotion.is_none()).then_some(())?;
|
||||
SanInner::Normal {
|
||||
role,
|
||||
file,
|
||||
rank,
|
||||
capture,
|
||||
target,
|
||||
promotion,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Some(Self { inner, suffix })
|
||||
}
|
||||
}
|
||||
659
src/setup.rs
Normal file
659
src/setup.rs
Normal file
|
|
@ -0,0 +1,659 @@
|
|||
//! Building chess positions.
|
||||
//!
|
||||
//! [`Setup`] is a builder for the [`Position`] type.
|
||||
|
||||
use crate::bitboard::*;
|
||||
use crate::board::*;
|
||||
use crate::lookup::*;
|
||||
use crate::position::*;
|
||||
|
||||
/// **A builder type for chess positions.**
|
||||
///
|
||||
/// This type is useful to edit a position without having to ensure it stays legal at every step.
|
||||
/// It must be validated and converted to a [`Position`] using the [`Setup::validate`] method
|
||||
/// before generating moves.
|
||||
///
|
||||
/// This type implements [`FromStr`](std::str::FromStr) and [`Display`](std::fmt::Display) to parse
|
||||
/// and print positions from text records.
|
||||
///
|
||||
/// Forsyth-Edwards Notation (FEN) is typically used to describe chess positions as text. eschac
|
||||
/// uses a slightly different notation, which simply removes the last two fields of the FEN string
|
||||
/// (i.e. the halfmove clock and the fullmove number) as the [`Position`] type does not keep
|
||||
/// track of those.
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Setup {
|
||||
pub(crate) w: Bitboard,
|
||||
|
||||
pub(crate) p_b_q: Bitboard,
|
||||
pub(crate) n_b_k: Bitboard,
|
||||
pub(crate) r_q_k: Bitboard,
|
||||
|
||||
pub(crate) turn: Color,
|
||||
pub(crate) en_passant: OptionSquare,
|
||||
pub(crate) castling_rights: CastlingRights,
|
||||
}
|
||||
|
||||
impl Setup {
|
||||
/// Creates an empty board, i.e. `8/8/8/8/8/8/8/8 w - -`.
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
w: Bitboard(0),
|
||||
p_b_q: Bitboard(0),
|
||||
n_b_k: Bitboard(0),
|
||||
r_q_k: Bitboard(0),
|
||||
turn: Color::White,
|
||||
en_passant: OptionSquare::None,
|
||||
castling_rights: CastlingRights::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a position from an ascii record.
|
||||
pub fn from_ascii(s: &[u8]) -> Result<Self, ParseSetupError> {
|
||||
let mut s = s.iter().copied().peekable();
|
||||
let mut setup = Setup::new();
|
||||
(|| {
|
||||
let mut accept_empty_square = true;
|
||||
let mut rank: u8 = 7;
|
||||
let mut file: u8 = 0;
|
||||
for c in s.by_ref() {
|
||||
if c == b'/' {
|
||||
(file == 8).then_some(())?;
|
||||
rank = rank.checked_sub(1)?;
|
||||
file = 0;
|
||||
accept_empty_square = true;
|
||||
} else if (b'1'..=b'8').contains(&c) && accept_empty_square {
|
||||
file = file + c - b'0';
|
||||
(file <= 8).then_some(())?;
|
||||
accept_empty_square = false;
|
||||
} else if c == b' ' {
|
||||
break;
|
||||
} else {
|
||||
let role = Role::from_ascii(c)?;
|
||||
let color = match c.is_ascii_uppercase() {
|
||||
true => Color::White,
|
||||
false => Color::Black,
|
||||
};
|
||||
(file < 8).then_some(())?;
|
||||
setup.set(
|
||||
unsafe { Square::new(File::transmute(file), Rank::transmute(rank)) },
|
||||
Some(Piece { role, color }),
|
||||
);
|
||||
file += 1;
|
||||
accept_empty_square = true;
|
||||
}
|
||||
}
|
||||
(rank == 0).then_some(())?;
|
||||
(file == 8).then_some(())?;
|
||||
Some(())
|
||||
})()
|
||||
.ok_or(ParseSetupError::InvalidBoard)?;
|
||||
(|| {
|
||||
match s.next()? {
|
||||
b'w' => setup.set_turn(Color::White),
|
||||
b'b' => setup.set_turn(Color::Black),
|
||||
_ => return None,
|
||||
}
|
||||
(s.next()? == b' ').then_some(())
|
||||
})()
|
||||
.ok_or(ParseSetupError::InvalidTurn)?;
|
||||
(|| {
|
||||
if s.next_if_eq(&b'-').is_none() {
|
||||
if s.next_if_eq(&b'K').is_some() {
|
||||
setup.set_castling_rights(Color::White, CastlingSide::Short, true);
|
||||
}
|
||||
if s.next_if_eq(&b'Q').is_some() {
|
||||
setup.set_castling_rights(Color::White, CastlingSide::Long, true);
|
||||
}
|
||||
if s.next_if_eq(&b'k').is_some() {
|
||||
setup.set_castling_rights(Color::Black, CastlingSide::Short, true);
|
||||
}
|
||||
if s.next_if_eq(&b'q').is_some() {
|
||||
setup.set_castling_rights(Color::Black, CastlingSide::Long, true);
|
||||
}
|
||||
}
|
||||
(s.next()? == b' ').then_some(())
|
||||
})()
|
||||
.ok_or(ParseSetupError::InvalidCastlingRights)?;
|
||||
(|| {
|
||||
match s.next()? {
|
||||
b'-' => (),
|
||||
file => setup.set_en_passant_target_square(Some(Square::new(
|
||||
File::from_ascii(file)?,
|
||||
Rank::from_ascii(s.next()?)?,
|
||||
))),
|
||||
}
|
||||
s.next().is_none().then_some(())
|
||||
})()
|
||||
.ok_or(ParseSetupError::InvalidEnPassantTargetSquare)?;
|
||||
Ok(setup)
|
||||
}
|
||||
|
||||
/// Returns the occupancy of a square.
|
||||
#[inline]
|
||||
pub fn get(&self, square: Square) -> Option<Piece> {
|
||||
Some(Piece {
|
||||
role: self.get_role(square)?,
|
||||
color: match (self.w & square.bitboard()).is_empty() {
|
||||
false => Color::White,
|
||||
true => Color::Black,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the color to play.
|
||||
#[inline]
|
||||
pub fn turn(&self) -> Color {
|
||||
self.turn
|
||||
}
|
||||
|
||||
/// Returns `true` if castling is available for the given color and side.
|
||||
#[inline]
|
||||
pub fn castling_rights(&self, color: Color, side: CastlingSide) -> bool {
|
||||
self.castling_rights.get(color, side)
|
||||
}
|
||||
|
||||
/// Returns the optional en passant target square.
|
||||
#[inline]
|
||||
pub fn en_passant_target_square(&self) -> Option<Square> {
|
||||
self.en_passant.try_into_square()
|
||||
}
|
||||
|
||||
/// Sets the occupancy of a square.
|
||||
#[inline]
|
||||
pub fn set(&mut self, square: Square, piece: Option<Piece>) {
|
||||
let mask = !square.bitboard();
|
||||
self.w &= mask;
|
||||
self.p_b_q &= mask;
|
||||
self.n_b_k &= mask;
|
||||
self.r_q_k &= mask;
|
||||
if let Some(piece) = piece {
|
||||
let to = square.bitboard();
|
||||
match piece.color {
|
||||
Color::White => self.w |= to,
|
||||
Color::Black => (),
|
||||
}
|
||||
match piece.role {
|
||||
Role::Pawn => {
|
||||
self.p_b_q |= to;
|
||||
}
|
||||
Role::Knight => {
|
||||
self.n_b_k |= to;
|
||||
}
|
||||
Role::Bishop => {
|
||||
self.p_b_q |= to;
|
||||
self.n_b_k |= to;
|
||||
}
|
||||
Role::Rook => {
|
||||
self.r_q_k |= to;
|
||||
}
|
||||
Role::Queen => {
|
||||
self.p_b_q |= to;
|
||||
self.r_q_k |= to;
|
||||
}
|
||||
Role::King => {
|
||||
self.n_b_k |= to;
|
||||
self.r_q_k |= to;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the color to play.
|
||||
#[inline]
|
||||
pub fn set_turn(&mut self, color: Color) {
|
||||
self.turn = color;
|
||||
}
|
||||
|
||||
/// Sets the castling rights for the given color and side.
|
||||
#[inline]
|
||||
pub fn set_castling_rights(&mut self, color: Color, side: CastlingSide, value: bool) {
|
||||
match value {
|
||||
true => self.castling_rights.set(color, side),
|
||||
false => self.castling_rights.unset(color, side),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the en passant target square.
|
||||
#[inline]
|
||||
pub fn set_en_passant_target_square(&mut self, square: Option<Square>) {
|
||||
self.en_passant = OptionSquare::new(square);
|
||||
}
|
||||
|
||||
/// Returns the mirror image of the position.
|
||||
///
|
||||
/// The mirror of a position is the position obtained after reflecting the placement of pieces
|
||||
/// horizontally, inverting the color of all the pieces, inverting the turn, and reflecting the
|
||||
/// castling rights as well as the en passant target square.
|
||||
///
|
||||
/// For example, the mirror image of `rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b Kq e3`
|
||||
/// is `rnbqkbnr/pppp1ppp/8/4p3/8/8/PPPPPPPP/RNBQKBNR w Qk e6`.
|
||||
#[inline]
|
||||
pub fn mirror(&self) -> Self {
|
||||
Self {
|
||||
w: (self.w ^ (self.p_b_q | self.n_b_k | self.r_q_k)).mirror(),
|
||||
p_b_q: self.p_b_q.mirror(),
|
||||
n_b_k: self.n_b_k.mirror(),
|
||||
r_q_k: self.r_q_k.mirror(),
|
||||
turn: !self.turn,
|
||||
en_passant: self
|
||||
.en_passant
|
||||
.try_into_square()
|
||||
.map(|square| OptionSquare::from_square(square.mirror()))
|
||||
.unwrap_or(OptionSquare::None),
|
||||
castling_rights: self.castling_rights.mirror(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to validate the position, i.e. converting it to a [`Position`].
|
||||
///
|
||||
/// See [`IllegalPositionReason`] for details.
|
||||
pub fn validate(self) -> Result<Position, IllegalPosition> {
|
||||
debug_assert!((self.w & !(self.p_b_q | self.n_b_k | self.r_q_k)).is_empty());
|
||||
debug_assert!((self.p_b_q & self.n_b_k & self.r_q_k).is_empty());
|
||||
|
||||
let mut reasons = IllegalPositionReasons::new();
|
||||
let d = InitialisedLookup::init();
|
||||
|
||||
let blockers = self.p_b_q | self.n_b_k | self.r_q_k;
|
||||
let pieces = self.bitboards();
|
||||
|
||||
if Color::all()
|
||||
.into_iter()
|
||||
.any(|color| pieces.get(color).king().is_empty())
|
||||
{
|
||||
reasons.add(IllegalPositionReason::MissingKing);
|
||||
}
|
||||
|
||||
if Color::all()
|
||||
.into_iter()
|
||||
.any(|color| pieces.get(color).get(Role::King).len() > 1)
|
||||
{
|
||||
reasons.add(IllegalPositionReason::TooManyKings);
|
||||
}
|
||||
|
||||
if pieces.get(!self.turn).king().any(|enemy_king| {
|
||||
let pieces = pieces.get(self.turn);
|
||||
!(d.king(enemy_king) & *pieces.get(Role::King)
|
||||
| d.bishop(enemy_king, blockers)
|
||||
& (*pieces.get(Role::Queen) | *pieces.get(Role::Bishop))
|
||||
| d.rook(enemy_king, blockers)
|
||||
& (*pieces.get(Role::Queen) | *pieces.get(Role::Rook))
|
||||
| d.knight(enemy_king) & *pieces.get(Role::Knight)
|
||||
| d.pawn_attack(!self.turn, enemy_king) & *pieces.get(Role::Pawn))
|
||||
.is_empty()
|
||||
}) {
|
||||
reasons.add(IllegalPositionReason::HangingKing);
|
||||
}
|
||||
|
||||
if Color::all().into_iter().any(|color| {
|
||||
!(*pieces.get(color).get(Role::Pawn)
|
||||
& (Rank::First.bitboard() | Rank::Eighth.bitboard()))
|
||||
.is_empty()
|
||||
}) {
|
||||
reasons.add(IllegalPositionReason::PawnOnBackRank);
|
||||
}
|
||||
|
||||
if Color::all().into_iter().any(|color| {
|
||||
let dark_squares = Bitboard(0xAA55AA55AA55AA55);
|
||||
let light_squares = Bitboard(0x55AA55AA55AA55AA);
|
||||
let pieces = pieces.get(color);
|
||||
pieces.get(Role::Pawn).len()
|
||||
+ pieces.get(Role::Queen).len().saturating_sub(1)
|
||||
+ (*pieces.get(Role::Bishop) & dark_squares)
|
||||
.len()
|
||||
.saturating_sub(1)
|
||||
+ (*pieces.get(Role::Bishop) & light_squares)
|
||||
.len()
|
||||
.saturating_sub(1)
|
||||
+ pieces.get(Role::Knight).len().saturating_sub(2)
|
||||
+ pieces.get(Role::Rook).len().saturating_sub(2)
|
||||
> 8
|
||||
}) {
|
||||
reasons.add(IllegalPositionReason::TooMuchMaterial);
|
||||
}
|
||||
|
||||
if Color::all().into_iter().any(|color| {
|
||||
CastlingSide::all().into_iter().any(|side| {
|
||||
self.castling_rights.get(color, side)
|
||||
&& !(pieces
|
||||
.get(color)
|
||||
.get(Role::King)
|
||||
.contains(Square::new(File::E, color.home_rank()))
|
||||
&& pieces
|
||||
.get(color)
|
||||
.get(Role::Rook)
|
||||
.contains(Square::new(side.rook_origin_file(), color.home_rank())))
|
||||
})
|
||||
}) {
|
||||
reasons.add(IllegalPositionReason::InvalidCastlingRights);
|
||||
}
|
||||
|
||||
if self.en_passant.try_into_square().is_some_and(|en_passant| {
|
||||
let (target_rank, pawn_rank) = match self.turn {
|
||||
Color::White => (Rank::Sixth, Rank::Fifth),
|
||||
Color::Black => (Rank::Third, Rank::Fourth),
|
||||
};
|
||||
let pawn_square = Square::new(en_passant.file(), pawn_rank);
|
||||
en_passant.rank() != target_rank
|
||||
|| blockers.contains(en_passant)
|
||||
|| !pieces.get(!self.turn).get(Role::Pawn).contains(pawn_square)
|
||||
}) {
|
||||
reasons.add(IllegalPositionReason::InvalidEnPassant);
|
||||
}
|
||||
|
||||
if self.en_passant.try_into_square().is_some_and(|en_passant| {
|
||||
let blockers = blockers
|
||||
& !en_passant.bitboard().trans(match self.turn {
|
||||
Color::White => Direction::South,
|
||||
Color::Black => Direction::North,
|
||||
});
|
||||
pieces
|
||||
.get(self.turn)
|
||||
.king()
|
||||
.first()
|
||||
.is_some_and(|king_square| {
|
||||
!(d.bishop(king_square, blockers)
|
||||
& (pieces.get(!self.turn).queen() | pieces.get(!self.turn).bishop()))
|
||||
.is_empty()
|
||||
})
|
||||
}) {
|
||||
reasons.add(IllegalPositionReason::ImpossibleEnPassantPin);
|
||||
}
|
||||
|
||||
if reasons.0 != 0 {
|
||||
Err(IllegalPosition {
|
||||
setup: self,
|
||||
reasons,
|
||||
})
|
||||
} else {
|
||||
Ok(unsafe { Position::from_setup(self) })
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn get_role(&self, square: Square) -> Option<Role> {
|
||||
let mask = square.bitboard();
|
||||
let bit0 = (self.p_b_q & mask).0 >> square as u8;
|
||||
let bit1 = (self.n_b_k & mask).0 >> square as u8;
|
||||
let bit2 = (self.r_q_k & mask).0 >> square as u8;
|
||||
match bit0 | bit1 << 1 | bit2 << 2 {
|
||||
0 => None,
|
||||
i => Some(unsafe { Role::transmute(i as u8) }),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn bitboards(&self) -> ByColor<ByRole<Bitboard>> {
|
||||
let Self {
|
||||
w,
|
||||
p_b_q,
|
||||
n_b_k,
|
||||
r_q_k,
|
||||
..
|
||||
} = self.clone();
|
||||
let k = n_b_k & r_q_k;
|
||||
let q = p_b_q & r_q_k;
|
||||
let b = p_b_q & n_b_k;
|
||||
let n = n_b_k ^ b ^ k;
|
||||
let r = r_q_k ^ q ^ k;
|
||||
let p = p_b_q ^ b ^ q;
|
||||
ByColor::new(|color| {
|
||||
let mask = match color {
|
||||
Color::White => w,
|
||||
Color::Black => !w,
|
||||
};
|
||||
ByRole::new(|kind| {
|
||||
mask & match kind {
|
||||
Role::King => k,
|
||||
Role::Queen => q,
|
||||
Role::Bishop => b,
|
||||
Role::Knight => n,
|
||||
Role::Rook => r,
|
||||
Role::Pawn => p,
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Setup {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
f.debug_tuple("Setup").field(&self.to_string()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Setup {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
use std::fmt::Write;
|
||||
|
||||
for rank in Rank::all().into_iter().rev() {
|
||||
let mut count = 0;
|
||||
for file in File::all() {
|
||||
match self.get(Square::new(file, rank)) {
|
||||
Some(piece) => {
|
||||
if count > 0 {
|
||||
f.write_char(char::from_u32('0' as u32 + count).unwrap())?;
|
||||
}
|
||||
count = 0;
|
||||
f.write_char(match piece.color {
|
||||
Color::White => piece.role.to_char_uppercase(),
|
||||
Color::Black => piece.role.to_char_lowercase(),
|
||||
})?;
|
||||
}
|
||||
None => {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if count > 0 {
|
||||
f.write_char(char::from_u32('0' as u32 + count).unwrap())?;
|
||||
}
|
||||
if rank != Rank::First {
|
||||
f.write_char('/')?;
|
||||
}
|
||||
}
|
||||
|
||||
f.write_char(' ')?;
|
||||
|
||||
f.write_char(match self.turn {
|
||||
Color::White => 'w',
|
||||
Color::Black => 'b',
|
||||
})?;
|
||||
|
||||
f.write_char(' ')?;
|
||||
|
||||
let mut no_castle_available = true;
|
||||
if self.castling_rights(Color::White, CastlingSide::Short) {
|
||||
f.write_char('K')?;
|
||||
no_castle_available = false;
|
||||
}
|
||||
if self.castling_rights(Color::White, CastlingSide::Long) {
|
||||
f.write_char('Q')?;
|
||||
no_castle_available = false;
|
||||
}
|
||||
if self.castling_rights(Color::Black, CastlingSide::Short) {
|
||||
f.write_char('k')?;
|
||||
no_castle_available = false;
|
||||
}
|
||||
if self.castling_rights(Color::Black, CastlingSide::Long) {
|
||||
f.write_char('q')?;
|
||||
no_castle_available = false;
|
||||
}
|
||||
if no_castle_available {
|
||||
f.write_char('-')?;
|
||||
}
|
||||
|
||||
f.write_char(' ')?;
|
||||
|
||||
match self.en_passant.try_into_square() {
|
||||
Some(sq) => {
|
||||
f.write_str(sq.to_str())?;
|
||||
}
|
||||
None => {
|
||||
write!(f, "-")?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Setup {
|
||||
type Err = ParseSetupError;
|
||||
#[inline]
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::from_ascii(s.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// An error when trying to parse a position record.
|
||||
///
|
||||
/// The variant indicates the field that caused the error.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ParseSetupError {
|
||||
InvalidBoard,
|
||||
InvalidTurn,
|
||||
InvalidCastlingRights,
|
||||
InvalidEnPassantTargetSquare,
|
||||
}
|
||||
impl std::fmt::Display for ParseSetupError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let details = match self {
|
||||
Self::InvalidBoard => "board",
|
||||
Self::InvalidTurn => "turn",
|
||||
Self::InvalidCastlingRights => "castling rights",
|
||||
Self::InvalidEnPassantTargetSquare => "en passant target square",
|
||||
};
|
||||
write!(f, "invalid text record ({details})")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ParseSetupError {}
|
||||
|
||||
/// An invalid position.
|
||||
///
|
||||
/// This is an illegal position that can't be represented with the [`Position`] type.
|
||||
#[derive(Debug)]
|
||||
pub struct IllegalPosition {
|
||||
setup: Setup,
|
||||
reasons: IllegalPositionReasons,
|
||||
}
|
||||
impl std::fmt::Display for IllegalPosition {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
use std::fmt::Write;
|
||||
let setup = &self.setup;
|
||||
write!(f, "`{setup}` is illegal:")?;
|
||||
let mut first = true;
|
||||
for reason in self.reasons {
|
||||
if !first {
|
||||
f.write_char(',')?;
|
||||
}
|
||||
first = false;
|
||||
write!(f, " {reason}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl std::error::Error for IllegalPosition {}
|
||||
|
||||
impl IllegalPosition {
|
||||
/// Returns an iterator over the reasons why the position is rejected.
|
||||
pub fn reasons(&self) -> IllegalPositionReasons {
|
||||
self.reasons
|
||||
}
|
||||
|
||||
/// Returns the [`Setup`] that failed validation.
|
||||
pub fn as_setup(&self) -> &Setup {
|
||||
&self.setup
|
||||
}
|
||||
|
||||
/// Returns the [`Setup`] that failed validation.
|
||||
pub fn into_setup(self) -> Setup {
|
||||
self.setup
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of [`IllegalPositionReason`]s.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct IllegalPositionReasons(u8);
|
||||
|
||||
impl std::fmt::Debug for IllegalPositionReasons {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_list().entries(*self).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl IllegalPositionReasons {
|
||||
/// Returns `true` if the given reason appears in the set.
|
||||
pub fn contains(&self, reason: IllegalPositionReason) -> bool {
|
||||
(self.0 & reason as u8) != 0
|
||||
}
|
||||
|
||||
fn new() -> Self {
|
||||
IllegalPositionReasons(0)
|
||||
}
|
||||
|
||||
fn add(&mut self, reason: IllegalPositionReason) {
|
||||
self.0 |= reason as u8;
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for IllegalPositionReasons {
|
||||
type Item = IllegalPositionReason;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.0 == 0 {
|
||||
None
|
||||
} else {
|
||||
let reason = 1 << self.0.trailing_zeros();
|
||||
self.0 &= !reason;
|
||||
Some(unsafe { std::mem::transmute::<u8, IllegalPositionReason>(reason) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reasons for illegal positions to be rejected by eschac.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum IllegalPositionReason {
|
||||
/// One of the colors misses its king.
|
||||
MissingKing = 1,
|
||||
/// There is more than one king of the same color.
|
||||
TooManyKings = 2,
|
||||
/// The opponent's king is in check.
|
||||
HangingKing = 4,
|
||||
/// There is a pawn on the first or eighth rank.
|
||||
PawnOnBackRank = 8,
|
||||
/// Some castling rights are invalid regarding the positions of the rooks and kings.
|
||||
InvalidCastlingRights = 16,
|
||||
/// The en passant target square is invalid, either because:
|
||||
/// - it is not on the correct rank
|
||||
/// - it is occupied
|
||||
/// - it is not behind an opponent's pawn
|
||||
InvalidEnPassant = 32,
|
||||
/// There is an impossible number of pieces.
|
||||
///
|
||||
/// Enforcing this enables to put an upper limit on the number of legal moves on any position,
|
||||
/// allowing to reduce the size of [`Moves`].
|
||||
TooMuchMaterial = 64,
|
||||
/// The pawn that can be taken en passant is pinned diagonally to the playing king.
|
||||
///
|
||||
/// This can't happen on a legal position, as it would imply that the king could have be taken
|
||||
/// on that move. Enforcing this makes it unnecessary to test for a discovery check on the
|
||||
/// diagonal when taking en passant.
|
||||
ImpossibleEnPassantPin = 128,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IllegalPositionReason {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::MissingKing => "missing king",
|
||||
Self::TooManyKings => "too many kings",
|
||||
Self::HangingKing => "hanging king",
|
||||
Self::PawnOnBackRank => "pawn on back rank",
|
||||
Self::InvalidCastlingRights => "invalid castling rights",
|
||||
Self::InvalidEnPassant => "invalid en passant",
|
||||
Self::TooMuchMaterial => "too much material",
|
||||
Self::ImpossibleEnPassantPin => "illegal en passant",
|
||||
})
|
||||
}
|
||||
}
|
||||
95
src/uci.rs
Normal file
95
src/uci.rs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
//! UCI notation.
|
||||
//!
|
||||
//! Move notation as defined by the Universal Chess Interface standard used for most chess engines
|
||||
//! and chess servers.
|
||||
//!
|
||||
//! A move is described by its origin and target squares. Castling is described as the move done by
|
||||
//! the king. For promotion, a lowercase letter is added at the end of the move.
|
||||
//!
|
||||
//! Examples: *`e2e4`*, *`d1d8`*, *`e1g1`* (short castling), *`h7h8q`* (promotion)
|
||||
|
||||
use crate::board::*;
|
||||
use crate::position::*;
|
||||
|
||||
/// **The UCI notation of a move.**
|
||||
///
|
||||
/// UCI notation can be obtained from a legal move using the [`Move::to_uci`] method.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct UciMove {
|
||||
pub from: Square,
|
||||
pub to: Square,
|
||||
pub promotion: Option<Role>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for UciMove {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "{}{}", self.from, self.to)?;
|
||||
if let Some(promotion) = self.promotion {
|
||||
write!(f, "{}", promotion.to_char_lowercase())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for UciMove {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
f.debug_tuple("UciMove").field(&self.to_string()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for UciMove {
|
||||
type Err = ParseUciMoveError;
|
||||
#[inline]
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Self::from_ascii(s.as_bytes()).ok_or(ParseUciMoveError)
|
||||
}
|
||||
}
|
||||
|
||||
/// A syntax error when parsing a [`UciMove`].
|
||||
#[derive(Debug)]
|
||||
pub struct ParseUciMoveError;
|
||||
impl std::fmt::Display for ParseUciMoveError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("invalid UCI notation")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ParseUciMoveError {}
|
||||
|
||||
/// An error when converting [`UciMove`] notation to a playable [`Move`].
|
||||
#[derive(Debug)]
|
||||
pub enum InvalidUciMove {
|
||||
/// The is no move on the position that matches the UCI notation.
|
||||
Illegal,
|
||||
}
|
||||
impl std::fmt::Display for InvalidUciMove {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("illegal UCI move")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for InvalidUciMove {}
|
||||
|
||||
impl UciMove {
|
||||
/// Tries to convert UCI notation to a playable move.
|
||||
#[inline]
|
||||
pub fn to_move<'l>(&self, position: &'l Position) -> Result<Move<'l>, InvalidUciMove> {
|
||||
position.move_from_uci(*self)
|
||||
}
|
||||
|
||||
/// Tries to read UCI notation from ascii text.
|
||||
#[inline]
|
||||
pub fn from_ascii(s: &[u8]) -> Option<Self> {
|
||||
match s {
|
||||
[a, b, c, d, s @ ..] => Some(Self {
|
||||
from: Square::new(File::from_ascii(*a)?, Rank::from_ascii(*b)?),
|
||||
to: Square::new(File::from_ascii(*c)?, Rank::from_ascii(*d)?),
|
||||
promotion: match s {
|
||||
[] => None,
|
||||
[c] => Some(Role::from_ascii(*c)?),
|
||||
_ => return None,
|
||||
},
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue