mercredi 28 novembre 2018

C# calculate + display possible knight positions chessboard

I'm currently trying to make a chessboard of 8x8. I want to randomly generate a position for my knight. After that i want to show all possible moves the knight can make.

I've managed to make it work if all possible positions are in the chessboard matrix. When one of the positions isn't in the matrix however the program does weird things. It's shows possible positions that should not be possible. Sometimes it even gives a error saying that the position is out of bounds.

I think my if statements are wrong. Can't see what's wrong.

This is my code:

        void PossibleKnightMoves(int[,] chessboard, Position position)
    {
        for (int row = -2; row <= 2; row+=4)
        {
            for (int col = -1; col <=1; col+=2)
            {
                if (row >= chessboard.GetLength(0) || row <0 || col >= chessboard.GetLength(1) || col < 0)
                {
                    continue;
                }
                if (row < chessboard.GetLength(0) && row >= 0 && col < chessboard.GetLength(1) && col >= 0)
                {
                    chessboard[position.col + row, position.row + col] = 2;
                    chessboard[position.col + col, position.row + row] = 2;
                }

            }

        }
    }

Kind regards,

Lorenzo.

Aucun commentaire:

Enregistrer un commentaire