Search in sources :

Example 6 with IDelegateBridge

use of games.strategy.engine.delegate.IDelegateBridge in project triplea by triplea-game.

the class ProPurchaseUtils method canUnitsBePlaced.

public static boolean canUnitsBePlaced(final List<Unit> units, final PlayerID player, final Territory t, final boolean isBid) {
    final GameData data = ProData.getData();
    AbstractPlaceDelegate placeDelegate = (AbstractPlaceDelegate) data.getDelegateList().getDelegate("place");
    if (isBid) {
        placeDelegate = (AbstractPlaceDelegate) data.getDelegateList().getDelegate("placeBid");
    }
    final IDelegateBridge bridge = new ProDummyDelegateBridge(ProData.getProAi(), player, data);
    placeDelegate.setDelegateBridgeAndPlayer(bridge);
    final String s = placeDelegate.canUnitsBePlaced(t, units, player);
    return s == null;
}
Also used : GameData(games.strategy.engine.data.GameData) ProDummyDelegateBridge(games.strategy.triplea.ai.pro.simulate.ProDummyDelegateBridge) AbstractPlaceDelegate(games.strategy.triplea.delegate.AbstractPlaceDelegate) IDelegateBridge(games.strategy.engine.delegate.IDelegateBridge)

Example 7 with IDelegateBridge

use of games.strategy.engine.delegate.IDelegateBridge in project triplea by triplea-game.

the class BattleDelegate method setupTerritoriesAbandonedToTheEnemy.

/**
 * Setup the battles where we have abandoned a contested territory during combat move to the enemy.
 * The enemy then takes over the territory in question.
 */
private static void setupTerritoriesAbandonedToTheEnemy(final BattleTracker battleTracker, final IDelegateBridge bridge) {
    final GameData data = bridge.getData();
    if (!Properties.getAbandonedTerritoriesMayBeTakenOverImmediately(data)) {
        return;
    }
    final PlayerID player = bridge.getPlayerId();
    final List<Territory> battleTerritories = CollectionUtils.getMatches(data.getMap().getTerritories(), Matches.territoryIsNotUnownedWater().and(Matches.territoryHasEnemyUnitsThatCanCaptureItAndIsOwnedByTheirEnemy(player, data)));
    // all territories that contain enemy units, where the territory is owned by an enemy of these units
    for (final Territory territory : battleTerritories) {
        final List<Unit> abandonedToUnits = territory.getUnits().getMatches(Matches.enemyUnit(player, data));
        final PlayerID abandonedToPlayer = AbstractBattle.findPlayerWithMostUnits(abandonedToUnits);
        // now make sure to add any units that must move with these units, so that they get included as dependencies
        final Map<Unit, Collection<Unit>> transportMap = TransportTracker.transporting(territory.getUnits());
        abandonedToUnits.addAll(transportMap.entrySet().stream().filter(e -> abandonedToUnits.contains(e.getKey())).map(Entry::getValue).flatMap(Collection::stream).filter(Util.not(abandonedToUnits::contains)).collect(Collectors.toSet()));
        // either we have abandoned the territory (so there are no more units that are enemy units of our enemy units)
        // or we are possibly bombing the territory (so we may have units there still)
        final Set<Unit> enemyUnitsOfAbandonedToUnits = abandonedToUnits.stream().map(Unit::getOwner).map(p -> Matches.unitIsEnemyOf(data, p).and(Matches.unitIsNotAir()).and(Matches.unitIsNotInfrastructure())).map(territory.getUnits()::getMatches).flatMap(Collection::stream).collect(Collectors.toSet());
        // only look at bombing battles, because otherwise the normal attack will determine the ownership of the territory
        final IBattle bombingBattle = battleTracker.getPendingBattle(territory, true, null);
        if (bombingBattle != null) {
            enemyUnitsOfAbandonedToUnits.removeAll(bombingBattle.getAttackingUnits());
        }
        if (!enemyUnitsOfAbandonedToUnits.isEmpty()) {
            continue;
        }
        final IBattle nonFightingBattle = battleTracker.getPendingBattle(territory, false, BattleType.NORMAL);
        if (nonFightingBattle != null) {
            throw new IllegalStateException("Should not be possible to have a normal battle in: " + territory.getName() + " and have abandoned or only bombing there too.");
        }
        bridge.getHistoryWriter().startEvent(player.getName() + " has abandoned " + territory.getName() + " to " + abandonedToPlayer.getName(), abandonedToUnits);
        battleTracker.takeOver(territory, abandonedToPlayer, bridge, null, abandonedToUnits);
    // TODO: if there are multiple defending unit owners, allow picking which one takes over the territory
    }
}
Also used : DiceType(games.strategy.engine.random.IRandomStats.DiceType) WhoWon(games.strategy.triplea.delegate.IBattle.WhoWon) BattleRecord(games.strategy.triplea.delegate.dataObjects.BattleRecord) IRemote(games.strategy.engine.message.IRemote) UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) IBattleDelegate(games.strategy.triplea.delegate.remote.IBattleDelegate) HashMap(java.util.HashMap) PredicateBuilder(games.strategy.util.PredicateBuilder) Properties(games.strategy.triplea.Properties) Resource(games.strategy.engine.data.Resource) BattleListing(games.strategy.triplea.delegate.dataObjects.BattleListing) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Route(games.strategy.engine.data.Route) BattleType(games.strategy.triplea.delegate.IBattle.BattleType) TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment) IDelegateBridge(games.strategy.engine.delegate.IDelegateBridge) Map(java.util.Map) UnitType(games.strategy.engine.data.UnitType) PlayerAttachment(games.strategy.triplea.attachments.PlayerAttachment) TripleAUnit(games.strategy.triplea.TripleAUnit) CompositeChange(games.strategy.engine.data.CompositeChange) AutoSave(games.strategy.engine.delegate.AutoSave) CollectionUtils(games.strategy.util.CollectionUtils) IntegerMap(games.strategy.util.IntegerMap) BattleResults(games.strategy.triplea.oddsCalculator.ta.BattleResults) Unit(games.strategy.engine.data.Unit) Iterator(java.util.Iterator) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Territory(games.strategy.engine.data.Territory) Collectors(java.util.stream.Collectors) Util(games.strategy.util.Util) Serializable(java.io.Serializable) GameData(games.strategy.engine.data.GameData) ChangeFactory(games.strategy.engine.data.changefactory.ChangeFactory) List(java.util.List) Tuple(games.strategy.util.Tuple) PlayerID(games.strategy.engine.data.PlayerID) ResourceCollection(games.strategy.engine.data.ResourceCollection) Change(games.strategy.engine.data.Change) RouteScripted(games.strategy.engine.data.RouteScripted) MyFormatter(games.strategy.triplea.formatter.MyFormatter) ITripleAPlayer(games.strategy.triplea.player.ITripleAPlayer) Entry(java.util.Map.Entry) MapSupport(games.strategy.triplea.MapSupport) Collections(java.util.Collections) PlayerID(games.strategy.engine.data.PlayerID) Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) TripleAUnit(games.strategy.triplea.TripleAUnit) Unit(games.strategy.engine.data.Unit) Entry(java.util.Map.Entry) Collection(java.util.Collection) ResourceCollection(games.strategy.engine.data.ResourceCollection)

Example 8 with IDelegateBridge

use of games.strategy.engine.delegate.IDelegateBridge in project triplea by triplea-game.

the class BattleTracker method fightDefenselessBattles.

/**
 * Kill undefended transports. Done first to remove potentially dependent sea battles
 * Which could block amphibious assaults later
 */
public void fightDefenselessBattles(final IDelegateBridge bridge) {
    final GameData gameData = bridge.getData();
    // Here and below parameter "false" to getPendingBattleSites & getPendingBattle denote non-SBR battles
    for (final Territory territory : getPendingBattleSites(false)) {
        final IBattle battle = getPendingBattle(territory, false, BattleType.NORMAL);
        final List<Unit> defenders = new ArrayList<>(battle.getDefendingUnits());
        final List<Unit> sortedUnitsList = getSortedDefendingUnits(bridge, gameData, territory, defenders);
        if (getDependentOn(battle).isEmpty() && DiceRoll.getTotalPower(DiceRoll.getUnitPowerAndRollsForNormalBattles(sortedUnitsList, defenders, false, false, gameData, territory, TerritoryEffectHelper.getEffects(territory), false, null), gameData) == 0) {
            battle.fight(bridge);
        }
    }
    getPendingBattleSites(false).stream().map(territory -> getPendingBattle(territory, false, BattleType.NORMAL)).filter(NonFightingBattle.class::isInstance).filter(battle -> getDependentOn(battle).isEmpty()).forEach(battle -> battle.fight(bridge));
}
Also used : WhoWon(games.strategy.triplea.delegate.IBattle.WhoWon) BiFunction(java.util.function.BiFunction) GUID(games.strategy.net.GUID) Constants(games.strategy.triplea.Constants) BattleRecord(games.strategy.triplea.delegate.dataObjects.BattleRecord) UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) HashMap(java.util.HashMap) Properties(games.strategy.triplea.Properties) Supplier(java.util.function.Supplier) Resource(games.strategy.engine.data.Resource) BattleListing(games.strategy.triplea.delegate.dataObjects.BattleListing) TuvUtils(games.strategy.triplea.util.TuvUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Route(games.strategy.engine.data.Route) BattleType(games.strategy.triplea.delegate.IBattle.BattleType) BattleRecords(games.strategy.triplea.delegate.dataObjects.BattleRecords) TerritoryAttachment(games.strategy.triplea.attachments.TerritoryAttachment) IDelegateBridge(games.strategy.engine.delegate.IDelegateBridge) Map(java.util.Map) UnitType(games.strategy.engine.data.UnitType) PlayerAttachment(games.strategy.triplea.attachments.PlayerAttachment) RelationshipTracker(games.strategy.engine.data.RelationshipTracker) TripleAUnit(games.strategy.triplea.TripleAUnit) CompositeChange(games.strategy.engine.data.CompositeChange) CollectionUtils(games.strategy.util.CollectionUtils) IntegerMap(games.strategy.util.IntegerMap) RelationshipType(games.strategy.engine.data.RelationshipType) BattleResults(games.strategy.triplea.oddsCalculator.ta.BattleResults) Unit(games.strategy.engine.data.Unit) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Territory(games.strategy.engine.data.Territory) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) GameData(games.strategy.engine.data.GameData) ChangeFactory(games.strategy.engine.data.changefactory.ChangeFactory) List(java.util.List) Tuple(games.strategy.util.Tuple) PlayerID(games.strategy.engine.data.PlayerID) Change(games.strategy.engine.data.Change) MyFormatter(games.strategy.triplea.formatter.MyFormatter) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) SoundPath(games.strategy.sound.SoundPath) Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) ArrayList(java.util.ArrayList) TripleAUnit(games.strategy.triplea.TripleAUnit) Unit(games.strategy.engine.data.Unit)

Example 9 with IDelegateBridge

use of games.strategy.engine.delegate.IDelegateBridge in project triplea by triplea-game.

the class TriggerAttachment method triggerProductionFrontierEditChange.

public static void triggerProductionFrontierEditChange(final Set<TriggerAttachment> satisfiedTriggers, final IDelegateBridge bridge, final String beforeOrAfter, final String stepName, final boolean useUses, final boolean testUses, final boolean testChance, final boolean testWhen) {
    final GameData data = bridge.getData();
    Collection<TriggerAttachment> trigs = CollectionUtils.getMatches(satisfiedTriggers, prodFrontierEditMatch());
    if (testWhen) {
        trigs = CollectionUtils.getMatches(trigs, whenOrDefaultMatch(beforeOrAfter, stepName));
    }
    if (testUses) {
        trigs = CollectionUtils.getMatches(trigs, availableUses);
    }
    final CompositeChange change = new CompositeChange();
    for (final TriggerAttachment triggerAttachment : trigs) {
        if (testChance && !triggerAttachment.testChance(bridge)) {
            continue;
        }
        if (useUses) {
            triggerAttachment.use(bridge);
        }
        triggerAttachment.getProductionRule().stream().map(s -> s.split(":")).forEach(array -> {
            final ProductionFrontier front = data.getProductionFrontierList().getProductionFrontier(array[0]);
            final String rule = array[1];
            final String ruleName = rule.replaceFirst("^-", "");
            final ProductionRule productionRule = data.getProductionRuleList().getProductionRule(ruleName);
            final boolean ruleAdded = !rule.startsWith("-");
            if (ruleAdded) {
                if (!front.getRules().contains(productionRule)) {
                    change.add(ChangeFactory.addProductionRule(productionRule, front));
                    bridge.getHistoryWriter().startEvent(MyFormatter.attachmentNameToText(triggerAttachment.getName()) + ": " + productionRule.getName() + " added to " + front.getName());
                }
            } else {
                if (front.getRules().contains(productionRule)) {
                    change.add(ChangeFactory.removeProductionRule(productionRule, front));
                    bridge.getHistoryWriter().startEvent(MyFormatter.attachmentNameToText(triggerAttachment.getName()) + ": " + productionRule.getName() + " removed from " + front.getName());
                }
            }
        });
    }
    if (!change.isEmpty()) {
        // TODO: we should sort the frontier list if we make changes to it...
        bridge.addChange(change);
    }
}
Also used : BattleTracker(games.strategy.triplea.delegate.BattleTracker) ITripleADisplay(games.strategy.triplea.ui.display.ITripleADisplay) Constants(games.strategy.triplea.Constants) Properties(games.strategy.triplea.Properties) IAttachment(games.strategy.engine.data.IAttachment) MutableProperty(games.strategy.engine.data.MutableProperty) DelegateFinder(games.strategy.triplea.delegate.DelegateFinder) IDelegateBridge(games.strategy.engine.delegate.IDelegateBridge) Map(java.util.Map) IntegerMap(games.strategy.util.IntegerMap) GameParseException(games.strategy.engine.data.GameParseException) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Attachable(games.strategy.engine.data.Attachable) GameData(games.strategy.engine.data.GameData) List(java.util.List) Tuple(games.strategy.util.Tuple) PlayerID(games.strategy.engine.data.PlayerID) ProductionFrontier(games.strategy.engine.data.ProductionFrontier) Matches(games.strategy.triplea.delegate.Matches) MyFormatter(games.strategy.triplea.formatter.MyFormatter) MapSupport(games.strategy.triplea.MapSupport) TerritoryEffect(games.strategy.engine.data.TerritoryEffect) TechTracker(games.strategy.triplea.delegate.TechTracker) HashMap(java.util.HashMap) Resource(games.strategy.engine.data.Resource) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) UnitType(games.strategy.engine.data.UnitType) CompositeChange(games.strategy.engine.data.CompositeChange) TechnologyFrontier(games.strategy.engine.data.TechnologyFrontier) CollectionUtils(games.strategy.util.CollectionUtils) TechAdvance(games.strategy.triplea.delegate.TechAdvance) RelationshipType(games.strategy.engine.data.RelationshipType) Unit(games.strategy.engine.data.Unit) Territory(games.strategy.engine.data.Territory) IDelegate(games.strategy.engine.delegate.IDelegate) ClientLogger(games.strategy.debug.ClientLogger) ChangeFactory(games.strategy.engine.data.changefactory.ChangeFactory) NotificationMessages(games.strategy.triplea.ui.NotificationMessages) Change(games.strategy.engine.data.Change) EndRoundDelegate(games.strategy.triplea.delegate.EndRoundDelegate) OriginalOwnerTracker(games.strategy.triplea.delegate.OriginalOwnerTracker) ProductionRule(games.strategy.engine.data.ProductionRule) AbstractMoveDelegate(games.strategy.triplea.delegate.AbstractMoveDelegate) Collections(java.util.Collections) SoundPath(games.strategy.sound.SoundPath) GameData(games.strategy.engine.data.GameData) ProductionRule(games.strategy.engine.data.ProductionRule) CompositeChange(games.strategy.engine.data.CompositeChange) ProductionFrontier(games.strategy.engine.data.ProductionFrontier)

Example 10 with IDelegateBridge

use of games.strategy.engine.delegate.IDelegateBridge in project triplea by triplea-game.

the class ProAi method purchase.

@Override
protected void purchase(final boolean purchaseForBid, final int pusToSpend, final IPurchaseDelegate purchaseDelegate, final GameData data, final PlayerID player) {
    final long start = System.currentTimeMillis();
    BattleCalculator.clearOolCache();
    ProLogUi.notifyStartOfRound(data.getSequence().getRound(), player.getName());
    initializeData();
    if (pusToSpend <= 0) {
        return;
    }
    if (purchaseForBid) {
        calc.setData(data);
        storedPurchaseTerritories = purchaseAi.bid(pusToSpend, purchaseDelegate, data);
    } else {
        // Repair factories
        purchaseAi.repair(pusToSpend, purchaseDelegate, data, player);
        // Check if any place territories exist
        final Map<Territory, ProPurchaseTerritory> purchaseTerritories = ProPurchaseUtils.findPurchaseTerritories(player);
        final List<Territory> possibleFactoryTerritories = CollectionUtils.getMatches(data.getMap().getTerritories(), ProMatches.territoryHasNoInfraFactoryAndIsNotConqueredOwnedLand(player, data));
        if (purchaseTerritories.isEmpty() && possibleFactoryTerritories.isEmpty()) {
            ProLogger.info("No possible place or factory territories owned so exiting purchase logic");
            return;
        }
        ProLogger.info("Starting simulation for purchase phase");
        // Setup data copy and delegates
        GameData dataCopy;
        try {
            data.acquireReadLock();
            dataCopy = GameDataUtils.cloneGameData(data, true);
        } catch (final Throwable t) {
            ProLogger.log(Level.WARNING, "Error trying to clone game data for simulating phases", t);
            return;
        } finally {
            data.releaseReadLock();
        }
        calc.setData(dataCopy);
        final PlayerID playerCopy = dataCopy.getPlayerList().getPlayerId(player.getName());
        final IMoveDelegate moveDel = DelegateFinder.moveDelegate(dataCopy);
        final IDelegateBridge bridge = new ProDummyDelegateBridge(this, playerCopy, dataCopy);
        moveDel.setDelegateBridgeAndPlayer(bridge);
        // Determine turn sequence
        final List<GameStep> gameSteps = new ArrayList<>();
        for (final GameStep gameStep : dataCopy.getSequence()) {
            gameSteps.add(gameStep);
        }
        // Simulate the next phases until place/end of turn is reached then use simulated data for purchase
        final int nextStepIndex = dataCopy.getSequence().getStepIndex() + 1;
        for (int i = nextStepIndex; i < gameSteps.size(); i++) {
            final GameStep step = gameSteps.get(i);
            if (!playerCopy.equals(step.getPlayerId())) {
                continue;
            }
            dataCopy.getSequence().setRoundAndStep(dataCopy.getSequence().getRound(), step.getDisplayName(), step.getPlayerId());
            final String stepName = step.getName();
            ProLogger.info("Simulating phase: " + stepName);
            if (stepName.endsWith("NonCombatMove")) {
                ProData.initializeSimulation(this, dataCopy, playerCopy);
                final Map<Territory, ProTerritory> factoryMoveMap = nonCombatMoveAi.simulateNonCombatMove(moveDel);
                if (storedFactoryMoveMap == null) {
                    storedFactoryMoveMap = ProSimulateTurnUtils.transferMoveMap(factoryMoveMap, data, player);
                }
            } else if (stepName.endsWith("CombatMove") && !stepName.endsWith("AirborneCombatMove")) {
                ProData.initializeSimulation(this, dataCopy, playerCopy);
                final Map<Territory, ProTerritory> moveMap = combatMoveAi.doCombatMove(moveDel);
                if (storedCombatMoveMap == null) {
                    storedCombatMoveMap = ProSimulateTurnUtils.transferMoveMap(moveMap, data, player);
                }
            } else if (stepName.endsWith("Battle")) {
                ProData.initializeSimulation(this, dataCopy, playerCopy);
                ProSimulateTurnUtils.simulateBattles(dataCopy, playerCopy, bridge, calc);
            } else if (stepName.endsWith("Place") || stepName.endsWith("EndTurn")) {
                ProData.initializeSimulation(this, dataCopy, player);
                storedPurchaseTerritories = purchaseAi.purchase(purchaseDelegate, data);
                break;
            } else if (stepName.endsWith("Politics")) {
                ProData.initializeSimulation(this, dataCopy, player);
                final PoliticsDelegate politicsDelegate = DelegateFinder.politicsDelegate(dataCopy);
                politicsDelegate.setDelegateBridgeAndPlayer(bridge);
                final List<PoliticalActionAttachment> actions = politicsAi.politicalActions();
                if (storedPoliticalActions == null) {
                    storedPoliticalActions = actions;
                }
            }
        }
    }
    ProLogger.info(player.getName() + " time for purchase=" + (System.currentTimeMillis() - start));
}
Also used : IMoveDelegate(games.strategy.triplea.delegate.remote.IMoveDelegate) PlayerID(games.strategy.engine.data.PlayerID) ProPurchaseTerritory(games.strategy.triplea.ai.pro.data.ProPurchaseTerritory) ProTerritory(games.strategy.triplea.ai.pro.data.ProTerritory) Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) ProTerritory(games.strategy.triplea.ai.pro.data.ProTerritory) ArrayList(java.util.ArrayList) ProPurchaseTerritory(games.strategy.triplea.ai.pro.data.ProPurchaseTerritory) PoliticsDelegate(games.strategy.triplea.delegate.PoliticsDelegate) PoliticalActionAttachment(games.strategy.triplea.attachments.PoliticalActionAttachment) ProDummyDelegateBridge(games.strategy.triplea.ai.pro.simulate.ProDummyDelegateBridge) GameStep(games.strategy.engine.data.GameStep) Map(java.util.Map) HashMap(java.util.HashMap) IDelegateBridge(games.strategy.engine.delegate.IDelegateBridge)

Aggregations

IDelegateBridge (games.strategy.engine.delegate.IDelegateBridge)10 ArrayList (java.util.ArrayList)7 GameData (games.strategy.engine.data.GameData)6 Territory (games.strategy.engine.data.Territory)6 Unit (games.strategy.engine.data.Unit)6 HashSet (java.util.HashSet)6 Change (games.strategy.engine.data.Change)5 PlayerID (games.strategy.engine.data.PlayerID)5 HashMap (java.util.HashMap)5 CompositeChange (games.strategy.engine.data.CompositeChange)4 Resource (games.strategy.engine.data.Resource)4 UnitType (games.strategy.engine.data.UnitType)4 Collection (java.util.Collection)4 Map (java.util.Map)4 Route (games.strategy.engine.data.Route)3 ChangeFactory (games.strategy.engine.data.changefactory.ChangeFactory)3 Properties (games.strategy.triplea.Properties)3 TripleAUnit (games.strategy.triplea.TripleAUnit)3 MyFormatter (games.strategy.triplea.formatter.MyFormatter)3 CollectionUtils (games.strategy.util.CollectionUtils)3