A dependency-free chess engine library built to run anywhere.

Overview

♔chess-engine♚

A dependency-free chess engine library built to run anywhere.

Donate Open Source

Demo | Docs | Contact Me

Written in Rust 🦀 💖

Why write a Chess engine?

Above all, this video by Tom7 is my inspiration for this project. He's absolutely brilliant and I implore you to watch his content.

I love chess a lot. It's definitely one of my favorite games ever. However, I've always been disappointed when trying to write programs that play chess digitally (particularly in a compiled language). Although several amazing engines exist, it's near impossible to find a neat library for chess-related-programming that runs on everything.

chess-engine is a solution to my problem. If you want a chess engine that runs on embedded devices, the terminal, the desktop (with a gui), and the web, this is probably your best bet.

How does it work?

This particular AI (along with most other chess AIs) works using the Minimax algorithm, along with Alpha-Beta pruning for optimization.

Now, let's unpack that.

The Minimax algorithm essentially iterates through all possible moves recursively, and evaluates all of the boards after the moves are played. If the board is more favorable, it will encourage playing its parent move, but if a board is less favorable, then it will select against playing a given move.

Minimax

Additionally, when the AI attempts to see past just the current board, it will assume the human always responds with the best moves. As a result, the computer almost never blunders. This allows the computer to almost always play objectively better moves than the player.

Embedded in the Web

Because it has zero dependencies, it's extremely simple to embed in the web browser using wasm. Try playing it yourself!

Average AI Setting

Try playing it yourself!

Usage

The Board structure has a few different methods that allow users to generate moves from a given position, including get_best_next_move, get_worst_next_move, and get_legal_moves. These are particularly handy for writing chess AIs to play against.

fn main() {
    let board = Board::default();

    // Get the best move with 4 moves of lookahead
    let best_move = board.get_best_next_move(4);
    // Get the worst move with 3 moves of lookahead
    let worst_move = board.get_worst_next_move(3);

    // Get all of the possible legal moves for the given player
    let legal_moves = board.get_legal_moves();
    // Print the board
    println!("{}", board);

    print!("CPU chose to ");
    match best_move {
        Move::Piece(from, to) => println!("move {} to {}", from, to),
        Move::KingSideCastle => println!("castle kingside"),
        Move::QueenSideCastle => println!("castle queenside"),
        Move::Resign => println!("resign")
    }
}

To add some variation or more advanced play, consider writing an AI that plays known openings that build better positions before using the get_best_next_move method!

Custom Boards

Additionally, users can create their own custom Board objects other than the default one. This is done using the BoardBuilder structure. The BoardBuilder structure supports enabling and disabling castling, placing rows and columns of pieces, and placing individual pieces.

Keep in mind when using a BoardBuilder that castling is disabled by default!

Play the Horde Chess Variant

Play the Horde Chess Variant
fn main() {
    // `BoardBuilder::new()` returns an empty board
    // with castling disabled.
    // Creating a board builder from another board
    // structure will preserve
    // all settings from the board (such as castling
    // and the last en-passant move).

    // This BoardBuilder constructs the "Horde" chess variant!
    let board = BoardBuilder::from(Board::default())
            .row(Piece::Pawn(WHITE, A1))
            .row(Piece::Pawn(WHITE, A2))
            .row(Piece::Pawn(WHITE, A3))
            .row(Piece::Pawn(WHITE, A4))
            .piece(Piece::Pawn(WHITE, F5))
            .piece(Piece::Pawn(WHITE, G5))
            .piece(Piece::Pawn(WHITE, B5))
            .piece(Piece::Pawn(WHITE, C5))
            .build();

    // The CPU can also play variants!
    let cpu_move = board.get_best_next_move(3);
    
    match board.play_move(cpu_move) {
        GameResult::Continuing(next_board) => {
            println!("{}", next_board);
        }

        GameResult::Victory(winner) => {
            // You can use the ! operator on a player's
            // color to invert.
            println!("{} loses. {} is victorious.",
              !winner, winner
            );
        }

        GameResult::IllegalMove(x) => {
            eprintln!("{} is an illegal move.", x);
        }

        GameResult::Stalemate => {
            println!("Drawn game.");
        }
    }
}

About the Author

Website | Blog | GitHub

I'm a freshman in college, mainly working on side projects like these in the ~30 minute breaks between classes. If you enjoy my projects, consider supporting me by buying me a coffee!

Buy Me A Coffee
Comments
  • Chess Pieces Fail to Render on Desktop

    Chess Pieces Fail to Render on Desktop

    Tested on Windows 10, Rust Ver. 1.49.0

    Expected: Pieces actually render as shown in the example images

    Actual behavior: Pieces show up as thin white squares on the board image

    opened by BornIncompetence 2
  • Game

    Game

    Hi, great project. I used this to build a cosmwasm smart contract and needed several changes, and wanted to contribute back to the upstream. Let me know if you have any questions or suggestions

    • support non-queen promotion
    • bug fix for pawn fork (allow take up right)
    • SAN move parsing
    • FEN board state (except move counting)
    • game abstraction
    • some tests (which caught pawn bug)
    opened by jeremyfee 1
  • Nice chess engine.

    Nice chess engine.

    I willl write my own chess engine (backend) for a C# app, there is a chance I might use the code from here if I don't write it from scratch.

    Have a good day

    opened by netzeroo 1
  • Version 0.1.1 hasn't been published on crates.io

    Version 0.1.1 hasn't been published on crates.io

    Hi,

    thanks for developing this amazing engine. I was wondering why the 0.1.1 version hasn't been published on crates.io yet. I wanted to include it in my project, but I can see that only the 0.1.0 has been published https://crates.io/crates/chess-engine.

    Could you please publish version 0.1.1?

    Best regards

    opened by veeso 0
  • Multithreading for this crate

    Multithreading for this crate

    First of all, thanks for the all the hard work. This is an awesome crate. I tried to run it on my microcontroller (EK-TM4C123GXL) and it works perfectly out of the box! However, it runs quite slowly (as expected), so I am thinking of running it on a more powerful device, such as the raspberry pi pico to make use of its powerful specs, and possibly using both of its cores to compute faster so I'm creating this issue to ask if there is any pointer for me to implement multithreading for this crate? As far as I can see, I will have to basically rewrite everything related to the evaluation functions to make this work.

    opened by Rudo2204 0
  • Error: GraphicsAdapterNotFound when running chess-gui example on Ubuntu 16.04

    Error: GraphicsAdapterNotFound when running chess-gui example on Ubuntu 16.04

    $: cargo run --release --bin best
        Finished release [optimized] target(s) in 0.54s
         Running `target/release/best`
    Error: GraphicsAdapterNotFound
    

    This is the output on Ubuntu 16.04.3, with Intel HD 5300 graphics chip. Some more info:

    $: rustup show
    Default host: x86_64-unknown-linux-gnu
    rustup home:  /home/jaywalker/.rustup
    
    installed toolchains
    --------------------
    
    stable-x86_64-unknown-linux-gnu (default)
    nightly-2016-12-16-x86_64-unknown-linux-gnu
    nightly-x86_64-unknown-linux-gnu
    
    active toolchain
    ----------------
    
    stable-x86_64-unknown-linux-gnu (default)
    rustc 1.48.0 (7eac88abb 2020-11-16)
    

    I'm guessing this is due to some missing dependency because your screenshots look like you're running Ubuntu, but not sure what the dependency might be.

    opened by JayWalker512 0
  • Implement UCI protocol

    Implement UCI protocol

    https://en.m.wikipedia.org/wiki/Universal_Chess_Interface

    https://www.shredderchess.com/download.html

    As this is crate is no_std, the first step would be to implement a message parser and state machine with an API to send commands to the engine. This API can then be used to wire up to stdin/stdout for chess GUIs for example.

    opened by tom-sherman 2
A rust chess implementation using a neural network scoring function built on huggingface/candle + rust + wasm

Rusty Chess What is it? Rusty Chess aims to be a high quality embeddable chess engine that runs entirely locally in the browser (no backend required).

Gareth 3 Nov 3, 2023
Walleye is a chess engine written completely in rust.

Walleye is a UCI-compatible engine written using the classical alpha-beta style AI. It supports loading board positions from arbitrary FEN strings, Unicode pretty printing to the console, and UCI communication logs to help with debugging.

Mitchel Paulin 95 Dec 24, 2022
Blackmarlin is a chess engine fully written in Rust.

Blackmarlin WIP UCI Chess Engine Blackmarlin is a chess engine fully written in Rust. Make sure to compile the chess engine with cargo build --release

null 50 Oct 31, 2022
Stockfish/ - UCI chess engine

Overview Stockfish is a free, powerful UCI chess engine derived from Glaurung 2.1. Stockfish is not a complete chess program and requires a UCI-compat

null 7.5k Jan 8, 2023
A basic web assembly chess engine written in rust.

This library is a basic implementation of a chess min-max algorithm with alpha-beta pruning (Algorithm Info). It is designed to be compiled down to WebAssembly and used for web applications.

null 2 Nov 25, 2022
A Chess Engine written in Rust that runs natively and on the web!

About The Project chess-rs is a Chess Engine written from scratch in Rust that runs natively and on web! Live Demo: https://parthpant.github.io/chess-

Parth Pant 109 Apr 6, 2023
A Chess Engine written in Rust .

Kelp Kelp is a UCI compatible chess engine written in Rust Using standard chess algorithms. Kelp is work in progress. Currently, it can be used as a U

Gautam 5 Sep 3, 2023
Opening randomizer for Chess

chess-randomizer chess-randomizer is a simple opening randomizer written in Rust using WASM and the Lichess API. To build the project, you need Rust a

null 1 Jan 31, 2022
Yet another shape chess game in Rust.

shape_chesss_in_rust Yet another shape chess game in Rust. Why the implementation is so slow? The main reason is performance of Vector iteration is ve

Simon Lee 1 Apr 10, 2022
Play jungle chess on the linux terminal.

Jungle-Chess This is my first project written in Rust. Happy for contributors and feedback! The code is dirty. Play Jungle Chess on an Emoji-Enabled L

Arne Winter 10 Aug 9, 2022
Chess implemented entirely in the Rust and TS type systems.

Type System Chess This repo contains chess implemented entirely in the (stable) Rust and Typescript type systems. Both languages feature turing comple

null 170 Jul 12, 2023
An (experimental) chess tactics trainer with spaced repetition

better-tactics A chess tactics trainer that with spaced repetition. New puzzles will be shown to you from the lichess puzzle db, according to your cal

Caitlin Wilks 6 Oct 6, 2023
A vdom-free reactive UI lib for the bevy game engine

ui4 ui4 is my fourth major attempt at making a UI dataflow library for the Bevy game engine. More specifically, it's a vdom-less UI library which uses

null 48 Nov 28, 2022
A simple and minimal game engine library built in rust.

Neptune A brand new free, open-source minimal and compact game engine built in rust. Design Goals We plan to make Neptune a small and minimal engine,

Levitate 17 Jan 25, 2023
"putzen" is German and means cleaning. It helps keeping your disk clean of build and dependency artifacts safely.

Putzen "putzen" is German and means cleaning. It helps keeping your disk clean of build and dependency artifacts safely. About In short, putzen solves

Sven Assmann 2 Jul 4, 2022
A refreshingly simple data-driven game engine built in Rust

What is Bevy? Bevy is a refreshingly simple data-driven game engine built in Rust. It is free and open-source forever! WARNING Bevy is still in the ve

Bevy Engine 21.1k Jan 4, 2023
game engine built in rust, using wgpu and probably other stuff too

horizon game engine engine for devpty games, made in 99.9% rust and 0.1% shell. this is our main project currently. the engine will be used for most i

DEVPTY 2 Apr 12, 2022
Bevy is a refreshingly simple data-driven game engine built in Rust

What is Bevy? Bevy is a refreshingly simple data-driven game engine built in Rust. It is free and open-source forever! WARNING Bevy is still in the ve

John Winston 3 Jun 3, 2022
Minecraft-esque voxel engine prototype made with the bevy game engine. Pending bevy 0.6 release to undergo a full rewrite.

vx_bevy A voxel engine prototype made using the Bevy game engine. Goals and features Very basic worldgen Animated chunk loading (ala cube world) Optim

Lucas Arriesse 125 Dec 31, 2022