【发布时间】:2015-01-14 11:11:32
【问题描述】:
这是我用 Java 编写的国际象棋游戏的粗略设置。主要有四个对象:
Board:方形对象的二维数组 (8 x 8) 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]) .
知道为什么这可能会返回错误吗?我很确定我的“getLegalDestinationSquares”方法已经正确编写(但如果您认为这可能是问题,很高兴发布)。
谢谢!
【问题讨论】:
-
I'm pretty sure my "getLegalDestinationSquares" method has been written correctly- 相当大的要求!你的调试告诉你正在发生什么? -
所以我通过放置任何相反颜色的所有合法目标方格(任何可能能够检查相关玩家的国王的棋子)进行调试。然后我循环遍历,白皇后的合法方格数组列表 does 包含黑王方格。也许 arrayList 的 .contains() 方法的工作方式与我的预期不同?
-
contains() 返回 true 当且仅当此列表包含至少一个元素 e 使得 (o==null ? e==null : o.equals(e))。检查 blackKingSquare 是否等于 arrayList 中的那个。也许你需要重写equals(),或者不使用contains(),而是写另一个方法来检查它。
标签: java