Code Monkey home page Code Monkey logo

cozy-chess's Introduction

cozy-chess

Rust Chess and Chess960 move generation library

crates.io ko-fi lgbtq+ friendly trans rights

cozy-chess is a Chess and Chess960 (Fischer Random Chess) move generation library written in Rust that aims to provide competitive move generation performance. It is largely inspired by Jordan Bray's neat chess library. cozy-chess aims to be a safer alternative to chess that maintains correctness while providing similar performance.

Overview

  • no_std compatible
  • Supports Chess, Chess960/FRC, and Double Chess960/DFRC
  • Strongly-typed API that makes heavy use of newtypes to avoid errors
  • Performant legal move generation suitable for use in a chess engine
    • Implements fixed shift fancy black magic bitboards
    • Optionally implements PEXT bitboards based on the BMI2 intrinsic
    • Flexible API produces moves in bulk for optional bulk filtering
  • Efficient bitboard-based board representation
  • Incrementally updated zobrist hash for quickly obtaining a hash of a board

Crate features

  • std: Enable features that require std. Currently only used for the Error trait.
  • pext: Enable PEXT bitboards.

A note on CPU features and performance

By default, Rust binaries target a baseline CPU to ensure maximum compatibility at the cost of performance. cozy-chess benefits significantly from features present in modern CPUs. For maximum performance, the target CPU can instead be set to native to use features supported by the machine running the build. Alternatively, the target CPU can be set to x86-64-v3, which will produce binaries that run on most modern CPUs. The target CPU may be changed by adding -C target-cpu=<CPU> to RUSTFLAGS.

PEXT bitboards are a faster variant of the magic bitboard algorithm used by cozy-chess. PEXT bitboards rely on an intrinsic introduced in the BMI2 CPU extension. However, it is not enabled by default, as PEXT bitboards are slower on AMD CPUs prior to Zen 3, which implement PEXT with microcode. PEXT bitboards can be enabled through the pext feature.

A note on UCI parsing

In order to support Chess960, cozy-chess uses a king-captures-rook castling notation incompatible with the standard castling representation used by the UCI protocol. This is a common use case, so the cozy_chess::util module provides helpers that automatically parse and convert between the formats.

Examples

Basic example

// Start position
let board = Board::default();
let mut move_list = Vec::new();
board.generate_moves(|moves| {
    // Unpack dense move set into move list
    move_list.extend(moves);
    false
});
assert_eq!(move_list.len(), 20);

Get capture moves in bulk

// Parse position from FEN
let board = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1"
    .parse::<Board>()
    .unwrap();

let mut total_moves = 0;
let mut total_captures = 0;

let enemy_pieces = board.colors(!board.side_to_move());
board.generate_moves(|moves| {
    let mut captures = moves.clone();
    // Bitmask to efficiently get all captures set-wise.
    // Excluding en passant square for convenience.
    captures.to &= enemy_pieces;

    total_moves += moves.len();
    total_captures += captures.len();
    false
});

assert_eq!(total_moves, 48);
assert_eq!(total_captures, 8);

Perft example

A perft implementation exists in cozy-chess/examples/perft.rs:

$ cargo run --release --example perft -- 7
   Compiling cozy-chess v0.3.0
    Finished release [optimized] target(s) in 6.37s
     Running `target\release\examples\perft.exe 7`
3195901860 nodes in 10.05s (318045465 nps)

Changelog

v0.3.4

Added

  • Added helper methods for handling UCI moves.
  • Added Square::relative_to to get a square relative to some color.

v0.3.3

Added

  • Added setters for the halfmove clock and fullmove number fields.

Fixed

  • Fixed checkmate not taking precedence over 50 move rule draw.
  • Fixed possible overflows on halfmove clock and fullmove number.

v0.3.2

Fixed

  • Fixed bug where en passant was not correctly validated when parsing and building Boards.

v0.3.1

Fixed

  • Fixed bug where Board::is_legal said castles while in check were legal.

v0.3.0

Added

  • Added methods for obtaining Chess960 start positions from their Scharnagl number.
  • Added PEXT bitboards using the BMI2 PEXT intrinsic. Potentially faster than the default algorithm. Enable using the pext feature.
  • Added Board::hash_without_ep method for fast equivalence checks excluding the en passant square.
  • Added Board::same_position to check if two boards are equivalent under FIDE rules.
  • Added Board::colored_pieces, a shorthand for board.colors(color) & board.pieces(piece).
  • Added BitBoard::is_subset, BitBoard::is_superset, and BitBoard::is_disjoint.

Changed (breaking)

  • BitBoards now operate in a more set-wise manner instead of acting like a u64. Bit operators changed to match set operators.
  • BitBoard::popcnt renamed to BitBoard::len for consistency with other data structures.
  • BoardBuilder's fullmove_number field changed to a u16 for usability reasons.
  • Board's FromStr implementation now parses both FEN and Shredder FEN.

Removed (breaking)

  • BitBoard no longer implements Iterator directly.
  • Sliding move functions are no longer const by default; Use the const variants if required.
  • Unnecessary "try" variants on Board removed; The risk of panicking is accepted when *_unchecked methods are called.

Fixed

  • Overflow bug in Square::try_offset fixed.
  • FenParseError is no longer unnameable.
  • Fixed incorrect errors being returned in FEN parsing.
  • Fixed some errors not being produced in FEN parsing.

cozy-chess's People

Contributors

analog-hors avatar karelpeeters avatar minuskelvin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cozy-chess's Issues

Support UCI castling notation

cozy-chess uses the 960 notation for castling, which breaks UCI engines and cutechess.

For example, the position "r1b1k2r/ppp1n1pp/4p3/3qNp2/3P4/2P3N1/PP2QPPP/R2R2K1 b kq - 1 15" generates "e8h8" as its castling move instead of "e8g8".

It should be possible to configure cozy-chess to generate UCI castling moves.

Generating en passant capture

Hello,
In the documentation this example is provided to generate captures:

let enemy_pieces = board.colors(!board.side_to_move());
board.generate_moves(|moves| {
        let mut captures = moves.clone();
        captures.to &= enemy_pieces;
        false
});

It also points out that En Passant captures are excluded. Is there a way to generate them and if so, how?
Thank you for your time and great working crate.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.