【发布时间】:2018-12-02 17:49:31
【问题描述】:
我正在编写国际象棋游戏,但无法检查移动是否有效。
长话短说,我得到了具有
的 Pawn(扩展 Piece)类 //First element of array represents row, second element of array represents column
Set<int[]> legalMoves = new HashSet<>();
void initLegalMoves() {
if(color == PieceColor.WHITE) {
legalMoves.add(new int[] {-1, 0});
} else {
legalMoves.add(new int[] {1, 0});
}
}
现在我得到了另一个类MoveValidator,显然它会检查移动是否有效。
private boolean isLegalMove(int oldRow, int oldColumn, int newRow, int newColumn){
int rowDifference = newRow - oldRow;
int columnDifference = newColumn - oldColumn;
board.getSelectedTile().getPiece().getLegalMoves().forEach(x -> {
if(x[0] == rowDifference && x[1] == columnDifference){
System.out.println("Ok move");
}
});
return board.getSelectedTile().getPiece().getLegalMoves().contains(new int[] {rowDifference, columnDifference});
}
虽然它似乎不起作用,但返回值始终为 false。其余代码似乎相关,forEach 当移动确实可以时,我在打印“Ok move”之前放置。我可以用一些Iterator 和for loops 来实现我想要的,但是为什么contains 总是返回false?我是否需要覆盖equals() 我想这样检查的课程?不能为int[] 这样做,对吧?
另一方面,我可以像打印值一样使用 lambda 和 forEach。不过,我不能简单地将return true 放在if statement 中...
【问题讨论】: