public class ChessGame {
// ...private boolean isValidMove(Move move) {
Position from = move.getFrom();
Position to = move.getTo();
Piece piece = board.getPieceAt(from);// 检查起始位置是否有棋子
if (piece == null) {
return false;
}// 检查是否轮到该玩家移动棋子
if (piece.getColor() != currentPlayer.getColor()) {
return false;
}// 检查移动是否在合法范围内
if (!piece.isValidMove(from, to, board)) {
return false;
}// 检查移动是否导致玩家处于将军状态
if (isInCheckAfterMove(from, to)) {
return false;
}// 其他检查(例如遵守吃子规则)
return true;
}private boolean isInCheckAfterMove(Position from, Position to) {
// 创建一个临时棋盘,模拟移动棋子
Board tempBoard = new Board(board);
tempBoard.makeMove(new Move(from, to));// 检查当前玩家是否处于将军状态
Color opponentColor = (currentPlayer == whitePlayer) ? Color.BLACK : Color.WHITE;
Position kingPosition = tempBoard.getKingPosition(currentPlayer.getColor());return tempBoard.isSquareAttacked(kingPosition, opponentColor);
}
// ...private void displayResult() {
// ...// 检查是否有玩家被将死
if (isInCheckAfterMove(null, null)) {
System.out.println("将死!");
} else {
System.out.println("和棋!");
}
}
}public class Piece {
// ...public boolean isValidMove(Position from, Position to, Board board) {
// 检查移动是否在该棋子的合法范围内
// ...// 其他检查(例如遵守吃子规则)
// ...return true;
}
}public class Board {
// ...public void makeMove(Move move) {
Position from = move.getFrom();
Position to = move.getTo();
Piece piece = squares[from.getRow()][from.getColumn()];// 移动棋子
squares[to.getRow()][to.getColumn()] = piece;
squares[from.getRow()][from.getColumn()] = null;
}public boolean isSquareAttacked(Position position, Color attackerColor) {
// 检查指定位置是否受到来自指定颜色的棋子的攻击
// ...return false;
}public Position getKingPosition(Color color) {
// 获取指定颜色玩家的国王位置
// ...return null;
}
}