public boolean attackAUnit(Pos unit1Position, Pos unit2Position) { List<Pos> cellsInRange = new LinkedList<Pos>(); cellsInRange = possiblesAttackCellsAroundASpecificPosition(unit1Position); Unit selectedUnit1 = getCellAtASpecificPos(unit1Position).getUnitOnThisCell(); Unit selectedUnit2 = getCellAtASpecificPos(unit2Position).getUnitOnThisCell(); for (int index = 0; index < cellsInRange.size(); index++) { for (int index2 = index + 1; index2 < cellsInRange.size(); index2++) { if (cellsInRange.get(index2).equals(cellsInRange.get(index))) cellsInRange.remove(index2); } } if (getCellAtASpecificPos(unit2Position).getUnitOnThisCell() != null && !unit1Position.equals(unit2Position)) { if (!cellsInRange.contains(unit2Position)) { return false; } else { selectedUnit2.setLife(selectedUnit2.getLife() - selectedUnit1.getAttackDamage()); if (selectedUnit2.getLife() <= 0) { getCellAtASpecificPos(unit2Position) .getUnitOnThisCell() .getOwner() .removeOneUnitToPlayerCounter(); getCellAtASpecificPos(unit2Position).removeUnitFromThisCell(); } return true; } } return false; }
/** * Moves a selected unit to another cell. * * @param initialPosition * @param endPosition * @return True if the unit has been moved, false otherwise. */ public boolean moveAUnit(Pos initialPosition, Pos endPosition) { Unit selectedUnit = getCellAtASpecificPos(initialPosition).getUnitOnThisCell(); int counter = 0; List<Pos> reachableCells = new LinkedList<Pos>(); HashSet<Pos> setTemp = new HashSet<Pos>(); // setTemp allows to avoid duplicates. setTemp.addAll(possiblesMoves(initialPosition)); reachableCells.addAll(setTemp); if (selectedUnit != null && !initialPosition.equals(endPosition) && getCellAtASpecificPos(endPosition).getUnitOnThisCell() == null) { // We must check if the final position is not the initial one, and // if the final position is empty. while (counter < reachableCells.size() && !reachableCells.get(counter).equals(endPosition)) { // Then we check is the final position is in the list of every // reachable cells. counter++; } if (counter > reachableCells.size() - 1) { // endPosition isn't in reachableCells. counter = 0; reachableCells.clear(); return false; } else { // endPosition is in reachableCells. getCellAtASpecificPos(initialPosition).removeUnitFromThisCell(); getCellAtASpecificPos(endPosition).setUnitOnASpecificCell(selectedUnit, endPosition); counter = 0; reachableCells.clear(); return true; } } return false; }