所以我一直在从事国际象棋游戏,每个棋子都生成正确的棋局,但是当我浏览游戏时,最终会删除不正确的棋局。
例如,在这种特殊情况下,国王在c4受到主教的检查。为了逃避检查,大写玩家应该能够将dawn移至d7-d5,但是返回的只是国王的动作。我的代码中的逻辑可能不正确。
A B C D E F G H
8 R N B Q # B N R 8
7 P P P P _ K P P 7
6 # _ # _ # _ # _ 6
5 _ # _ # q # _ # 5
4 # _ b _ p _ # _ 4
3 _ # _ # _ # _ # 3
2 p p p p # p p p 2
1 r n b # k # _ r 1
A B C D E F G H
在游戏代码段中移动生成
ChessBoard testBoard;
HashSet<ChessMove> initialMoves = new HashSet<>(), kingMoves;
menu();
Boolean inCheck = false;
while (true) {
testBoard = board.clone();
initialMoves.addAll(board.generateMoves( currentPlayer ));
initialMoves = testBoard.removeBadMoves(initialMoves, currentPlayer);
kingMoves = testBoard.kingMoves(currentPlayer);
initialMoves.addAll(kingMoves);
if (inCheck) {
if (board.checkWin(currentPlayer)) {
System.out.println( "Checkmate!" );
playerWins( currentPlayer );
break;
}
System.out.println( "Check!" );
}
生成,测试,删除移动和检查玩家的操作
HashSet<ChessMove> generateMoves(Player player) {
HashSet<ChessMove> moves = new HashSet<>();
if (player.getColor().equals(Colors.WHITE)) {
for (ChessPiece each : whitePieces) {
moves.addAll(each.addMoves(this));
}
} else if (player.getColor().equals(Colors.BLACK)){
for (ChessPiece each : blackPieces) {
moves.addAll(each.addMoves(this));
}
}
return moves;
}
private boolean testMove(ChessMove each, Player player) {
this.performMove(player, each);
return !this.playerInCheck(player);
}
HashSet<ChessMove> removeBadMoves(HashSet<ChessMove> moves, Player player) {
HashSet<ChessMove> newMoves = new HashSet<>();
for (ChessMove each : moves) {
if (testMove(each, player)) {
if (each.castle) {
if (!playerInCheck(player)) {
newMoves.add(each);
}
}else{
newMoves.add(each);
}
}
}
return newMoves;
}
任何可能的帮助都非常好,如果我没有提供足够的信息,对不起。我很高兴添加任何需要的额外内容。