96 lines
2.0 KiB
Java
96 lines
2.0 KiB
Java
package chess.controller;
|
|
|
|
import chess.controller.Command.CommandResult;
|
|
import chess.model.Game;
|
|
import chess.model.Game.GameStatus;
|
|
|
|
public class CommandExecutor {
|
|
|
|
private Game game;
|
|
private OutputSystem outputSystem;
|
|
|
|
public CommandExecutor() {
|
|
this.game = null;
|
|
this.outputSystem = null;
|
|
}
|
|
|
|
public synchronized CommandResult executeCommand(Command command) {
|
|
assert this.game != null : "No input game specified !";
|
|
assert this.outputSystem != null : "No output system specified !";
|
|
|
|
CommandResult result = command.execute(this.game, this.outputSystem);
|
|
|
|
// non player commands are not supposed to return move result
|
|
assert result != CommandResult.Moved || command instanceof PlayerCommand;
|
|
|
|
processResult(command, result);
|
|
|
|
if (command instanceof PlayerCommand playerCommand && result != CommandResult.NotAllowed)
|
|
this.game.addAction(playerCommand);
|
|
|
|
command.postExec(game, outputSystem);
|
|
return result;
|
|
}
|
|
|
|
private void processResult(Command command, CommandResult result) {
|
|
switch (result) {
|
|
case NotAllowed:
|
|
case NotMoved:
|
|
return;
|
|
|
|
case ActionNeeded:
|
|
this.outputSystem.updateDisplay();
|
|
return;
|
|
|
|
case Moved:
|
|
if (checkGameStatus())
|
|
return;
|
|
switchPlayerTurn();
|
|
this.outputSystem.updateDisplay();
|
|
return;
|
|
}
|
|
}
|
|
|
|
private void switchPlayerTurn() {
|
|
this.game.switchPlayerTurn();
|
|
this.outputSystem.playerTurn(this.game.getPlayerTurn());
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @return True if the game is over
|
|
*/
|
|
private boolean checkGameStatus() {
|
|
GameStatus gameStatus = this.game.checkGameStatus();
|
|
|
|
switch (gameStatus) {
|
|
case Check:
|
|
this.outputSystem.kingIsInCheck();
|
|
return false;
|
|
|
|
case CheckMate:
|
|
this.outputSystem.kingIsInMat();
|
|
this.outputSystem.winnerIs(this.game.getPlayerTurn());
|
|
return true;
|
|
|
|
case OnGoing:
|
|
return false;
|
|
|
|
case Pat:
|
|
this.outputSystem.patSituation();
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public void setOutputSystem(OutputSystem outputSystem) {
|
|
this.outputSystem = outputSystem;
|
|
}
|
|
|
|
public void setGame(Game game) {
|
|
this.game = game;
|
|
}
|
|
|
|
}
|