这是我用 Java 编写的国际象棋游戏的粗略设置。主要有四个对象:
板:方形对象的二维数组 (8 x 8) 正方形:具有颜色、整数高度、整数宽度和 block 对象 棋子:所有类型的棋子都继承于此(例如车、主教等) 玩家:现在只有一个色域(哪些棋子是他们的)
我正在尝试在 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”方法已正确编写(但如果您认为这可能是问题所在,很乐意发布该方法)。
谢谢!
最佳答案
我认为你放错了!在
//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)) {
关于Java国际象棋 : Method to check if player in check not working properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935208/