首页 文章

Java Chess:检查检查中的玩家是否工作不正常的方法

提问于
浏览
0

这是我用Java编写的国际象棋游戏的粗略设置 . 有四个主要对象:

Board:2d数组(8 x 8)Square对象Square:有颜色,整数高度,整数宽度和棋子对象棋子:所有类型的棋子继承自此(例如Rook,Bishop等)玩家:现在只是有一个色域(哪些是他们的)

我正在尝试在我的Board类中编写一个方法来检查给定的玩家是否在检查中(给定了当前的棋盘状态) .

这是我的尝试:

public boolean isInCheck(Player candidatePlayer) {

    String candidateColor = candidatePlayer.getColor();

    //get opposite color of candidatePlayer
    String oppositeColor = candidateColor.equals("w") ? "b" : "w";

    //loop through squares
    for (int i = 0; i < myBoard.length; i++) {
        for (int j = 0; j < myBoard[i].length; j++) {
            //if current square not empty
            if (! myBoard[i][j].isEmpty()) {
                //if piece at current square is opposite color of candidate player
                if (! myBoard[i][j].getPiece().getColor().equals(oppositeColor)) {
                    //if piece's current legal squares moves contains square of candidatePlayer's king
                    if (candidateColor.equals("w")) {
                        if (myBoard[i][j].getPiece().getLegalDestinationSquares(myBoard[i][j]).contains(whiteKingSquare)) {
                                return true;
                        }
                    } else {
                        if (myBoard[i][j].getPiece().getLegalDestinationSquares(myBoard[i][j]).contains(blackKingSquare)) {
                            return true;
                        }
                    }
                }   
            }
        }
    }
    return false;
}

我已经设置了我的棋盘,以便在黑王面前没有棋子(坐标[1] [4]为空)并且在e2上有一个白色的女王(坐标[6] [4]) .

知道为什么这可能会返回false吗?我很确定我的“getLegalDestinationSquares”方法已经正确编写(但如果您认为可能是问题,我很乐意发布) .

谢谢!

1 回答

  • 1

    我觉得你错了!在

    //if piece at current square is opposite color of candidate player
    if (! myBoard[i][j].getPiece().getColor().equals(oppositeColor)) {
    

    所以你实际上检查具有候选人颜色的碎片 . 将其更改为:

    if (myBoard[i][j].getPiece().getColor().equals(oppositeColor)) {
    

相关问题