r/javahelp • • Jan 11 '20

infinite loop in chess

currently i have a design problem in my chess game, im creating a functionality with means that the king cannot moved onto tiles that are being attacked for example by a rook

so i did program this as following:

0. Lets say the king has a list of 4 valid moves

  1. I create an function(isSafeSpotForKing) that is a condition during the calculating the king moves, to ensure the position is safe

  2. this functions loops through all pieces of the opponent calculates the valid moves from the opponent

  3. Then im comparing ALL the possible moves from the opponent with the possible valid moves of mine (based on x and y coords) 3.0 if compare reach true, the move is not valid ofc 3.1 if compare reach false, the move is valid

but the problem is The opponent has a king aswell, and whenever i trigger the function, it goes to the opponent pieces ( so eventuallly the opponent king (look step 2) so black player king > white player king > black player king > white player king, creating a infinite loop xd which results in a stack overflow error

18 Upvotes

8 comments sorted by

View all comments

1

u/[deleted] Jan 11 '20

Maybe post your code(?)

2

u/poepstinktvies Jan 11 '20

calculating valid moves for king

    public ArrayList<Move> calculateValidMoves(Board board, 
   Position currentPosition) {
    ArrayList<Move> legalMoves = new ArrayList<>();
    for (Position rule : moveRules) {
        Position checkPosition = currentPosition.addPosition(rule);
        if (!board.isInBounds(checkPosition)) {
            continue;
        }

        if(board.isSafeSpotForKing(this.pieceColor, checkPosition))
        {
            continue;
        }
        if (board.IsPositionOccupied(checkPosition)) {
            var collisonPiece = board.getPieceAtBoard(checkPosition);
            if (collisonPiece.getPieceColor() == this.pieceColor) {
                continue;
            }
            legalMoves.add(new Move(currentPosition, checkPosition, this, MoveType.ATTACK));
        }
        legalMoves.add(new Move(currentPosition, checkPosition, this, MoveType.MOVE));
    }
    return legalMoves;
}

calculation of available moves of opponent ( to see if it matches with king valid moves, basically if so, then king move will be invalid, because it attacked

    public ArrayList<Move> 
    getAllAvailableMovesWithoutKing(PieceColor pieceColor){
    ArrayList<Move> availableMoves = new ArrayList<>();
    if(pieceColor == PieceColor.WHITE){
        List<Piece> opponentPieceListWithoutKing = new ArrayList<Piece>(whitePieces);
        opponentPieceListWithoutKing.removeIf(piece -> piece instanceof King);
        for(Piece piece : opponentPieceListWithoutKing){
            availableMoves = piece.calculateValidMoves(this, piece.getPosition());
        }
    }
    else {
        List<Piece> opponentPieceListWithoutKing = new ArrayList<Piece>(blackPieces);
        opponentPieceListWithoutKing.removeIf(piece -> piece instanceof King);
        for(Piece piece : opponentPieceListWithoutKing){

            availableMoves =  piece.calculateValidMoves(this, piece.getPosition());
        }
    }
    return availableMoves;
}

public boolean isSafeSpotForKing(PieceColor pieceColor, Position position){
    var opponentMoves = new ArrayList<Move>();

    if(pieceColor == PieceColor.BLACK){
        opponentMoves = getAllAvailableMovesWithoutKing(PieceColor.WHITE);
        return opponentMoves.stream()
                .anyMatch(move -> move.getDesPos().getX() == position.getX() &&
                move.getDesPos().getY() == position.getY());
    }
    else{
        opponentMoves = getAllAvailableMovesWithoutKing(PieceColor.BLACK);
        return opponentMoves.stream().anyMatch(move -> move.getDesPos().getX() == position.getX() &&
                move.getDesPos().getY() == position.getY());
    }

}

1

u/poepstinktvies Jan 11 '20

i currently implemented to remove the king in the list of the opponent, then prcoeed to calculate, but i think its dirty

1

u/leroybentley Jan 12 '20

Could you temporarily treat the King as if it were the other types of pieces? Calculate valid moves for all pieces from the King's position and then check if that type of piece exists in the destination? For example, check the Knight's "L" moves, starting on the King and see if the result is occupied by a Knight.

Also, I would suggest checking isPositionOccupied before doing the opponent moves check (It seems like checking occupied would be quicker...no need to loop through all pieces if the resulting spot is occupied).