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

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).

2

u/morhp Professional Developer Jan 12 '20

I believe this is less a java problem and more a chess problem.

King proximity works in a way that kings may not enter the 3x3 grid around the other king, it doesn't matter that the other king may not be able to move to one of these squares because of check.

Also this would be much simpler by simulating the move and testing that the king can't be in check after that. Note that this applies to all moves, not just king moves. You can't move a pawn if that would cause the opponent's bishop to gets in "sight" of your king for example.

2

u/jasonthorpe Jan 13 '20

I agree, you can't mix checking for a valid square and checking to see if the move puts you in check in the same function

You need to find all the valid moves, and then see which one places the player in check. Then you can remove those squares from the valid moves list.

1

u/thomasjjc Jan 12 '20

Maybe you should let the move that captures the king happen. It's a hyptothetical move only anyway. But then when the search algorithm makes the score for the resulting board, you should treat it as a win for the opposing player. That way that move should never be considered as a good move (and if all possible moves result in a win for the opposing player, your AI can give up an tell your player that he won).

That's how I did it in my Java chess engine.

1

u/morhp Professional Developer Jan 12 '20

I believe OP wants to create a chess game (with complete rules), not just an ai/engine. For an engine, your approach night be fine, but you should handle the case than the AI tries to make an illegal move.