GithubHelp home page GithubHelp logo

adam-mcdaniel / chess-engine Goto Github PK

View Code? Open in Web Editor NEW
395.0 5.0 29.0 3.02 MB

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

Home Page: https://adam-mcdaniel.github.io/chess-engine/docs/book/index.html

License: MIT License

Rust 100.00%
chess ai game

chess-engine's Introduction

♔chess-engine♚

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

Donate Open Source

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

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

chess-engine's People

Contributors

adam-mcdaniel avatar bornincompetence avatar ishibi avatar jeremyfee avatar luis951 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

chess-engine's Issues

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

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

Variants

(On mobile, excuse spelling)

Do you feel that variants would be in-scope for this library?

To do this effectively, I think a generic Rule trait may be required that allows you to (de)active any arbitrary sets of rules so thst variants can be easily built and added on to without much fuss.

I understand if you beleive your library is not rhe right place for such a feature, but I'd be willing to write up a PR if you think it could work.

Let me know what you think about the idea in general and specifically about using a new Rule trait.

Thanks so much for your great work! I love it when there's no external dependencies!

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.

Pawn promotion

Is pawn promotion implemented? I can't seem to find it.

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.

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.