@@ -186,11 +186,14 @@ void ChessEngine::getPossibleMoves(const char board[8][8], int row, int col, int
186186 getPseudoLegalMoves (board, row, col, pseudoMoveCount, pseudoMoves, true );
187187
188188 // Filter out moves that would leave the king in check
189- moveCount = 0 ;
190189 for (int i = 0 ; i < pseudoMoveCount; i++) {
191190 int toRow = pseudoMoves[i][0 ];
192191 int toCol = pseudoMoves[i][1 ];
193192
193+ // A legal chess move never captures the opponent king
194+ if (toupper (board[toRow][toCol]) == ' K' )
195+ continue ;
196+
194197 // Only add this move if it doesn't leave the king in check
195198 if (!wouldMoveLeaveKingInCheck (board, row, col, toRow, toCol)) {
196199 moves[moveCount][0 ] = toRow;
@@ -417,28 +420,18 @@ bool ChessEngine::isValidSquare(int row, int col) const {
417420}
418421
419422// Move validation
420- bool ChessEngine::isValidMove (const char board[8 ][8 ], int fromRow, int fromCol, int toRow, int toCol) {
423+ bool ChessEngine::isValidMove (const char board[8 ][8 ], int fromRow, int fromCol, int toRow, int toCol, char currentTurn) {
424+ if (ChessUtils::getPieceColor (board[fromRow][fromCol]) != currentTurn)
425+ return false ;
426+
421427 int moveCount = 0 ;
422428 int moves[28 ][2 ]; // Maximum possible moves for a queen
423-
424429 getPossibleMoves (board, fromRow, fromCol, moveCount, moves);
425-
426- // First check if it's a pseudo-legal move (piece can move there according to its movement rules)
427- bool isPseudoLegal = false ;
428430 for (int i = 0 ; i < moveCount; i++)
429- if (moves[i][0 ] == toRow && moves[i][1 ] == toCol) {
430- isPseudoLegal = true ;
431- break ;
432- }
433-
434- if (!isPseudoLegal)
435- return false ; // Not even a valid move according to piece rules
431+ if (moves[i][0 ] == toRow && moves[i][1 ] == toCol)
432+ return true ;
436433
437- // Check if this move would leave the king in check (illegal move)
438- if (wouldMoveLeaveKingInCheck (board, fromRow, fromCol, toRow, toCol))
439- return false ; // Move would leave king in check
440-
441- return true ; // Move is legal
434+ return false ;
442435}
443436
444437// Check if a pawn move results in promotion
@@ -655,4 +648,4 @@ bool ChessEngine::isInsufficientMaterial(const char board[8][8]) const {
655648 return true ;
656649
657650 return false ;
658- }
651+ }
0 commit comments