use of games.strategy.util.Tuple in project triplea by triplea-game.
the class GameParser method parseAttachments.
private void parseAttachments(final Element root) throws GameParseException {
for (final Element current : getChildren("attachment", root)) {
final String className = current.getAttribute("javaClass");
final Attachable attachable = findAttachment(current, current.getAttribute("type"));
final String name = current.getAttribute("name");
final List<Element> options = getChildren("option", current);
final IAttachment attachment = new XmlGameElementMapper().getAttachment(className, name, attachable, data).orElseThrow(() -> newGameParseException("Attachment of type " + className + " could not be instantiated"));
attachable.addAttachment(name, attachment);
final ArrayList<Tuple<String, String>> attachmentOptionValues = setValues(attachment, options);
// keep a list of attachment references in the order they were added
data.addToAttachmentOrderAndValues(Tuple.of(attachment, attachmentOptionValues));
}
}
use of games.strategy.util.Tuple in project triplea by triplea-game.
the class BattleCalculator method sortUnitsForCasualtiesWithSupport.
/**
* The purpose of this is to return a list in the PERFECT order of which units should be selected to die first,
* And that means that certain units MUST BE INTERLEAVED.
* This list assumes that you have already taken any extra hit points away from any 2 hitpoint units.
* Example: You have a 1 attack Artillery unit that supports, and a 1 attack infantry unit that can receive support.
* The best selection of units to die is first to take whichever unit has excess, then cut that down til they are both
* the same size,
* then to take 1 artillery followed by 1 infantry, followed by 1 artillery, then 1 inf, etc, until everyone is dead.
* If you just return all infantry followed by all artillery, or the other way around, you will be missing out on some
* important support
* provided.
* (Veqryn)
*/
private static List<Unit> sortUnitsForCasualtiesWithSupport(final Collection<Unit> targetsToPickFrom, final boolean defending, final PlayerID player, final Collection<Unit> enemyUnits, final boolean amphibious, final Collection<Unit> amphibiousLandAttackers, final Territory battlesite, final IntegerMap<UnitType> costs, final Collection<TerritoryEffect> territoryEffects, final GameData data, final boolean bonus) {
// Convert unit lists to unit type lists
final List<UnitType> targetTypes = new ArrayList<>();
for (final Unit u : targetsToPickFrom) {
targetTypes.add(u.getType());
}
final List<UnitType> amphibTypes = new ArrayList<>();
if (amphibiousLandAttackers != null) {
for (final Unit u : amphibiousLandAttackers) {
amphibTypes.add(u.getType());
}
}
// Calculate hashes and cache key
int targetsHashCode = 1;
for (final UnitType ut : targetTypes) {
targetsHashCode += ut.hashCode();
}
targetsHashCode *= 31;
int amphibHashCode = 1;
for (final UnitType ut : amphibTypes) {
amphibHashCode += ut.hashCode();
}
amphibHashCode *= 31;
String key = player.getName() + "|" + battlesite.getName() + "|" + defending + "|" + amphibious + "|" + targetsHashCode + "|" + amphibHashCode;
// Check OOL cache
final List<UnitType> stored = oolCache.get(key);
if (stored != null) {
// System.out.println("Hit with cacheSize=" + oolCache.size() + ", key=" + key);
final List<Unit> result = new ArrayList<>();
final List<Unit> selectFrom = new ArrayList<>(targetsToPickFrom);
for (final UnitType ut : stored) {
for (final Iterator<Unit> it = selectFrom.iterator(); it.hasNext(); ) {
final Unit u = it.next();
if (ut.equals(u.getType())) {
result.add(u);
it.remove();
}
}
}
return result;
}
// System.out.println("Miss with cacheSize=" + oolCache.size() + ", key=" + key);
// Sort enough units to kill off
final List<Unit> sortedUnitsList = new ArrayList<>(targetsToPickFrom);
sortedUnitsList.sort(new UnitBattleComparator(defending, costs, territoryEffects, data, bonus, false));
// Sort units starting with strongest so that support gets added to them first
Collections.reverse(sortedUnitsList);
final UnitBattleComparator unitComparatorWithoutPrimaryPower = new UnitBattleComparator(defending, costs, territoryEffects, data, bonus, true);
final Map<Unit, IntegerMap<Unit>> unitSupportPowerMap = new HashMap<>();
final Map<Unit, IntegerMap<Unit>> unitSupportRollsMap = new HashMap<>();
final Map<Unit, Tuple<Integer, Integer>> unitPowerAndRollsMap = DiceRoll.getUnitPowerAndRollsForNormalBattles(sortedUnitsList, new ArrayList<>(enemyUnits), defending, false, data, battlesite, territoryEffects, amphibious, amphibiousLandAttackers, unitSupportPowerMap, unitSupportRollsMap);
// Sort units starting with weakest for finding the worst units
Collections.reverse(sortedUnitsList);
final List<Unit> sortedWellEnoughUnitsList = new ArrayList<>();
for (int i = 0; i < sortedUnitsList.size(); ++i) {
// Loop through all target units to find the best unit to take as casualty
Unit worstUnit = null;
int minPower = Integer.MAX_VALUE;
final Set<UnitType> unitTypes = new HashSet<>();
for (final Unit u : sortedUnitsList) {
if (unitTypes.contains(u.getType())) {
continue;
}
unitTypes.add(u.getType());
// Find unit power
final Map<Unit, Tuple<Integer, Integer>> currentUnitMap = new HashMap<>();
currentUnitMap.put(u, unitPowerAndRollsMap.get(u));
int power = DiceRoll.getTotalPower(currentUnitMap, data);
// Add any support power that it provides to other units
final IntegerMap<Unit> unitSupportPowerMapForUnit = unitSupportPowerMap.get(u);
if (unitSupportPowerMapForUnit != null) {
for (final Unit supportedUnit : unitSupportPowerMapForUnit.keySet()) {
Tuple<Integer, Integer> strengthAndRolls = unitPowerAndRollsMap.get(supportedUnit);
if (strengthAndRolls == null) {
continue;
}
// Remove any rolls provided by this support so they aren't counted twice
final IntegerMap<Unit> unitSupportRollsMapForUnit = unitSupportRollsMap.get(u);
if (unitSupportRollsMapForUnit != null) {
strengthAndRolls = Tuple.of(strengthAndRolls.getFirst(), strengthAndRolls.getSecond() - unitSupportRollsMapForUnit.getInt(supportedUnit));
}
// If one roll then just add the power
if (strengthAndRolls.getSecond() == 1) {
power += unitSupportPowerMapForUnit.getInt(supportedUnit);
continue;
}
// Find supported unit power with support
final Map<Unit, Tuple<Integer, Integer>> supportedUnitMap = new HashMap<>();
supportedUnitMap.put(supportedUnit, strengthAndRolls);
final int powerWithSupport = DiceRoll.getTotalPower(supportedUnitMap, data);
// Find supported unit power without support
final int strengthWithoutSupport = strengthAndRolls.getFirst() - unitSupportPowerMapForUnit.getInt(supportedUnit);
final Tuple<Integer, Integer> strengthAndRollsWithoutSupport = Tuple.of(strengthWithoutSupport, strengthAndRolls.getSecond());
supportedUnitMap.put(supportedUnit, strengthAndRollsWithoutSupport);
final int powerWithoutSupport = DiceRoll.getTotalPower(supportedUnitMap, data);
// Add the actual power provided by the support
final int addedPower = powerWithSupport - powerWithoutSupport;
power += addedPower;
}
}
// Add any power from support rolls that it provides to other units
final IntegerMap<Unit> unitSupportRollsMapForUnit = unitSupportRollsMap.get(u);
if (unitSupportRollsMapForUnit != null) {
for (final Unit supportedUnit : unitSupportRollsMapForUnit.keySet()) {
final Tuple<Integer, Integer> strengthAndRolls = unitPowerAndRollsMap.get(supportedUnit);
if (strengthAndRolls == null) {
continue;
}
// Find supported unit power with support
final Map<Unit, Tuple<Integer, Integer>> supportedUnitMap = new HashMap<>();
supportedUnitMap.put(supportedUnit, strengthAndRolls);
final int powerWithSupport = DiceRoll.getTotalPower(supportedUnitMap, data);
// Find supported unit power without support
final int rollsWithoutSupport = strengthAndRolls.getSecond() - unitSupportRollsMap.get(u).getInt(supportedUnit);
final Tuple<Integer, Integer> strengthAndRollsWithoutSupport = Tuple.of(strengthAndRolls.getFirst(), rollsWithoutSupport);
supportedUnitMap.put(supportedUnit, strengthAndRollsWithoutSupport);
final int powerWithoutSupport = DiceRoll.getTotalPower(supportedUnitMap, data);
// Add the actual power provided by the support
final int addedPower = powerWithSupport - powerWithoutSupport;
power += addedPower;
}
}
// Check if unit has lower power
if (power < minPower || (power == minPower && unitComparatorWithoutPrimaryPower.compare(u, worstUnit) < 0)) {
worstUnit = u;
minPower = power;
}
}
// Add worst unit to sorted list, update any units it supported, and remove from other collections
final IntegerMap<Unit> unitSupportPowerMapForUnit = unitSupportPowerMap.get(worstUnit);
if (unitSupportPowerMapForUnit != null) {
for (final Unit supportedUnit : unitSupportPowerMapForUnit.keySet()) {
final Tuple<Integer, Integer> strengthAndRolls = unitPowerAndRollsMap.get(supportedUnit);
if (strengthAndRolls == null) {
continue;
}
final int strengthWithoutSupport = strengthAndRolls.getFirst() - unitSupportPowerMapForUnit.getInt(supportedUnit);
final Tuple<Integer, Integer> strengthAndRollsWithoutSupport = Tuple.of(strengthWithoutSupport, strengthAndRolls.getSecond());
unitPowerAndRollsMap.put(supportedUnit, strengthAndRollsWithoutSupport);
sortedUnitsList.remove(supportedUnit);
sortedUnitsList.add(0, supportedUnit);
}
}
final IntegerMap<Unit> unitSupportRollsMapForUnit = unitSupportRollsMap.get(worstUnit);
if (unitSupportRollsMapForUnit != null) {
for (final Unit supportedUnit : unitSupportRollsMapForUnit.keySet()) {
final Tuple<Integer, Integer> strengthAndRolls = unitPowerAndRollsMap.get(supportedUnit);
if (strengthAndRolls == null) {
continue;
}
final int rollsWithoutSupport = strengthAndRolls.getSecond() - unitSupportRollsMapForUnit.getInt(supportedUnit);
final Tuple<Integer, Integer> strengthAndRollsWithoutSupport = Tuple.of(strengthAndRolls.getFirst(), rollsWithoutSupport);
unitPowerAndRollsMap.put(supportedUnit, strengthAndRollsWithoutSupport);
sortedUnitsList.remove(supportedUnit);
sortedUnitsList.add(0, supportedUnit);
}
}
sortedWellEnoughUnitsList.add(worstUnit);
sortedUnitsList.remove(worstUnit);
unitPowerAndRollsMap.remove(worstUnit);
unitSupportPowerMap.remove(worstUnit);
unitSupportRollsMap.remove(worstUnit);
}
sortedWellEnoughUnitsList.addAll(sortedUnitsList);
// Cache result and all subsets of the result
final List<UnitType> unitTypes = new ArrayList<>();
for (final Unit u : sortedWellEnoughUnitsList) {
unitTypes.add(u.getType());
}
for (final Iterator<UnitType> it = unitTypes.iterator(); it.hasNext(); ) {
oolCache.put(key, new ArrayList<>(unitTypes));
final UnitType unitTypeToRemove = it.next();
targetTypes.remove(unitTypeToRemove);
if (Collections.frequency(targetTypes, unitTypeToRemove) < Collections.frequency(amphibTypes, unitTypeToRemove)) {
amphibTypes.remove(unitTypeToRemove);
}
targetsHashCode = 1;
for (final UnitType ut : targetTypes) {
targetsHashCode += ut.hashCode();
}
targetsHashCode *= 31;
amphibHashCode = 1;
for (final UnitType ut : amphibTypes) {
amphibHashCode += ut.hashCode();
}
amphibHashCode *= 31;
key = player.getName() + "|" + battlesite.getName() + "|" + defending + "|" + amphibious + "|" + targetsHashCode + "|" + amphibHashCode;
it.remove();
}
return sortedWellEnoughUnitsList;
}
use of games.strategy.util.Tuple in project triplea by triplea-game.
the class BattleTracker method captureOrDestroyUnits.
/**
* Called when a territory is conquered to determine if remaining enemy units should be
* captured, destroyed, or take damage.
*/
public static void captureOrDestroyUnits(final Territory territory, final PlayerID id, final PlayerID newOwner, final IDelegateBridge bridge, final UndoableMove changeTracker) {
final GameData data = bridge.getData();
// destroy any units that should be destroyed on capture
if (Properties.getUnitsCanBeDestroyedInsteadOfCaptured(data)) {
final Predicate<Unit> enemyToBeDestroyed = Matches.enemyUnit(id, data).and(Matches.unitDestroyedWhenCapturedByOrFrom(id));
final Collection<Unit> destroyed = territory.getUnits().getMatches(enemyToBeDestroyed);
if (!destroyed.isEmpty()) {
final Change destroyUnits = ChangeFactory.removeUnits(territory, destroyed);
bridge.getHistoryWriter().addChildToEvent("Some non-combat units are destroyed: ", destroyed);
bridge.addChange(destroyUnits);
if (changeTracker != null) {
changeTracker.addChange(destroyUnits);
}
}
}
// destroy any capture on entering units, IF the property to destroy them instead of capture is turned on
if (Properties.getOnEnteringUnitsDestroyedInsteadOfCaptured(data)) {
final Collection<Unit> destroyed = territory.getUnits().getMatches(Matches.unitCanBeCapturedOnEnteringToInThisTerritory(id, territory, data));
if (!destroyed.isEmpty()) {
final Change destroyUnits = ChangeFactory.removeUnits(territory, destroyed);
bridge.getHistoryWriter().addChildToEvent(id.getName() + " destroys some units instead of capturing them", destroyed);
bridge.addChange(destroyUnits);
if (changeTracker != null) {
changeTracker.addChange(destroyUnits);
}
}
}
// destroy any disabled units owned by the enemy that are NOT infrastructure or factories
final Predicate<Unit> enemyToBeDestroyed = Matches.enemyUnit(id, data).and(Matches.unitIsDisabled()).and(Matches.unitIsInfrastructure().negate());
final Collection<Unit> destroyed = territory.getUnits().getMatches(enemyToBeDestroyed);
if (!destroyed.isEmpty()) {
final Change destroyUnits = ChangeFactory.removeUnits(territory, destroyed);
bridge.getHistoryWriter().addChildToEvent(id.getName() + " destroys some disabled combat units", destroyed);
bridge.addChange(destroyUnits);
if (changeTracker != null) {
changeTracker.addChange(destroyUnits);
}
}
// take over non combatants
final Predicate<Unit> enemyNonCom = Matches.enemyUnit(id, data).and(Matches.unitIsInfrastructure());
final Predicate<Unit> willBeCaptured = enemyNonCom.or(Matches.unitCanBeCapturedOnEnteringToInThisTerritory(id, territory, data));
final Collection<Unit> nonCom = territory.getUnits().getMatches(willBeCaptured);
// change any units that change unit types on capture
if (Properties.getUnitsCanBeChangedOnCapture(data)) {
final Collection<Unit> toReplace = CollectionUtils.getMatches(nonCom, Matches.unitWhenCapturedChangesIntoDifferentUnitType());
for (final Unit u : toReplace) {
final Map<String, Tuple<String, IntegerMap<UnitType>>> map = UnitAttachment.get(u.getType()).getWhenCapturedChangesInto();
final PlayerID currentOwner = u.getOwner();
for (final String value : map.keySet()) {
final String[] s = value.split(":");
if (!(s[0].equals("any") || data.getPlayerList().getPlayerId(s[0]).equals(currentOwner))) {
continue;
}
// we could use "id" or "newOwner" here... not sure which to use
if (!(s[1].equals("any") || data.getPlayerList().getPlayerId(s[1]).equals(id))) {
continue;
}
final CompositeChange changes = new CompositeChange();
final Collection<Unit> toAdd = new ArrayList<>();
final Tuple<String, IntegerMap<UnitType>> toCreate = map.get(value);
final boolean translateAttributes = toCreate.getFirst().equalsIgnoreCase("true");
for (final UnitType ut : toCreate.getSecond().keySet()) {
toAdd.addAll(ut.create(toCreate.getSecond().getInt(ut), newOwner));
}
if (!toAdd.isEmpty()) {
if (translateAttributes) {
final Change translate = TripleAUnit.translateAttributesToOtherUnits(u, toAdd, territory);
if (!translate.isEmpty()) {
changes.add(translate);
}
}
changes.add(ChangeFactory.removeUnits(territory, Collections.singleton(u)));
changes.add(ChangeFactory.addUnits(territory, toAdd));
changes.add(ChangeFactory.markNoMovementChange(toAdd));
bridge.getHistoryWriter().addChildToEvent(id.getName() + " converts " + u.toStringNoOwner() + " into different units", toAdd);
bridge.addChange(changes);
if (changeTracker != null) {
changeTracker.addChange(changes);
}
// don't forget to remove this unit from the list
nonCom.remove(u);
break;
}
}
}
}
if (!nonCom.isEmpty()) {
// FYI: a dummy delegate will not do anything with this change,
// meaning that the battle calculator will think this unit lived,
// even though it died or was captured, etc!
final Change capture = ChangeFactory.changeOwner(nonCom, newOwner, territory);
bridge.addChange(capture);
if (changeTracker != null) {
changeTracker.addChange(capture);
}
final Change noMovementChange = ChangeFactory.markNoMovementChange(nonCom);
bridge.addChange(noMovementChange);
if (changeTracker != null) {
changeTracker.addChange(noMovementChange);
}
final IntegerMap<Unit> damageMap = new IntegerMap<>();
for (final Unit unit : CollectionUtils.getMatches(nonCom, Matches.unitWhenCapturedSustainsDamage())) {
final TripleAUnit taUnit = (TripleAUnit) unit;
final int damageLimit = taUnit.getHowMuchMoreDamageCanThisUnitTake(unit, territory);
final int sustainedDamage = UnitAttachment.get(unit.getType()).getWhenCapturedSustainsDamage();
final int actualDamage = Math.max(0, Math.min(sustainedDamage, damageLimit));
final int totalDamage = taUnit.getUnitDamage() + actualDamage;
damageMap.put(unit, totalDamage);
}
if (!damageMap.isEmpty()) {
final Change damageChange = ChangeFactory.bombingUnitDamage(damageMap);
bridge.addChange(damageChange);
if (changeTracker != null) {
changeTracker.addChange(damageChange);
}
// Kill any units that can die if they have reached max damage
if (damageMap.keySet().stream().anyMatch(Matches.unitCanDieFromReachingMaxDamage())) {
final List<Unit> unitsCanDie = CollectionUtils.getMatches(damageMap.keySet(), Matches.unitCanDieFromReachingMaxDamage());
unitsCanDie.retainAll(CollectionUtils.getMatches(unitsCanDie, Matches.unitIsAtMaxDamageOrNotCanBeDamaged(territory)));
if (!unitsCanDie.isEmpty()) {
final Change removeDead = ChangeFactory.removeUnits(territory, unitsCanDie);
bridge.addChange(removeDead);
if (changeTracker != null) {
changeTracker.addChange(removeDead);
}
}
}
}
}
}
use of games.strategy.util.Tuple in project triplea by triplea-game.
the class UnitAttachmentTest method testSetWhenCapturedChangesInto.
@Test
public void testSetWhenCapturedChangesInto() throws Exception {
final SecureRandom rand = new SecureRandom();
final String from = "any";
final String to = "any";
final String trueString = Boolean.toString(true);
final String falseString = Boolean.toString(false);
final Map<String, Tuple<String, IntegerMap<UnitType>>> mapReference = attachment.getWhenCapturedChangesInto();
final int random1 = rand.nextInt();
final IntegerMap<UnitType> expected1 = new IntegerMap<>(unit1, random1);
attachment.setWhenCapturedChangesInto(concatWithColon(from, to, trueString, unit1String, String.valueOf(random1)));
assertEquals(Tuple.of(trueString, expected1), mapReference.get(from + ":" + to));
final int random2 = rand.nextInt();
final int random3 = rand.nextInt();
final IntegerMap<UnitType> expected2 = new IntegerMap<>();
expected2.put(unit1, random2);
expected2.put(unit2, random3);
attachment.setWhenCapturedChangesInto(concatWithColon(from, to, falseString, unit1String, String.valueOf(random2), unit2String, String.valueOf(random3)));
assertEquals(Tuple.of(falseString, expected2), mapReference.get(from + ":" + to));
}
use of games.strategy.util.Tuple in project triplea by triplea-game.
the class MoveDelegate method repairedChangeInto.
private static void repairedChangeInto(final Set<Unit> units, final Territory territory, final IDelegateBridge bridge) {
final List<Unit> changesIntoUnits = CollectionUtils.getMatches(units, Matches.unitWhenHitPointsRepairedChangesInto());
final CompositeChange changes = new CompositeChange();
final List<Unit> unitsToRemove = new ArrayList<>();
final List<Unit> unitsToAdd = new ArrayList<>();
for (final Unit unit : changesIntoUnits) {
final Map<Integer, Tuple<Boolean, UnitType>> map = UnitAttachment.get(unit.getType()).getWhenHitPointsRepairedChangesInto();
if (map.containsKey(unit.getHits())) {
final boolean translateAttributes = map.get(unit.getHits()).getFirst();
final UnitType unitType = map.get(unit.getHits()).getSecond();
final List<Unit> toAdd = unitType.create(1, unit.getOwner());
if (translateAttributes) {
final Change translate = TripleAUnit.translateAttributesToOtherUnits(unit, toAdd, territory);
changes.add(translate);
}
unitsToRemove.add(unit);
unitsToAdd.addAll(toAdd);
}
}
if (!unitsToRemove.isEmpty()) {
bridge.addChange(changes);
final String removeText = MyFormatter.unitsToText(unitsToRemove) + " removed in " + territory.getName();
bridge.getHistoryWriter().addChildToEvent(removeText, new ArrayList<>(unitsToRemove));
bridge.addChange(ChangeFactory.removeUnits(territory, unitsToRemove));
final String addText = MyFormatter.unitsToText(unitsToAdd) + " added in " + territory.getName();
bridge.getHistoryWriter().addChildToEvent(addText, new ArrayList<>(unitsToAdd));
bridge.addChange(ChangeFactory.addUnits(territory, unitsToAdd));
}
}
Aggregations