Search in sources :

Example 26 with TerritoryAttachment

use of games.strategy.triplea.attachments.TerritoryAttachment in project triplea by triplea-game.

the class ProCombatMoveAi method removeTerritoriesWhereTransportsAreExposed.

private void removeTerritoriesWhereTransportsAreExposed() {
    ProLogger.info("Remove territories where transports are exposed");
    final Map<Territory, ProTerritory> attackMap = territoryManager.getAttackOptions().getTerritoryMap();
    final ProOtherMoveOptions enemyAttackOptions = territoryManager.getEnemyAttackOptions();
    // Find maximum defenders for each transport territory
    final List<Territory> clearedTerritories = attackMap.entrySet().stream().filter(e -> !e.getValue().getUnits().isEmpty()).map(Map.Entry::getKey).collect(Collectors.toList());
    territoryManager.populateDefenseOptions(clearedTerritories);
    final Map<Territory, ProTerritory> defendMap = territoryManager.getDefendOptions().getTerritoryMap();
    // Remove units that have already attacked
    final Set<Unit> alreadyAttackedWithUnits = new HashSet<>();
    for (final ProTerritory t : attackMap.values()) {
        alreadyAttackedWithUnits.addAll(t.getUnits());
        alreadyAttackedWithUnits.addAll(t.getAmphibAttackMap().keySet());
    }
    for (final ProTerritory t : defendMap.values()) {
        t.getMaxUnits().removeAll(alreadyAttackedWithUnits);
    }
    // Loop through all prioritized territories
    for (final Territory t : attackMap.keySet()) {
        final ProTerritory patd = attackMap.get(t);
        ProLogger.debug("Checking territory=" + patd.getTerritory().getName() + " with tranports size=" + patd.getTransportTerritoryMap().size());
        if (!patd.getTerritory().isWater() && !patd.getTransportTerritoryMap().isEmpty()) {
            // Find all transports for each unload territory
            final Map<Territory, List<Unit>> territoryTransportAndBombardMap = new HashMap<>();
            for (final Unit u : patd.getTransportTerritoryMap().keySet()) {
                final Territory unloadTerritory = patd.getTransportTerritoryMap().get(u);
                if (territoryTransportAndBombardMap.containsKey(unloadTerritory)) {
                    territoryTransportAndBombardMap.get(unloadTerritory).add(u);
                } else {
                    final List<Unit> transports = new ArrayList<>();
                    transports.add(u);
                    territoryTransportAndBombardMap.put(unloadTerritory, transports);
                }
            }
            // Find all bombard units for each unload territory
            for (final Unit u : patd.getBombardTerritoryMap().keySet()) {
                final Territory unloadTerritory = patd.getBombardTerritoryMap().get(u);
                if (territoryTransportAndBombardMap.containsKey(unloadTerritory)) {
                    territoryTransportAndBombardMap.get(unloadTerritory).add(u);
                } else {
                    final List<Unit> transports = new ArrayList<>();
                    transports.add(u);
                    territoryTransportAndBombardMap.put(unloadTerritory, transports);
                }
            }
            // Determine counter attack results for each transport territory
            double enemyTuvSwing = 0.0;
            for (final Territory unloadTerritory : territoryTransportAndBombardMap.keySet()) {
                if (enemyAttackOptions.getMax(unloadTerritory) != null) {
                    final List<Unit> enemyAttackers = enemyAttackOptions.getMax(unloadTerritory).getMaxUnits();
                    final Set<Unit> defenders = new HashSet<>(unloadTerritory.getUnits().getMatches(ProMatches.unitIsAlliedNotOwned(player, data)));
                    defenders.addAll(territoryTransportAndBombardMap.get(unloadTerritory));
                    if (defendMap.get(unloadTerritory) != null) {
                        defenders.addAll(defendMap.get(unloadTerritory).getMaxUnits());
                    }
                    final ProBattleResult result = calc.calculateBattleResults(unloadTerritory, enemyAttackOptions.getMax(unloadTerritory).getMaxUnits(), new ArrayList<>(defenders), new HashSet<>());
                    final ProBattleResult minResult = calc.calculateBattleResults(unloadTerritory, enemyAttackOptions.getMax(unloadTerritory).getMaxUnits(), territoryTransportAndBombardMap.get(unloadTerritory), new HashSet<>());
                    final double minTuvSwing = Math.min(result.getTuvSwing(), minResult.getTuvSwing());
                    if (minTuvSwing > 0) {
                        enemyTuvSwing += minTuvSwing;
                    }
                    ProLogger.trace(unloadTerritory + ", EnemyAttackers=" + enemyAttackers.size() + ", MaxDefenders=" + defenders.size() + ", MaxEnemyTUVSwing=" + result.getTuvSwing() + ", MinDefenders=" + territoryTransportAndBombardMap.get(unloadTerritory).size() + ", MinEnemyTUVSwing=" + minResult.getTuvSwing());
                } else {
                    ProLogger.trace("Territory=" + unloadTerritory.getName() + " has no enemy attackers");
                }
            }
            // Determine whether its worth attacking
            final ProBattleResult result = calc.calculateBattleResults(t, patd.getUnits(), patd.getMaxEnemyDefenders(player, data), patd.getBombardTerritoryMap().keySet());
            int production = 0;
            int isEnemyCapital = 0;
            final TerritoryAttachment ta = TerritoryAttachment.get(t);
            if (ta != null) {
                production = ta.getProduction();
                if (ta.isCapital()) {
                    isEnemyCapital = 1;
                }
            }
            final double attackValue = result.getTuvSwing() + production * (1 + 3 * isEnemyCapital);
            if (!patd.isStrafing() && (0.75 * enemyTuvSwing) > attackValue) {
                ProLogger.debug("Removing amphib territory: " + patd.getTerritory() + ", enemyTUVSwing=" + enemyTuvSwing + ", attackValue=" + attackValue);
                attackMap.get(t).getUnits().clear();
                attackMap.get(t).getAmphibAttackMap().clear();
                attackMap.get(t).getBombardTerritoryMap().clear();
            } else {
                ProLogger.debug("Keeping amphib territory: " + patd.getTerritory() + ", enemyTUVSwing=" + enemyTuvSwing + ", attackValue=" + attackValue);
            }
        }
    }
}
Also used : Territory(games.strategy.engine.data.Territory) ProTerritory(games.strategy.triplea.ai.pro.data.ProTerritory) HashMap(java.util.HashMap) ProTerritory(games.strategy.triplea.ai.pro.data.ProTerritory) TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment) ArrayList(java.util.ArrayList) ProBattleResult(games.strategy.triplea.ai.pro.data.ProBattleResult) TripleAUnit(games.strategy.triplea.TripleAUnit) Unit(games.strategy.engine.data.Unit) ArrayList(java.util.ArrayList) List(java.util.List) ProOtherMoveOptions(games.strategy.triplea.ai.pro.data.ProOtherMoveOptions) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet)

Example 27 with TerritoryAttachment

use of games.strategy.triplea.attachments.TerritoryAttachment in project triplea by triplea-game.

the class ProRetreatAi method retreatQuery.

Territory retreatQuery(final GUID battleId, final Territory battleTerritory, final Collection<Territory> possibleTerritories) {
    // Get battle data
    final GameData data = ProData.getData();
    final PlayerID player = ProData.getPlayer();
    final BattleDelegate delegate = DelegateFinder.battleDelegate(data);
    final IBattle battle = delegate.getBattleTracker().getPendingBattle(battleId);
    // Get units and determine if attacker
    final boolean isAttacker = player.equals(battle.getAttacker());
    final List<Unit> attackers = (List<Unit>) battle.getAttackingUnits();
    final List<Unit> defenders = (List<Unit>) battle.getDefendingUnits();
    // Calculate battle results
    final ProBattleResult result = calc.calculateBattleResults(battleTerritory, attackers, defenders, new HashSet<>());
    // Determine if it has a factory
    int isFactory = 0;
    if (ProMatches.territoryHasInfraFactoryAndIsLand().test(battleTerritory)) {
        isFactory = 1;
    }
    // Determine production value and if it is a capital
    int production = 0;
    int isCapital = 0;
    final TerritoryAttachment ta = TerritoryAttachment.get(battleTerritory);
    if (ta != null) {
        production = ta.getProduction();
        if (ta.isCapital()) {
            isCapital = 1;
        }
    }
    // Calculate current attack value
    double territoryValue = 0;
    if (result.isHasLandUnitRemaining() || attackers.stream().noneMatch(Matches.unitIsAir())) {
        territoryValue = result.getWinPercentage() / 100 * (2 * production * (1 + isFactory) * (1 + isCapital));
    }
    double battleValue = result.getTuvSwing() + territoryValue;
    if (!isAttacker) {
        battleValue = -battleValue;
    }
    // Decide if we should retreat
    if (battleValue < 0) {
        // Retreat to capital if available otherwise the territory with highest defense strength
        Territory retreatTerritory = null;
        double maxStrength = Double.NEGATIVE_INFINITY;
        final Territory myCapital = TerritoryAttachment.getFirstOwnedCapitalOrFirstUnownedCapital(player, data);
        for (final Territory t : possibleTerritories) {
            if (t.equals(myCapital)) {
                retreatTerritory = t;
                break;
            }
            final double strength = ProBattleUtils.estimateStrength(t, t.getUnits().getMatches(Matches.isUnitAllied(player, data)), new ArrayList<>(), false);
            if (strength > maxStrength) {
                retreatTerritory = t;
                maxStrength = strength;
            }
        }
        ProLogger.debug(player.getName() + " retreating from territory " + battleTerritory + " to " + retreatTerritory + " because AttackValue=" + battleValue + ", TUVSwing=" + result.getTuvSwing() + ", possibleTerritories=" + possibleTerritories.size());
        return retreatTerritory;
    }
    ProLogger.debug(player.getName() + " not retreating from territory " + battleTerritory + " with AttackValue=" + battleValue + ", TUVSwing=" + result.getTuvSwing());
    return null;
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) BattleDelegate(games.strategy.triplea.delegate.BattleDelegate) Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment) ProBattleResult(games.strategy.triplea.ai.pro.data.ProBattleResult) Unit(games.strategy.engine.data.Unit) IBattle(games.strategy.triplea.delegate.IBattle) ArrayList(java.util.ArrayList) List(java.util.List)

Example 28 with TerritoryAttachment

use of games.strategy.triplea.attachments.TerritoryAttachment in project triplea by triplea-game.

the class TripleAUnit method getHowMuchCanUnitProduce.

public static int getHowMuchCanUnitProduce(final Unit u, final Territory producer, final PlayerID player, final GameData data, final boolean accountForDamage, final boolean mathMaxZero) {
    if (u == null) {
        return 0;
    }
    if (!Matches.unitCanProduceUnits().test(u)) {
        return 0;
    }
    final UnitAttachment ua = UnitAttachment.get(u.getType());
    final TripleAUnit taUnit = (TripleAUnit) u;
    final TerritoryAttachment ta = TerritoryAttachment.get(producer);
    int territoryProduction = 0;
    int territoryUnitProduction = 0;
    if (ta != null) {
        territoryProduction = ta.getProduction();
        territoryUnitProduction = ta.getUnitProduction();
    }
    int productionCapacity;
    if (accountForDamage) {
        if (Properties.getDamageFromBombingDoneToUnitsInsteadOfTerritories(data)) {
            if (ua.getCanProduceXUnits() < 0) {
                // we could use territoryUnitProduction OR
                // territoryProduction if we wanted to, however we should
                // change damage to be based on whichever we choose.
                productionCapacity = territoryUnitProduction - taUnit.getUnitDamage();
            } else {
                productionCapacity = ua.getCanProduceXUnits() - taUnit.getUnitDamage();
            }
        } else {
            productionCapacity = territoryProduction;
            if (productionCapacity < 1) {
                productionCapacity = (Properties.getWW2V2(data) || Properties.getWW2V3(data)) ? 0 : 1;
            }
        }
    } else {
        if (ua.getCanProduceXUnits() < 0 && !Properties.getDamageFromBombingDoneToUnitsInsteadOfTerritories(data)) {
            productionCapacity = territoryProduction;
        } else if (ua.getCanProduceXUnits() < 0 && Properties.getDamageFromBombingDoneToUnitsInsteadOfTerritories(data)) {
            productionCapacity = territoryUnitProduction;
        } else {
            productionCapacity = ua.getCanProduceXUnits();
        }
        if (productionCapacity < 1 && !Properties.getDamageFromBombingDoneToUnitsInsteadOfTerritories(data)) {
            productionCapacity = (Properties.getWW2V2(data) || Properties.getWW2V3(data)) ? 0 : 1;
        }
    }
    // Increase production if have industrial technology
    if (territoryProduction >= TechAbilityAttachment.getMinimumTerritoryValueForProductionBonus(player, data)) {
        productionCapacity += TechAbilityAttachment.getProductionBonus(u.getType(), player, data);
    }
    return mathMaxZero ? Math.max(0, productionCapacity) : productionCapacity;
}
Also used : UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment)

Example 29 with TerritoryAttachment

use of games.strategy.triplea.attachments.TerritoryAttachment in project triplea by triplea-game.

the class GameParser method parseOwner.

private void parseOwner(final List<Element> elements) throws GameParseException {
    for (final Element current : elements) {
        final Territory territory = getTerritory(current, "territory", true);
        final PlayerID owner = getPlayerId(current, "owner", true);
        territory.setOwner(owner);
        // Kevin will look into it.
        if (!territory.getData().getGameName().equals("gameExample") && !territory.getData().getGameName().equals("test")) {
            // set the original owner
            final TerritoryAttachment ta = TerritoryAttachment.get(territory);
            if (ta != null) {
                // If we already have an original owner set (ie: we set it previously in the attachment using originalOwner or
                // occupiedTerrOf),
                // then we DO NOT set the original owner again.
                // This is how we can have a game start with territories owned by 1 faction but controlled by a 2nd faction.
                final PlayerID currentOwner = ta.getOriginalOwner();
                if (currentOwner == null) {
                    ta.setOriginalOwner(owner);
                }
            }
        }
    }
}
Also used : TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment) Element(org.w3c.dom.Element)

Example 30 with TerritoryAttachment

use of games.strategy.triplea.attachments.TerritoryAttachment in project triplea by triplea-game.

the class TerritoryDetailPanel method territoryChanged.

private void territoryChanged(final Territory territory) {
    currentTerritory = territory;
    removeAll();
    refresh();
    if (territory == null) {
        return;
    }
    add(showOdds);
    final TerritoryAttachment ta = TerritoryAttachment.get(territory);
    final String labelText;
    if (ta == null) {
        labelText = "<html>" + territory.getName() + "<br>Water Territory" + "<br><br></html>";
    } else {
        labelText = "<html>" + ta.toStringForInfo(true, true) + "<br></html>";
    }
    add(new JLabel(labelText));
    gameData.acquireReadLock();
    Collection<Unit> unitsInTerritory;
    try {
        unitsInTerritory = territory.getUnits().getUnits();
    } finally {
        gameData.releaseReadLock();
    }
    add(new JLabel("Units: " + unitsInTerritory.size()));
    final JScrollPane scroll = new JScrollPane(unitsInTerritoryPanel(unitsInTerritory, uiContext));
    scroll.setBorder(BorderFactory.createEmptyBorder());
    scroll.getVerticalScrollBar().setUnitIncrement(20);
    add(scroll);
    refresh();
}
Also used : JScrollPane(javax.swing.JScrollPane) TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment) JLabel(javax.swing.JLabel) Unit(games.strategy.engine.data.Unit)

Aggregations

TerritoryAttachment (games.strategy.triplea.attachments.TerritoryAttachment)36 Territory (games.strategy.engine.data.Territory)29 Unit (games.strategy.engine.data.Unit)24 TripleAUnit (games.strategy.triplea.TripleAUnit)19 ArrayList (java.util.ArrayList)14 PlayerID (games.strategy.engine.data.PlayerID)13 GameData (games.strategy.engine.data.GameData)9 HashSet (java.util.HashSet)8 UnitAttachment (games.strategy.triplea.attachments.UnitAttachment)7 ProTerritory (games.strategy.triplea.ai.pro.data.ProTerritory)6 UnitType (games.strategy.engine.data.UnitType)5 ProBattleResult (games.strategy.triplea.ai.pro.data.ProBattleResult)5 CompositeChange (games.strategy.engine.data.CompositeChange)4 Resource (games.strategy.engine.data.Resource)4 ProOtherMoveOptions (games.strategy.triplea.ai.pro.data.ProOtherMoveOptions)4 PlayerAttachment (games.strategy.triplea.attachments.PlayerAttachment)4 IntegerMap (games.strategy.util.IntegerMap)4 RelationshipTracker (games.strategy.engine.data.RelationshipTracker)3 ProPlaceTerritory (games.strategy.triplea.ai.pro.data.ProPlaceTerritory)3 ProPurchaseTerritory (games.strategy.triplea.ai.pro.data.ProPurchaseTerritory)3