SebLague / Chess-Challenge

Create your own tiny chess bot!
https://www.youtube.com/watch?v=Ne40a5LkK6A
MIT License
1.78k stars 1.07k forks source link

'occupiedSquares' is Causing an Error #458

Closed ZachCreatesThings closed 10 months ago

ZachCreatesThings commented 10 months ago

Hello! So, I've been running into a couple of issues with my project, and I'm not sure if I'm making an error or if it's a bug. The current one is involving the 'occupiedSquares' variable within the PieceList function 'AddPieceAtSquare.' Here is a picture of it with its error.

image

Here is the code that ends up causing this.

public class MyBot : IChessBot
{
    const int SearchDepth = 3;
    bool? isWhite = null;

    public Move Think(Board board, Timer timer)
    {
        if (!isWhite.HasValue)
            isWhite = board.IsWhiteToMove;

        Move[] moves = board.GetLegalMoves();
        int bestMovePosition = MoveToMake(board);
        return moves[bestMovePosition];
    }

    int MoveToMake(Board board)
    {
        List<Data> data = new List<Data>();

        GenerateMoveData(board, data, 0);

        Random rng = new Random();
        return rng.Next(data[0].moves.Length);
    }

    void GenerateMoveData(Board board, List<Data> data, int depth)
    {
        data.Add(new Data { depth = depth, moves = board.GetLegalMoves() });

        if(depth < SearchDepth)
        {
            List<Data> currentDepthData = new List<Data>(data.Where(x => x.depth == depth));
            foreach(Data _data in currentDepthData)
            {
                foreach(Move move in _data.moves)
                {
                    if(!board.GetPiece(move.StartSquare).IsNull)
                    {
                        board.MakeMove(move);
                        GenerateMoveData(board, data, depth + 1);
                        board.UndoMove(move);
                    }
                }
            }
        }
    }

    int GetPieceValue(PieceType type)
    {
        switch(type)
        {
            case PieceType.Pawn:
                return 1;
            case PieceType.Bishop:
            case PieceType.Knight:
                return 3;
            case PieceType.Rook:
                return 5;
            case PieceType.Queen:
                return 9;
            case PieceType.King:
                return 1000;
        }

        return -1;
    }
}

class Data
{
    public int depth;
    public int score;
    public Move[] moves;
}

Before this error was happening, I had another one dealing with the 'pieceList' variable. Here is the error.

image

I was only able to get rid of it by adding the if statement you can see in my code where I say 'if(!board.GetPiece(move.StartSquare).IsNull).' That was the only way I figured out how to get rid of that error. But, unfortunately, I just have another one now. And, I'm not sure how to fix it. Any help would be greatly appreciated!

Edit: If anyone would like to see the call stack, here it is:

image