* @param realm Realm to execute the command
* @return CommandResult
*/
public CommandResult execute(Realm realm) {
if (unit.getCoordinate().equals(coordinate)) {
return new CommandResult(CommandResult.RESULT_OK, "");
}
PathFinder pathFinder = realm.getPathFinder();
if (pathFinder == null) {
return new CommandResult(CommandResult.RESULT_ERROR, "PathFinder for realm is null.");
}
Path path = pathFinder.findPath(unit, coordinate, true);
if (path == null) {
String errorMessage = "There is not any path from unit's current location to target tile\n";
errorMessage = errorMessage + "Units location : " + unit.getCoordinate();
errorMessage = errorMessage + " Target coordinate :" + coordinate;
return new CommandResult(CommandResult.RESULT_ERROR, errorMessage);
}
int i = 0;
while ((unit.getMovementPoints() > 0) && (i < path.getLength())) {
Coordinate pathCoordinate = path.getStep(i);
Tile tile = realm.getTile(pathCoordinate);
ICommand command = null;
if (tile.getNumberOfUnits() > 0) {
Unit tileUnit = tile.getUnits().get(tile.getUnits().firstKey());
if (!unit.getPlayer().equals(tileUnit.getPlayer())) {
command = new AttackTileCommand(unit, tile);
} else {
command = new MoveUnitCommand(unit, pathCoordinate);
}
} else {
if (tile.getSettlement() != null) {
Settlement settlement = tile.getSettlement();
if (!unit.getPlayer().equals(settlement.getPlayer())) {
command = new CaptureSettlementCommand(unit, settlement);
} else {
command = new MoveUnitCommand(unit, pathCoordinate);
}
} else {
command = new MoveUnitCommand(unit, pathCoordinate);
}
}
CommandResult commandResult = Executor.getInstance().execute(command);
i++;
if (commandResult.getCode() == CommandResult.RESULT_ERROR) {
return new CommandResult(CommandResult.RESULT_ERROR, "A command returned an error. Error : " + commandResult.getText());
}
}
return new CommandResult(CommandResult.RESULT_OK, "");
}