refactor draw

This commit is contained in:
2025-04-13 15:58:26 +02:00
parent b336784a5d
commit 8b8eb428e5
2 changed files with 31 additions and 11 deletions

View File

@@ -59,11 +59,7 @@ public class CommandExecutor {
}
private void switchPlayerTurn() {
if(this.game.switchPlayerTurn()) {
this.dispatcher.onDraw();
this.dispatcher.onGameEnd();
return;
}
this.game.switchPlayerTurn();
this.dispatcher.onPlayerTurn(this.game.getPlayerTurn());
}
@@ -75,6 +71,9 @@ public class CommandExecutor {
GameStatus gameStatus = this.game.checkGameStatus();
switch (gameStatus) {
case Draw:
this.dispatcher.onDraw();
return true;
case Check:
this.dispatcher.onKingInCheck();
return false;

View File

@@ -13,8 +13,10 @@ public class Game {
private final Stack<PlayerCommand> movesHistory;
private final Map<Color, Map<Integer, Integer>> traitsPos;
private static final int DRAW_REPETITONS = 3;
public enum GameStatus {
Check, CheckMate, OnGoing, Pat;
Draw, Check, CheckMate, OnGoing, Pat;
}
public Game(ChessBoard board) {
@@ -42,26 +44,45 @@ public class Game {
* @param color the current player turn
* @return true if a draw should be declared
*/
private boolean saveTraitPiecesPos(Color color) {
private void saveTraitPiecesPos(Color color) {
int piecesHash = this.board.hashPlayerPieces(color);
Integer count = this.traitsPos.get(color).get(piecesHash);
this.traitsPos.get(color).put(piecesHash, count == null ? 1 : count + 1);
return count == null ? false : count == (3 - 1);
}
/**
*
* @param player the trait to check
* @return true if a position is repeated DRAW_REPETITONS times
*/
private boolean checkDraw(Color player) {
return this.traitsPos.get(player).containsValue(DRAW_REPETITONS);
}
/**
* @return whether the game is in a draw situation
*/
private boolean checkDraw() {
if (checkDraw(Color.White))
return true;
return checkDraw(Color.Black);
}
/**
*
* @return true if a draw should occur
*/
public boolean switchPlayerTurn() {
boolean draw = saveTraitPiecesPos(this.playerTurn);
public void switchPlayerTurn() {
saveTraitPiecesPos(this.playerTurn);
playerTurn = Color.getEnemy(playerTurn);
return draw;
}
public GameStatus checkGameStatus() {
final Color enemy = Color.getEnemy(getPlayerTurn());
if(checkDraw())
return GameStatus.Draw;
if (this.board.isKingInCheck(enemy))
if (this.board.hasAllowedMoves(enemy))
return GameStatus.Check;