1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
// This file is part of the shakmaty-syzygy library.
// Copyright (C) 2017-2022 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::{
cmp::{max, Reverse},
fs, io,
path::{Path, PathBuf},
};
use arrayvec::ArrayVec;
use once_cell::sync::OnceCell;
use positioned_io::RandomAccessFile;
use rustc_hash::FxHashMap;
use shakmaty::{Move, Position, Role};
use crate::{
errors::{ProbeResultExt as _, SyzygyError, SyzygyResult},
material::Material,
table::{DtzTable, WdlTable},
types::{DecisiveWdl, Dtz, MaybeRounded, Metric, Syzygy, Wdl},
AmbiguousWdl,
};
/// Additional probe information from a brief alpha-beta search.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum ProbeState {
/// Normal probe.
Normal,
/// Best move is zeroing.
ZeroingBestMove,
/// Threatening to force a capture (in antichess variants, where captures
/// are compulsory).
Threat,
}
/// A collection of tables.
#[derive(Debug)]
pub struct Tablebase<S: Position + Clone + Syzygy> {
wdl: FxHashMap<Material, (PathBuf, OnceCell<WdlTable<S, RandomAccessFile>>)>,
dtz: FxHashMap<Material, (PathBuf, OnceCell<DtzTable<S, RandomAccessFile>>)>,
max_pieces: usize,
}
impl<S: Position + Clone + Syzygy> Default for Tablebase<S> {
fn default() -> Tablebase<S> {
Tablebase::new()
}
}
impl<S: Position + Clone + Syzygy> Tablebase<S> {
/// Create an empty collection of tables.
pub fn new() -> Tablebase<S> {
Tablebase {
wdl: FxHashMap::with_capacity_and_hasher(145, Default::default()),
dtz: FxHashMap::with_capacity_and_hasher(145, Default::default()),
max_pieces: 0,
}
}
/// Returns the maximum number of pieces over all added tables.
///
/// This number is updated when adding table files and very fast to read.
#[inline]
pub fn max_pieces(&self) -> usize {
self.max_pieces
}
/// Add all relevant tables from a directory.
///
/// Tables are selected by filename, e.g. `KQvKP.rtbz`. The files are not
/// actually opened. This happens lazily when probing.
///
/// Note that probing generally requires tables for the specific material
/// composition, as well as material compositions that are transitively
/// reachable by captures and promotions. These are sometimes distributed
/// separately, so make sure to add tables from all relevant directories.
///
/// Returns the number of added table files.
///
/// # Errors
///
/// Returns an error result when:
///
/// * The `path` does not exist.
/// * `path` is not a directory.
/// * The process lacks permissions to list the directory.
pub fn add_directory<P: AsRef<Path>>(&mut self, path: P) -> io::Result<usize> {
let mut num = 0;
for entry in fs::read_dir(path)? {
if self.add_file(entry?.path()).is_ok() {
num += 1;
}
}
Ok(num)
}
/// Add a table file.
///
/// The file is not actually opened. This happens lazily when probing.
///
/// # Errors
///
/// Returns an error when no file exists at the given path or the
/// filename does not indicate that it is a valid table file
/// (e.g. `KQvKP.rtbz`).
pub fn add_file<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> {
let path = path.as_ref();
if !path.is_file() {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
let (stem, ext) = path
.file_stem()
.and_then(|s| s.to_str())
.zip(path.extension())
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
let material =
Material::from_str(stem).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
let pieces = material.count();
if pieces > S::MAX_PIECES {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
if material.by_color.white.count() < 1 || material.by_color.black.count() < 1 {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
if ext == S::TBW.ext
|| (!material.has_pawns() && S::PAWNLESS_TBW.map_or(false, |t| ext == t.ext))
{
self.wdl
.insert(material, (path.to_path_buf(), OnceCell::new()));
} else if ext == S::TBZ.ext
|| (!material.has_pawns() && S::PAWNLESS_TBZ.map_or(false, |t| ext == t.ext))
{
self.dtz
.insert(material, (path.to_path_buf(), OnceCell::new()));
} else {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
self.max_pieces = max(self.max_pieces, pieces);
Ok(())
}
fn wdl_table(&self, key: &Material) -> SyzygyResult<&WdlTable<S, RandomAccessFile>> {
if let Some((path, table)) = self
.wdl
.get(key)
.or_else(|| self.wdl.get(&key.clone().into_flipped()))
{
table
.get_or_try_init(|| WdlTable::open(path, key))
.ctx(Metric::Wdl, key.to_owned())
} else {
Err(SyzygyError::MissingTable {
metric: Metric::Wdl,
material: key.clone().into_normalized(),
})
}
}
fn dtz_table(&self, key: &Material) -> SyzygyResult<&DtzTable<S, RandomAccessFile>> {
if let Some((path, table)) = self
.dtz
.get(key)
.or_else(|| self.dtz.get(&key.clone().into_flipped()))
{
table
.get_or_try_init(|| DtzTable::open(path, key))
.ctx(Metric::Dtz, key.to_owned())
} else {
Err(SyzygyError::MissingTable {
metric: Metric::Dtz,
material: key.clone().into_normalized(),
})
}
}
/// Probe tables for the [`Wdl`] value of a position, assuming `pos`
/// is reached directly after a capture or pawn move.
///
/// # Errors
///
/// See [`SyzygyError`] for possible error conditions.
pub fn probe_wdl_after_zeroing(&self, pos: &S) -> SyzygyResult<Wdl> {
self.probe(pos).map(|entry| entry.wdl_after_zeroing())
}
/// Probe tables for the WDL value of a position, considering also
/// the halfmove counter of `pos`. The result may be
/// [ambiguous due to DTZ rounding](MaybeRounded).
///
/// Requires both WDL and DTZ tables.
///
/// # Errors
///
/// See [`SyzygyError`] for possible error conditions.
pub fn probe_wdl(&self, pos: &S) -> SyzygyResult<AmbiguousWdl> {
self.probe(pos)
.and_then(|entry| entry.dtz())
.map(|dtz| AmbiguousWdl::from_dtz_and_halfmoves(dtz, pos.halfmoves()))
}
/// Probe tables for the [`Dtz`] value of a position.
///
/// Requires both WDL and DTZ tables.
///
/// # Errors
///
/// See [`SyzygyError`] for possible error conditions.
pub fn probe_dtz(&self, pos: &S) -> SyzygyResult<MaybeRounded<Dtz>> {
self.probe(pos).and_then(|entry| entry.dtz())
}
/// Get the recommended tablebase move.
///
/// Following the tablebase mainline *starting from a capture or pawn move*
/// guarantees achieving the optimal outcome under the 50-move rule.
///
/// Otherwise (i.e. when not immediately following the tablebase mainline
/// after the capture that crosses into tablebase territory),
/// [some care needs to be taken due to DTZ rounding](MaybeRounded).
///
/// Requires both WDL and DTZ tables.
///
/// # Errors
///
/// See [`SyzygyError`] for possible error conditions.
pub fn best_move(&self, pos: &S) -> SyzygyResult<Option<(Move, MaybeRounded<Dtz>)>> {
struct WithAfter<S> {
m: Move,
after: S,
}
struct WithWdlEntry<'a, S: Position + Clone + Syzygy> {
m: Move,
entry: WdlEntry<'a, S>,
}
struct WithDtz {
m: Move,
immediate_loss: bool,
zeroing: bool,
dtz: MaybeRounded<Dtz>,
}
// Build list of successor positions.
let with_after = pos
.legal_moves()
.into_iter()
.map(|m| {
let mut after = pos.clone();
after.play_unchecked(&m);
WithAfter { m, after }
})
.collect::<ArrayVec<_, 256>>();
// Determine WDL for each move.
let with_wdl = with_after
.iter()
.map(|e| {
Ok(WithWdlEntry {
m: e.m.clone(),
entry: self.probe(&e.after)?,
})
})
.collect::<SyzygyResult<ArrayVec<_, 256>>>()?;
// Find best WDL.
let best_wdl = with_wdl
.iter()
.map(|a| a.entry.wdl)
.min()
.unwrap_or(Wdl::Loss);
// Select a DTZ-optimal move among the moves with best WDL.
itertools::process_results(
with_wdl
.iter()
.filter(|a| a.entry.wdl == best_wdl)
.map(|a| {
let dtz = a.entry.dtz()?;
Ok(WithDtz {
immediate_loss: dtz.ignore_rounding() == Dtz(-1)
&& (a.entry.pos.is_checkmate()
|| a.entry.pos.variant_outcome().is_some()),
zeroing: a.m.is_zeroing(),
m: a.m.clone(),
dtz,
})
}),
|iter| {
iter.min_by_key(|m| {
(
Reverse(m.immediate_loss),
m.zeroing ^ m.dtz.is_negative(), // zeroing is good/bad if winning/losing
Reverse(m.dtz.ignore_rounding()),
)
})
.map(|m| (m.m, m.dtz))
},
)
}
fn probe<'a>(&'a self, pos: &'a S) -> SyzygyResult<WdlEntry<'a, S>> {
if pos.board().occupied().count() > S::MAX_PIECES {
return Err(SyzygyError::TooManyPieces);
}
if pos.castles().any() {
return Err(SyzygyError::Castling);
}
// Determine the WDL value of this position. This is also a
// prerequisite for probing DTZ tables. There are two complications:
//
// (1) Resolving en passant captures.
//
// (2) When a position has a capture that achieves a particular result
// (e.g. there is a winning capture), then the position itself
// should have at least that value (e.g. it is winning). In this
// case the table can store an arbitrary lower value, whichever is
// best for compression.
//
// If the best move is zeroing, then we need remember this to avoid
// probing the DTZ tables.
if S::CAPTURES_COMPULSORY {
// Tables for antichess variants take advantage of the rule that
// captures are compulsory. Forced captures are resolved in a brief
// alpha-beta search. Additionally 6-piece tables need a 1-ply
// search to find threat moves that will force a losing capture.
//
// Here we search for threat moves unconditionally. Strictly
// speaking this is not required when there are less than 6 pieces,
// but we need to know if there are threat moves when continuing
// with a DTZ probe.
let (v, state) = self.probe_compulsory_captures(pos, Wdl::Loss, Wdl::Win, true)?;
return Ok(WdlEntry {
tablebase: self,
pos,
wdl: v,
state,
});
} else if let Some(outcome) = pos.variant_outcome() {
// Handle game-end postions of chess variants.
return Ok(WdlEntry {
tablebase: self,
pos,
wdl: Wdl::from_outcome(outcome, pos.turn()),
state: ProbeState::ZeroingBestMove,
});
}
// Resolve captures: Find the best non-ep capture and the best
// en passant capture.
let mut best_capture = Wdl::Loss;
let mut best_ep = Wdl::Loss;
let legals = pos.legal_moves();
for m in legals.iter().filter(|m| m.is_capture()) {
let mut after = pos.clone();
after.play_unchecked(m);
let v = -self.probe_ab_no_ep(&after, Wdl::Loss, -best_capture)?;
if v == Wdl::Win {
return Ok(WdlEntry {
tablebase: self,
pos,
wdl: v,
state: ProbeState::ZeroingBestMove,
});
}
if m.is_en_passant() {
best_ep = max(best_ep, v);
} else {
best_capture = max(best_capture, v);
}
}
// Probe table.
let v = self.probe_wdl_table(pos)?;
// Now max(v, best_capture) is the WDL value of the position without
// ep rights. Detect the case were an ep move is stricly better
// (including blessed losing positions).
if best_ep > max(v, best_capture) {
return Ok(WdlEntry {
tablebase: self,
pos,
wdl: best_ep,
state: ProbeState::ZeroingBestMove,
});
}
best_capture = max(best_capture, best_ep);
// Now max(v, best_capture) is the WDL value of the position,
// unless the position without ep rights is stalemate (and there are
// ep moves).
if best_capture >= v {
return Ok(WdlEntry {
tablebase: self,
pos,
wdl: best_capture,
state: if best_capture > Wdl::Draw {
ProbeState::ZeroingBestMove
} else {
ProbeState::Normal
},
});
}
// If the position would be stalemate without ep captures, then we are
// forced to play the best en passant move.
if v == Wdl::Draw && !legals.is_empty() && legals.iter().all(|m| m.is_en_passant()) {
return Ok(WdlEntry {
tablebase: self,
pos,
wdl: best_ep,
state: ProbeState::ZeroingBestMove,
});
}
Ok(WdlEntry {
tablebase: self,
pos,
wdl: v,
state: ProbeState::Normal,
})
}
fn probe_ab_no_ep(&self, pos: &S, mut alpha: Wdl, beta: Wdl) -> SyzygyResult<Wdl> {
// Use alpha-beta to recursively resolve captures. This is only called
// for positions without ep rights.
assert!(pos.maybe_ep_square().is_none());
for m in pos.capture_moves() {
let mut after = pos.clone();
after.play_unchecked(&m);
let v = -self.probe_ab_no_ep(&after, -beta, -alpha)?;
if v >= beta {
return Ok(v);
}
alpha = max(alpha, v);
}
let v = self.probe_wdl_table(pos)?;
Ok(max(alpha, v))
}
fn probe_compulsory_captures(
&self,
pos: &S,
mut alpha: Wdl,
beta: Wdl,
threats: bool,
) -> SyzygyResult<(Wdl, ProbeState)> {
assert!(S::CAPTURES_COMPULSORY);
if let Some(outcome) = pos.variant_outcome() {
return Ok((
Wdl::from_outcome(outcome, pos.turn()),
ProbeState::ZeroingBestMove,
));
}
// Explore compulsory captures in antichess variants.
if pos.them().count() > 1 {
if let Some(v) = self.probe_captures(pos, alpha, beta)? {
return Ok((v, ProbeState::ZeroingBestMove));
}
} else {
// The opponent only has one piece left. If we need to capture it
// this immediately ends the game.
if !pos.capture_moves().is_empty() {
return Ok((Wdl::Loss, ProbeState::ZeroingBestMove));
}
}
let mut threats_found = false;
// For 6 piece endgames (or if indicated by the threats flag) also
// explore threat moves that will force a capture on following move.
if threats || pos.board().occupied().count() >= 6 {
for threat in pos.legal_moves() {
if threat.role() != Role::Pawn {
let mut after = pos.clone();
after.play_unchecked(&threat);
if let Some(v_plus) = self.probe_captures(&after, -beta, -alpha)? {
let v = -v_plus;
if v > alpha {
threats_found = true;
alpha = v;
if alpha >= beta {
return Ok((v, ProbeState::Threat));
}
}
}
}
}
}
let v = self.probe_wdl_table(pos)?;
if v > alpha {
Ok((v, ProbeState::Normal))
} else {
Ok((
alpha,
if threats_found {
ProbeState::Threat
} else {
ProbeState::Normal
},
))
}
}
fn probe_captures(&self, pos: &S, mut alpha: Wdl, beta: Wdl) -> SyzygyResult<Option<Wdl>> {
assert!(S::CAPTURES_COMPULSORY);
// Explore capture moves in antichess variants. If captures exists they
// are also the only moves, because captures are compulsory.
let captures = pos.capture_moves();
for m in pos.capture_moves() {
let mut after = pos.clone();
after.play_unchecked(&m);
let (v_plus, _) = self.probe_compulsory_captures(&after, -beta, -alpha, false)?;
let v = -v_plus;
alpha = max(v, alpha);
if alpha >= beta {
break;
}
}
Ok(if captures.is_empty() {
None
} else {
Some(alpha)
})
}
fn probe_wdl_table(&self, pos: &S) -> SyzygyResult<Wdl> {
// Variant game end.
if let Some(outcome) = pos.variant_outcome() {
return Ok(Wdl::from_outcome(outcome, pos.turn()));
}
// Test for KvK.
if S::ONE_KING && pos.board().kings() == pos.board().occupied() {
return Ok(Wdl::Draw);
}
// Get raw WDL value from the appropriate table.
let key = Material::from_board(pos.board());
self.wdl_table(&key)
.and_then(|table| table.probe_wdl(pos).ctx(Metric::Wdl, key))
}
fn probe_dtz_table(
&self,
pos: &S,
wdl: DecisiveWdl,
) -> SyzygyResult<Option<MaybeRounded<u32>>> {
// Get raw DTZ value from the appropriate table.
let key = Material::from_board(pos.board());
self.dtz_table(&key)
.and_then(|table| table.probe_dtz(pos, wdl).ctx(Metric::Dtz, key))
}
}
/// WDL entry. Prerequisite for probing DTZ tables.
#[derive(Debug)]
struct WdlEntry<'a, S: Position + Clone + Syzygy> {
tablebase: &'a Tablebase<S>,
pos: &'a S,
wdl: Wdl,
state: ProbeState,
}
impl<'a, S: Position + Clone + Syzygy + 'a> WdlEntry<'a, S> {
fn wdl_after_zeroing(&self) -> Wdl {
self.wdl
}
fn dtz(&self) -> SyzygyResult<MaybeRounded<Dtz>> {
let wdl = match self.wdl.decisive() {
Some(wdl) => wdl,
None => return Ok(MaybeRounded::Precise(Dtz(0))),
};
if self.state == ProbeState::ZeroingBestMove || self.pos.us() == self.pos.our(Role::Pawn) {
return Ok(MaybeRounded::Precise(Dtz::before_zeroing(wdl.into())));
}
if self.state == ProbeState::Threat && wdl >= DecisiveWdl::CursedWin {
// The position is a win or a cursed win by a threat move.
return Ok(MaybeRounded::Precise(
Dtz::before_zeroing(wdl.into()).add_plies(1),
));
}
// If winning, check for a winning pawn move. No need to look at
// captures again, they were already handled above.
if wdl >= DecisiveWdl::CursedWin {
let mut pawn_advances = self.pos.legal_moves();
pawn_advances.retain(|m| !m.is_capture() && m.role() == Role::Pawn);
for m in &pawn_advances {
let mut after = self.pos.clone();
after.play_unchecked(m);
let v = -self.tablebase.probe_wdl_after_zeroing(&after)?;
if v == wdl.into() {
return Ok(MaybeRounded::Precise(Dtz::before_zeroing(wdl.into())));
}
}
}
// At this point we know that the best move is not a capture. Probe the
// table. DTZ tables store only one side to move.
if let Some(plies) = self.tablebase.probe_dtz_table(self.pos, wdl)? {
return Ok(plies.map(|plies| Dtz::before_zeroing(wdl.into()).add_plies(plies)));
}
// We have to probe the other side of the table by doing
// a 1-ply search.
let mut moves = self.pos.legal_moves();
moves.retain(|m| !m.is_zeroing());
let mut best = if wdl >= DecisiveWdl::CursedWin {
None
} else {
Some(MaybeRounded::Precise(Dtz::before_zeroing(wdl.into())))
};
for m in &moves {
let mut after = self.pos.clone();
after.play_unchecked(m);
let v = -self.tablebase.probe_dtz(&after)?;
if v.ignore_rounding() == Dtz(1) && after.is_checkmate() {
best = Some(MaybeRounded::Precise(Dtz(1)));
} else if v.signum() == wdl.signum() {
let v = v.map(|v| v.add_plies(1));
best = match best {
None => Some(v),
Some(best) if v.ignore_rounding() < best.ignore_rounding() => Some(v),
_ => best,
};
}
}
(|| Ok(u!(best)))().ctx(Metric::Dtz, Material::from_board(self.pos.board()))
}
}
#[cfg(test)]
mod tests {
use shakmaty::{fen::Fen, CastlingMode, Chess, Square};
use super::*;
#[test]
fn test_send_sync() {
fn assert_send<T: Send>(_: T) {}
fn assert_sync<T: Sync>(_: T) {}
assert_send(Tablebase::<Chess>::new());
assert_sync(Tablebase::<Chess>::new());
}
#[test]
fn test_mating_best_move() {
let mut tables = Tablebase::new();
tables
.add_directory("tables/chess")
.expect("read directory");
let pos: Chess = "5BrN/8/8/8/8/2k5/8/2K5 b - -"
.parse::<Fen>()
.expect("valid fen")
.into_position(CastlingMode::Chess960)
.expect("legal position");
assert!(matches!(
tables.best_move(&pos),
Ok(Some((
Move::Normal {
role: Role::Rook,
from: Square::G8,
capture: None,
to: Square::G1,
promotion: None,
},
MaybeRounded::Rounded(Dtz(-1))
)))
));
}
#[test]
fn test_black_escapes_via_underpromotion() {
let mut tables = Tablebase::new();
tables
.add_directory("tables/chess")
.expect("read directory");
let pos: Chess = "8/6B1/8/8/B7/8/K1pk4/8 b - - 0 1"
.parse::<Fen>()
.expect("valid fen")
.into_position(CastlingMode::Chess960)
.expect("legal position");
assert!(matches!(
tables.best_move(&pos),
Ok(Some((
Move::Normal {
role: Role::Pawn,
from: Square::C2,
to: Square::C1,
capture: None,
promotion: Some(Role::Knight),
},
MaybeRounded::Rounded(Dtz(109))
)))
));
}
#[test]
#[ignore]
fn test_many_pawns() {
let mut tables = Tablebase::new();
tables
.add_directory("tables/chess")
.expect("read directory");
let pos: Chess = "3k4/5P2/8/8/4K3/2P3P1/PP6/8 w - - 0 1"
.parse::<Fen>()
.expect("valid fen")
.into_position(CastlingMode::Chess960)
.expect("legal position");
assert!(matches!(
tables.probe_dtz(&pos),
Ok(MaybeRounded::Precise(Dtz(1)))
));
}
}