C# – What would be the fastest way of storing or calculating legal move sets for chess pieces

cchessgame development

For example if a move is attempted I could just loop through a list of legal moves and compare the x,y but I have to write logic to calculate those at least every time the piece is moved.

Or, I can store in an array [,] and then check if x and y are not 0 then it is a legal move and then I save the data like this
[0][1][0][0] etc etc for each row where 1 is a legal move, but I still have to populate it.

I wonder what the fastest way to store and read a legal move on a piece object for calculation.

I could use matrix math as well I suppose but I don't know.

Basically I want to persist the rules for a given piece so I can assign a piece object a little template of all it's possible moves considering it is starting from it's current location, which should be just one table of data. But is it faster to loop or write LINQ queries or store arrays and matrices?

public class Move
{
    public int x;
    public int y;
}

public class ChessPiece : Move
{    
    private List<Move> possibleMoves { get; set; }

    public bool LegalMove(int x, int y){
      foreach(var p in possibleMoves)
      {
         if(p.x == x && p.y == y)
         {  return true;  }   
      }
    }
}

Anyone know?

Best Answer

Figuring out the legal moves available for a particular piece on a chess board in a particular chess position is very situational, especially when considering pawns...1 space except when it is on its starting position, then two, and then throw in captures and en passant captures...so building an array of moves that are "mechanically" possible is a bit hairy to start. In the case of en passant, you even need to know whether the opponents last move enabled en passant, as the move is only valid for one move after the opponent made a move to enable it.

Then it gets further complicated by other situational considerations. Does the move expose the player's king to check? For castling, will the king have to move through check (whether final position results in check or not)? If the king is already in check, does the move counter the check?

I think you would be best off to set up rules for each piece including special considerations, direction and distance, rather than an array to step through, since you literally have to determine where the piece is designed to go, then examine whether the position after it goes there will be legal.