DavidZalewski / chess

chess in dos format
0 stars 0 forks source link

Optimize ChessExplorer for depth 7 - Strategy #2 - ChessPiece calculates its own moves. #7

Open DavidZalewski opened 1 week ago

DavidZalewski commented 7 hours ago

Here's a GitHub Issue Ticket for the refactoring task you described:


Refactor ChessPiece Move Validation

Description:

The current implementation of the IsCheckMate method in our chess engine uses a brute force approach to validate moves for all chess pieces. This leads to unnecessary performance overhead, especially when dealing with pieces like pawns that have limited mobility. The goal of this refactoring is to:

Current Implementation:

// ... (existing code snippet) ...

Proposed Changes:

  1. Introduce GetValidSquares(ChessBoard chessBoard) Method:

    • Add this method to the ChessPiece abstract class. Each specific piece type (like ChessPiecePawn, ChessPieceKnight, etc.) will implement this method to return a List<Square> of valid squares it can move to based on the current state of the chessboard.
  2. Refactor IsCheckMate Method:

    • Replace the brute force loop with a call to GetValidSquares for each piece. Instead of iterating over all 64 squares for each piece, we'll only check the squares returned by GetValidSquares.

    Example Refactored Code:

    public bool IsCheckMate(Turn turn, out bool isStaleMate)
    {
       StaticLogger.Trace();
       List<ChessPiece> friendlyPieces = turn.PlayerTurn.Equals(Turn.Color.WHITE)
           ? turn.ChessPieces.FindAll(piece => piece.GetColor().Equals(ChessPiece.Color.BLACK))
           : turn.ChessPieces.FindAll(piece => piece.GetColor().Equals(ChessPiece.Color.WHITE));
    
       List<Turn> possibleMoves = new();
    
       foreach (ChessPiece piece in friendlyPieces)
       {
           SpecialMovesHandlers.ByPassPawnPromotionPromptUser = true;
           SimulationService.BeginSimulation();
           foreach (Square sq in piece.GetValidSquares(turn.ChessBoard))
           {
               Turn possibleTurn = new(turn.TurnNumber + 1, piece, piece.GetCurrentPosition(), sq.Position, turn.ChessBoard);
               if (possibleTurn.IsValidTurn)
                   possibleMoves.Add(possibleTurn);
           }
           SpecialMovesHandlers.ByPassPawnPromotionPromptUser = false;
           SimulationService.EndSimulation();
       }
    
       // ... (rest of the method remains similar)
    }
  3. Testing:

    • Extend existing unit tests or add new ones to ensure that GetValidSquares returns the correct set of squares for each piece type under various board configurations.

Benefits:

Action Items:

Related Issues:


Feel free to discuss implementation details, potential pitfalls, or suggest further improvements.