Giter VIP home page Giter VIP logo

chess-challenge's Introduction

Chess Coding Challenge (C#)

Welcome to the chess coding challenge! This is a friendly competition in which your goal is to create a small chess bot (in C#) using the framework provided in this repository. Once submissions close, these bots will battle it out to discover which bot is best!

I will then create a video exploring the implementations of the best and most unique/interesting bots. I also plan to make a small game that features these most interesting/challenging entries, so that everyone can try playing against them.

Submissions are now closed

Thank you so much to everyone who participated -- in total, 636 chess bots were submitted. Also, a huge extra thanks to everyone who contributed code, reported bugs in the framework (sorry about those!), and gave their time to help others getting started with the intricacies of chess programming.

The results video is now out over here. And the tournament data can be found here.

Change Log

It has been necessary to make some bug fixes to the original project, and I've also been tempted (by some great suggestions from the community) into making a few non-breaking improvements/additions to the API. I realize that changes can be frustrating during a challenge though, and so will commit to freezing the API from August 1st.

  • V1.1 Fixed major bug affecting board.GetPiece() and PieceList functions. Added Board.CreateBoardFromFEN().
  • V1.11 UI changes: Added coordinate names to board UI and fixed human player input bug.
  • V1.12 Small fixes to board.IsDraw(): Fifty move counter is now updated properly during search, and insufficient material is now detected for lone bishops on the same square colour.
  • V1.13 Fixed issue with board.ZobristKey where value would sometimes be different after making and undoing a move. Added an alternative function for getting moves board.GetLegalMovesNonAlloc() (see docs for more info).
  • V1.14 A handful of additions to the Board API: board.IsInsufficientMaterial(), board.IsRepeatedPosition(), board.GameRepetitionHistory, board.FiftyMoveCounter, board.GameMoveHistory, board.GameStartFenString.
  • V1.15 Fixed incorrect move.CapturePieceType for en-passant moves and moves in board.GameMoveHistory. Added BitboardHelper.VisualizeBitboard() to help with debugging bitboards.
  • V1.16 Added timer.GameStartTimeMilliseconds, timer.OpponentMillisecondsRemaining, board.ForceSkipTurn().
  • V1.17 Added BitboardHelper.GetPieceAttacks() and optimized board.SquareIsAttackedByOponent(). Writing #DEBUG in a comment will now exclude code in that line from counting towards the token limit (for testing only of course).
  • V1.18 Added timer.IncrementMilliseconds (this will be 0 for the main tournament, but a small increment may be used in the final playoff games). Fixed a bug in the repetition handling, and optimized check/stalemate detection.
  • V1.19 Fixed potential out of bounds exception. Fixed bug in stalemate detection.
  • V1.20 Fixed (another) bug in the repetition detection.

[There will be no API changes after August 1]

How to Participate

  • Install an IDE such as Visual Studio.
  • Install .NET 6.0
  • Download this repository and open the Chess-Challenge project in your IDE.
  • Try building and running the project.
    • If a window with a chess board appears — great!
    • If it doesn't work, take a look at the FAQ/troubleshooting section at the bottom of the page. You can also search the issues page to see if anyone is having a similar issue. If not, post about it there with any details such as error messages, operating system etc.
  • Open the MyBot.cs file (located in src/MyBot) and write some code!
    • You might want to take a look at the Documentation first, and the Rules too!
  • Build and run the program again to test your changes.
    • For testing, you have three options in the program:
      • You can play against the bot yourself (Human vs Bot)
      • The bot can play a match against itself (MyBot vs MyBot)
      • The bot can play a match against a simple example bot (MyBot vs EvilBot).
        You could also replace the EvilBot code with your own code, to test two different versions of your bot against one another.
  • Once you're happy with your chess bot, head over to the Submission Page to enter it into the competition.
    • You will be able to edit your entry up until the competition closes.

Rules

  • You may participate alone, or in a group of any size.
  • You may submit a maximum of two entries.
    • Please only submit a second entry if it is significantly different from your first bot (not just a minor tweak).
    • Note: you will need to log in with a second Google account if you want submit a second entry.
  • Only the following namespaces are allowed:
    • ChessChallenge.API
    • System
    • System.Numerics
    • System.Collections.Generic
    • System.Linq
      • You may not use the AsParallel() function
  • As implied by the allowed namespaces, you may not read data from a file or access the internet, nor may you create any new threads or tasks to run code in parallel/in the background.
  • You may not use the unsafe keyword.
  • You may not store data inside the name of a variable/function/class etc (to be extracted with nameof(), GetType().ToString(), Environment.StackTrace and so on). Thank you to #12 and #24.
  • If your bot makes an illegal move or runs out of time, it will lose the game.
    • Games are played with 1 minute per side by default (this can be changed in the settings class). The final tournament time control is TBD, so your bot should not assume a particular time control, and instead respect the amount of time left on the timer (given in the Think function).
  • Your bot may not use more than 256mb of memory for creating look-up tables (such as a transposition table).
  • If you have added a constructor to MyBot (for generating look up tables, etc.) it may not take longer than 5 seconds to complete.
  • All of your code/data must be contained within the MyBot.cs file.
    • Note: you may create additional scripts for testing/training your bot, but only the MyBot.cs file will be submitted, so it must be able to run without them.
    • You may not rename the MyBot struct or Think function contained in the MyBot.cs file.
    • The code in MyBot.cs may not exceed the bot brain capacity of 1024 (see below).

Bot Brain Capacity

There is a size limit on the code you create called the bot brain capacity. This is measured in ‘tokens’ and may not exceed 1024. The number of tokens you have used so far is displayed on the bottom of the screen when running the program.

All names (variables, functions, etc.) are counted as a single token, regardless of length. This means that both lines of code: bool a = true; and bool myObscenelyLongVariableName = true; count the same. Additionally, the following things do not count towards the limit: white space, new lines, comments, access modifiers, commas, and semicolons.

FAQ and Troubleshooting

  • What is the format of the tournament?
    • The format may change depending on the number of entries, but the current plan is to run two tournaments, with the first being a large Swiss tournament in which all bots are able to receive a ranking. These games will be played from the standard starting position. Some percengtage of the top bots will then be promoted to a second knock-out tournament, which will use a selection of different opening positions. The exact number of rounds/games and time-control are TBD.
  • Unable to build/run the project from my IDE/Code editor
    • After downloading the project and installing .Net 6.0, open a terminal / command prompt window.
    • Navigate to the folder where Chess-Challenge.csproj is located using the cd command.
      • For example: cd C:\Users\MyName\Desktop\Chess-Challenge\Chess-Challenge
    • Now use the command: dotnet run
    • This should launch the project. If not, open an issue with any error messages and relevant info.
  • Running on Linux
  • Issues with illegal moves or errors when making/undoing a move
    • Make sure that you are making and undoing moves in the correct order, and that you don't forget to undo a move when exiting early from a function for example.
  • How to tell what colour MyBot is playing
    • You can look at board.IsWhiteToMove when the Think function is called
  • GetPiece() function is giving a null piece after making a move
    • Please make sure you are using the latest version of the project, there was a bug with this function in the original version
  • There is a community-run discord server over here.
  • There is also an unofficial live leaderboard created by a member of the community (source code available here).

chess-challenge's People

Contributors

an-inconspicuous-semicolon avatar ernestoyaquello avatar gamma-delta avatar joshuajeschek avatar laurirasanen avatar seblague 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chess-challenge's Issues

Some error I am unable to fix

Chess-Challenge\src\Framework\Application\Core\ChallengeController.cs(208,57,208,62): 
error CS7036: There is no argument given that corresponds to the required parameter 'isWhitePlayer' of 'MyBot.MyBot(bool)'
ChessPlayer CreatePlayer(PlayerType type)
{
            return type switch
            {                                            ∀ ∀ ∀ ∀ 
                PlayerType.MyBot => new ChessPlayer(new MyBot(), type, GameDurationMilliseconds),
                PlayerType.EvilBot => new ChessPlayer(new EvilBot(), type, GameDurationMilliseconds),
                _ => new ChessPlayer(new HumanPlayer(boardUI), type)
            };
 }

I have no idea what to do to fix this
Error is at (∀) On MyBot()

Game pieces are not visible when program runs

I started running the program and the game piece images are just not there.
It seems like it otherwise work, but it is rather hard to infer what adjustments need to be done in order to make my bot better.
Thank you in advance.

Disabling token counter to remove the pause on start

Checking memory requirements at the start adds quite a long pause between trials, which I don't need right now.

I tried going into places like TokenCounter.cs and making it return 0 immediately but the pause persists.

Can you use nameof to load stored data

So can i use nameof? For example, i can have multible arrays worth of data stored in just a few tokens for defining a variable. And in the first round i load it into memory.

Unity port ?

I am more comfortable using unity(for debugging and development) and plan to port the project to unity , since its c# the mybot.cs will also be playable in the normal framework .Is anyone else interested?

Unable to resolve Raylib-cs dep using Rider IDE

I tried to install it through the dotnet cli but it says that no version 4.5.0.2 of Raylib-cs matches net6.0:

Chess-Challenge.csproj: [NU1100] Unable to resolve 'Raylib-cs (>= 4.5.0.2)' for 'net6.0'.

System.NullReferenceException: 'Object reference not set to an instance of an object.' PieceLists is missing some entries

Hi, just got System.NullReferenceException: 'Object reference not set to an instance of an object.' Looks like it rarely happens, but just in case I documented the stack trace here:
System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=Chess-Challenge StackTrace: at ChessChallenge.Chess.Board.MovePiece(Int32 piece, Int32 startSquare, Int32 targetSquare) in C:\Users\e.schwass\Source\Repos\Chess-Challenge\Chess-Challenge\src\Framework\Chess\Board\Board.cs:line 114 at ChessChallenge.Chess.Board.MakeMove(Move move, Boolean inSearch) in C:\Users\e.schwass\Source\Repos\Chess-Challenge\Chess-Challenge\src\Framework\Chess\Board\Board.cs:line 143 at ChessChallenge.Application.ChallengeController.PlayMove(Move move) in C:\Users\e.schwass\Source\Repos\Chess-Challenge\Chess-Challenge\src\Framework\Application\Core\ChallengeController.cs:line 256 at ChessChallenge.Application.ChallengeController.Update() in C:\Users\e.schwass\Source\Repos\Chess-Challenge\Chess-Challenge\src\Framework\Application\Core\ChallengeController.cs:line 366 at ChessChallenge.Application.Program.Main() in C:\Users\e.schwass\Source\Repos\Chess-Challenge\Chess-Challenge\src\Framework\Application\Core\Program.cs:line 40

image

What is meant by "tokens"?

I find it weird that the term "token", being the core of the whole challenge, was almost not explained in the description or the video.
It is not a sort of a widely-accepted term, is it? What does it include except for the names of variables/functions/classes?

  • colons and semicolons
  • commas and points
  • brackets and braces
  • mathematical operators (+, -, *, /, =, +=, -=, *=, /=, etc)
  • bitwise operators (&, |, >>, <<, etc.)
  • logical operators (&&, ||, !)
  • declarations of types that include several "names" such as: List, int[], List< List < float > >, etc.
  • keywords (for, foreach, if-else if-else, return, private/public, static, class/struct etc.)
  • and so on...

I think it would be correct to state explicitly what is considered a "token", or at least provide a link to the definition that is used.

Issue With Running The Program

So i just opened the program and when i try to run it it says "Please select a valid startup item!" its first time running vs on my new laptop so idk what i am doing.
Thanks.
image
It just says this

Tournament on own implementation(s)

Is there an easy way to automatically pit a set of implementations against each other and evaluate them, other than manually changing the implementation of EvilBot each time?

Constructing a Board

It may be useful to have a documented method for constructing an arbitrary board, perhaps from a string where each character represents a square and each rank is represented by a line. Is this in the cards?

Rules dont ban functions like nameof() for storing data.

A string that is constructed using "" has a token-count that depends on its size. I would assume that this is done to avoid freely storing lots of data.

This token cost can be avioded by putting your data in the name of a function, and then returning nameof() within that funtion.

Clarification on the match

What are the tournament details?
Is it all x all? Is it by brackets? Do you get white and black vs your opponent or not necessarily? Do all positions start from initial position, or are other preset positions?

XML debugging

VS code says I "have no extension for debugging XML" does anyone know which extension I should download to solve this issue?

Error cs0568 is making me unable to build the project

As i said in the title the error is making me unable to build due to the "public Move()" not allowing itself to be null or something to quote exactly its "structs cannot contain explicit parameterless constructors". im not entirely sure as im not used to developing in c# except some basics in unity so im unsure of what to do. i read that i might have to update to c# 10+ but i want to make sure first.

Moved piece becomes Null when using board.MakeMove()

I made a simple eval script to add up the values of the pieces but for some reason the piece that just moved becomes a null piece
image
image
As you can see here one of the White Knights becomes a Null
I used this code:

int eval = 0;
board.MakeMove(move);

foreach (PieceList piecelist in board.GetAllPieceLists())
{
    foreach (Piece piece in piecelist)
    {
        eval += pieceValues[(int)piece.PieceType]*(isWhite == piece.IsWhite ? 1 : -1);
        Console.WriteLine(piece.ToString() + " : " + pieceValues[(int)piece.PieceType]*(isWhite == piece.IsWhite ? 1 : -1));
    }
}

board.UndoMove(move);

Mention time limit in the rules

The rules currently mention no execution time limit for the bots.
The program itself shows a 1 minute per side per game limit, but this should likely be included in the rules as well.

Arbiter.InsufficientMaterial is incomplete

In Arbiter.InsufficientMaterial, it doesn't take into account the case where there are only 2 bishops remaining and they are both on the same color complex(whether they are white or black pieces does not matter, the game is still drawn)

Limit for memory allocation

Is there going to be a limit on how much data You can allocate during the game for things like a transposition table?

Unable to resolve Raylib-cs

I am not too familiar with C#, so maybe this has an easy fix. But, after installing .NET 6.0, when building the project in Rider, it is unable to resolve Raylib-cs for .NET 6.0.

Chess-Challenge.csproj: [NU1100] Unable to resolve 'Raylib-cs (>= 4.5.0.2)' for 'net6.0'.

Does GetLegalMoves() check for checks?

Does the GetLegalMoves() method check if the king is in check? Because my Bot only picks moves out of the GetLegalMoves() array and made an illegal move, because it tried to move something else while to king was in check. (And no the move did not resolve the check)

Piece Lists not correctly updated after MakeMove()

Am I missing something?

I'm trying to get at the piece lists after making a move but they don't seem to be updated.

I've boiled it down to the following simple example.

    public Move Think(Board board, Timer timer)
    {
        var from = new Square(0, 1);
        var to = new Square(0, 2);
        var moveString = $"{from.Name}{to.Name}";
        var move = new Move(moveString, board);
        board.MakeMove(move);

        var originalLocation = board.GetPiece(from);
        var newLocation = board.GetPiece(to);
        var allPieces = board.GetPieceList(PieceType.Pawn, true);

        Debug.Assert(allPieces.All(p => p.IsPawn)); // Fails, first "pawn" is null
        Debug.Assert(originalLocation.IsNull); // Fails still has the Pawn in it set to true
        Debug.Assert(!newLocation.IsNull);    // Fails, IsNull is true instead of IsPawn

        board.UndoMove(move);
        return move;
    }

Chess board not working


image_2023-07-21_170319493

my chess board looks like this for some reason and i dont think its suppose to be like that

How do I use the TargetsSquare?

targetsquare.TargetSquare();

It gives me Non-invocable member 'name' cannot be used like a method.
So how do I use it then

(I am sorry if this is a really simple question, but I have never programed anything in C#)

You can store unbounded data in identifiers

You can still store arbitrary data in identifiers, then retrieve it by calling the function and having it extract the stacktrace. Something like this would probably work:

String _Xfoobar_X() { return Environment.StackTrace.Split("_X")[1]; }
String theData() { return _Xfoobar_X(); }

Lambdas Reduce Brain Capacity by 1 vs Return Statements

public Move Think(Board board, Timer timer) => board.GetLegalMoves()[0];
results in 24 Bot Brain Capacity
public Move Think(Board board, Timer timer) { return board.GetLegalMoves()[0]; }
results in 25 Bot Brain Capacity

Both return a value and have the same content, but using a return statement is penalized.

Some illegal moves crash the game, some dont

If I make a move out of the chessboard (such as "a8a9"), the game throws an error and crashes, while for an illegal move "a8b7" (rook to move diagonally) the console just prints out Game over and the program doesn't crash. This could be an issue in the final tournament?

How do you know which side your bot is on?

I see methods in the API that allow you to check if a piece is white or black, but how do you know which side your bot is playing at a given moment? I'm looking for a bool isPieceMyPiece(Square s) kind of method. Did I just overlook something, or does this functionality not exist?

choosing illegal moves

it would be possible to look through all the pieces on the board and just choose a move (that isn't legal) that removes the opponents queen or one of their rooks.
the rules also do not state that this is not allowed.

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.