Implemented checkmate and stalemate detection
This commit is contained in:
parent
d9573f59da
commit
eb38fefcd1
@ -55,14 +55,14 @@ public class Board {
|
||||
Piece capturePiece = move(move);
|
||||
|
||||
// Revert move if it caused a check for its team
|
||||
if (checkCheck(piece.getColor()) != GameEventType.NONE) {
|
||||
if (checkCheck(piece.getColor())) {
|
||||
revert(move, capturePiece);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Detect check on the opposite team
|
||||
// Detect check and stalemate on the opposite team
|
||||
Color oppositeColor = piece.getColor().opposite();
|
||||
GameEventType eventType = checkCheck(oppositeColor);
|
||||
GameEventType eventType = getGameEventType(oppositeColor);
|
||||
if (eventType != GameEventType.NONE) notifyListeners(new GameEvent(this, eventType, oppositeColor));
|
||||
|
||||
return true;
|
||||
@ -121,18 +121,21 @@ public class Board {
|
||||
return get(pos).getMoves(pos);
|
||||
}
|
||||
|
||||
public GameEventType checkCheck(Color color) {
|
||||
public boolean checkCheck(Color color) {
|
||||
for (int i = 0; i < 8; i++)
|
||||
for (int j = 0; j < 8; j++) {
|
||||
Position pos = new Position(i, j);
|
||||
if (get(pos) != null && get(pos).getColor() != color
|
||||
&& get(pos).isValidMove(new Move(pos, kingPos.get(color))))
|
||||
return GameEventType.CHECK;
|
||||
// TOOD: Checkmate detection
|
||||
// return getMoves(kingPos.get(color)).isEmpty() ? GameEventType.CHECKMATE :
|
||||
// GameEventType.CHECK;
|
||||
return true;
|
||||
}
|
||||
return GameEventType.NONE;
|
||||
return false;
|
||||
}
|
||||
|
||||
public GameEventType getGameEventType(Color color) {
|
||||
return checkCheck(color)
|
||||
? getMoves(kingPos.get(color)).isEmpty() ? GameEventType.CHECKMATE : GameEventType.CHECK
|
||||
: getMoves(color).isEmpty() ? GameEventType.STALEMATE : GameEventType.NONE;
|
||||
}
|
||||
|
||||
public void registerGameEventListener(GameEventListener listener) {
|
||||
|
@ -33,6 +33,6 @@ public class GameEvent extends EventObject {
|
||||
public Color getColor() { return color; }
|
||||
|
||||
public static enum GameEventType {
|
||||
CHECK, CHECKMATE, STALEMENT, NONE;
|
||||
CHECK, CHECKMATE, STALEMATE, NONE;
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ import java.util.List;
|
||||
import dev.kske.chess.Board;
|
||||
import dev.kske.chess.Move;
|
||||
import dev.kske.chess.Position;
|
||||
import dev.kske.chess.event.GameEvent.GameEventType;
|
||||
|
||||
/**
|
||||
* Project: <strong>Chess</strong><br>
|
||||
@ -29,7 +28,7 @@ public abstract class Piece {
|
||||
for (Iterator<Move> iterator = moves.iterator(); iterator.hasNext();) {
|
||||
Move move = iterator.next();
|
||||
Piece capturePiece = board.move(move);
|
||||
if (board.checkCheck(getColor()) != GameEventType.NONE)
|
||||
if (board.checkCheck(getColor()))
|
||||
iterator.remove();
|
||||
board.revert(move, capturePiece);
|
||||
}
|
||||
|
Reference in New Issue
Block a user