Search in sources :

Example 21 with GameData

use of games.strategy.engine.data.GameData in project triplea by triplea-game.

the class PoliticsDelegate method actionIsAccepted.

/**
 * Get a list of players that should accept this action and then ask each
 * player if it accepts this action.
 *
 * @param paa
 *        the politicalActionAttachment that should be accepted
 */
private boolean actionIsAccepted(final PoliticalActionAttachment paa) {
    final GameData data = getData();
    final Predicate<PoliticalActionAttachment> intoAlliedChainOrIntoOrOutOfWar = Matches.politicalActionIsRelationshipChangeOf(null, Matches.relationshipTypeIsAlliedAndAlliancesCanChainTogether().negate(), Matches.relationshipTypeIsAlliedAndAlliancesCanChainTogether(), data).or(Matches.politicalActionIsRelationshipChangeOf(null, Matches.relationshipTypeIsAtWar().negate(), Matches.relationshipTypeIsAtWar(), data)).or(Matches.politicalActionIsRelationshipChangeOf(null, Matches.relationshipTypeIsAtWar(), Matches.relationshipTypeIsAtWar().negate(), data));
    if (!Properties.getAlliancesCanChainTogether(data) || !intoAlliedChainOrIntoOrOutOfWar.test(paa)) {
        for (final PlayerID player : paa.getActionAccept()) {
            if (!(getRemotePlayer(player)).acceptAction(this.player, PoliticsText.getInstance().getAcceptanceQuestion(paa.getText()), true)) {
                return false;
            }
        }
    } else {
        // if alliances chain together, then our allies must have a say in anyone becoming a new ally/enemy
        final LinkedHashSet<PlayerID> playersWhoNeedToAccept = new LinkedHashSet<>();
        playersWhoNeedToAccept.addAll(paa.getActionAccept());
        playersWhoNeedToAccept.addAll(CollectionUtils.getMatches(data.getPlayerList().getPlayers(), Matches.isAlliedAndAlliancesCanChainTogether(player, data)));
        for (final PlayerID player : paa.getActionAccept()) {
            playersWhoNeedToAccept.addAll(CollectionUtils.getMatches(data.getPlayerList().getPlayers(), Matches.isAlliedAndAlliancesCanChainTogether(player, data)));
        }
        playersWhoNeedToAccept.removeAll(paa.getActionAccept());
        for (final PlayerID player : playersWhoNeedToAccept) {
            String actionText = PoliticsText.getInstance().getAcceptanceQuestion(paa.getText());
            if (actionText.equals("NONE")) {
                actionText = this.player.getName() + " wants to take the following action: " + MyFormatter.attachmentNameToText(paa.getName()) + " \r\n Do you approve?";
            } else {
                actionText = this.player.getName() + " wants to take the following action: " + MyFormatter.attachmentNameToText(paa.getName()) + ".  Do you approve? \r\n\r\n " + this.player.getName() + " will ask " + MyFormatter.defaultNamedToTextList(paa.getActionAccept()) + ", the following question: \r\n " + actionText;
            }
            if (!(getRemotePlayer(player)).acceptAction(this.player, actionText, true)) {
                return false;
            }
        }
        for (final PlayerID player : paa.getActionAccept()) {
            if (!(getRemotePlayer(player)).acceptAction(this.player, PoliticsText.getInstance().getAcceptanceQuestion(paa.getText()), true)) {
                return false;
            }
        }
    }
    return true;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) PlayerID(games.strategy.engine.data.PlayerID) PoliticalActionAttachment(games.strategy.triplea.attachments.PoliticalActionAttachment) GameData(games.strategy.engine.data.GameData)

Example 22 with GameData

use of games.strategy.engine.data.GameData in project triplea by triplea-game.

the class AAInMoveUtil method getTerritoriesWhereAaWillFire.

Collection<Territory> getTerritoriesWhereAaWillFire(final Route route, final Collection<Unit> units) {
    final boolean alwaysOnAa = isAlwaysOnAaEnabled();
    // Just the attacked territory will have AA firing
    if (!alwaysOnAa && isAaTerritoryRestricted()) {
        return Collections.emptyList();
    }
    final GameData data = getData();
    // No AA in nonCombat unless 'Always on AA'
    if (GameStepPropertiesHelper.isNonCombatMove(data, false) && !alwaysOnAa) {
        return Collections.emptyList();
    }
    // can't rely on m_player being the unit owner in Edit Mode
    // look at the units being moved to determine allies and enemies
    final PlayerID movingPlayer = movingPlayer(units);
    final HashMap<String, HashSet<UnitType>> airborneTechTargetsAllowed = TechAbilityAttachment.getAirborneTargettedByAa(movingPlayer, data);
    // don't iterate over the end
    // that will be a battle
    // and handled else where in this tangled mess
    final Predicate<Unit> hasAa = Matches.unitIsAaThatCanFire(units, airborneTechTargetsAllowed, movingPlayer, Matches.unitIsAaForFlyOverOnly(), 1, true, data);
    // AA guns in transports shouldn't be able to fire
    final List<Territory> territoriesWhereAaWillFire = new ArrayList<>();
    for (final Territory current : route.getMiddleSteps()) {
        if (current.getUnits().anyMatch(hasAa)) {
            territoriesWhereAaWillFire.add(current);
        }
    }
    if (Properties.getForceAaAttacksForLastStepOfFlyOver(data)) {
        if (route.getEnd().getUnits().anyMatch(hasAa)) {
            territoriesWhereAaWillFire.add(route.getEnd());
        }
    } else {
        // fire
        if (route.getStart().getUnits().anyMatch(hasAa) && !getBattleTracker().wasBattleFought(route.getStart())) {
            territoriesWhereAaWillFire.add(route.getStart());
        }
    }
    return territoriesWhereAaWillFire;
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) ArrayList(java.util.ArrayList) Unit(games.strategy.engine.data.Unit) HashSet(java.util.HashSet)

Example 23 with GameData

use of games.strategy.engine.data.GameData in project triplea by triplea-game.

the class AbstractEndTurnDelegate method start.

@Override
public void start() {
    // figure out our current PUs before we do anything else, including super methods
    final GameData data = bridge.getData();
    final Resource pus = data.getResourceList().getResource(Constants.PUS);
    final int leftOverPUs = bridge.getPlayerId().getResources().getQuantity(pus);
    final IntegerMap<Resource> leftOverResources = bridge.getPlayerId().getResources().getResourcesCopy();
    super.start();
    if (!needToInitialize) {
        return;
    }
    final StringBuilder endTurnReport = new StringBuilder();
    hasPostedTurnSummary = false;
    final PlayerAttachment pa = PlayerAttachment.get(player);
    // can't collect unless you own your own capital
    if (!canPlayerCollectIncome(player, data)) {
        endTurnReport.append(rollWarBondsForFriends(bridge, player, data));
    // we do not collect any income this turn
    } else {
        // just collect resources
        final Collection<Territory> territories = data.getMap().getTerritoriesOwnedBy(player);
        int toAdd = getProduction(territories);
        final int blockadeLoss = getBlockadeProductionLoss(player, data, bridge, endTurnReport);
        toAdd -= blockadeLoss;
        toAdd *= Properties.getPuMultiplier(data);
        int total = player.getResources().getQuantity(pus) + toAdd;
        final String transcriptText;
        if (blockadeLoss == 0) {
            transcriptText = player.getName() + " collect " + toAdd + MyFormatter.pluralize(" PU", toAdd) + "; end with " + total + MyFormatter.pluralize(" PU", total);
        } else {
            transcriptText = player.getName() + " collect " + toAdd + MyFormatter.pluralize(" PU", toAdd) + " (" + blockadeLoss + " lost to blockades)" + "; end with " + total + MyFormatter.pluralize(" PU", total);
        }
        bridge.getHistoryWriter().startEvent(transcriptText);
        endTurnReport.append(transcriptText).append("<br />");
        // do war bonds
        final int bonds = rollWarBonds(bridge, player, data);
        if (bonds > 0) {
            total += bonds;
            toAdd += bonds;
            final String bondText = player.getName() + " collect " + bonds + MyFormatter.pluralize(" PU", bonds) + " from War Bonds; end with " + total + MyFormatter.pluralize(" PU", total);
            bridge.getHistoryWriter().startEvent(bondText);
            endTurnReport.append("<br />").append(bondText).append("<br />");
        }
        if (total < 0) {
            toAdd -= total;
        }
        final Change change = ChangeFactory.changeResourcesChange(player, pus, toAdd);
        bridge.addChange(change);
        if (data.getProperties().get(Constants.PACIFIC_THEATER, false) && pa != null) {
            final Change changeVp = (ChangeFactory.attachmentPropertyChange(pa, (pa.getVps() + (toAdd / 10) + (pa.getCaptureVps() / 10)), "vps"));
            final Change changeCaptureVp = ChangeFactory.attachmentPropertyChange(pa, "0", "captureVps");
            final CompositeChange ccVp = new CompositeChange(changeVp, changeCaptureVp);
            bridge.addChange(ccVp);
        }
        endTurnReport.append("<br />").append(addOtherResources(bridge));
        endTurnReport.append("<br />").append(doNationalObjectivesAndOtherEndTurnEffects(bridge));
        final IntegerMap<Resource> income = player.getResources().getResourcesCopy();
        income.subtract(leftOverResources);
        endTurnReport.append("<br />").append(BonusIncomeUtils.addBonusIncome(income, bridge, player));
        // now we do upkeep costs, including upkeep cost as a percentage of our entire income for this turn (including
        // NOs)
        final int currentPUs = player.getResources().getQuantity(pus);
        int relationshipUpkeepCostFlat = 0;
        int relationshipUpkeepCostPercentage = 0;
        for (final Relationship r : data.getRelationshipTracker().getRelationships(player)) {
            final String[] upkeep = r.getRelationshipType().getRelationshipTypeAttachment().getUpkeepCost().split(":");
            if (upkeep.length == 1 || upkeep[1].equals(RelationshipTypeAttachment.UPKEEP_FLAT)) {
                relationshipUpkeepCostFlat += Integer.parseInt(upkeep[0]);
            } else if (upkeep[1].equals(RelationshipTypeAttachment.UPKEEP_PERCENTAGE)) {
                relationshipUpkeepCostPercentage += Integer.parseInt(upkeep[0]);
            }
        }
        relationshipUpkeepCostPercentage = Math.min(100, relationshipUpkeepCostPercentage);
        int relationshipUpkeepTotalCost = 0;
        if (relationshipUpkeepCostPercentage != 0) {
            final float gainedPus = Math.max(0, currentPUs - leftOverPUs);
            relationshipUpkeepTotalCost += Math.round(gainedPus * (relationshipUpkeepCostPercentage) / 100f);
        }
        if (relationshipUpkeepCostFlat != 0) {
            relationshipUpkeepTotalCost += relationshipUpkeepCostFlat;
        }
        // we can't remove more than we have, and we also must flip the sign
        relationshipUpkeepTotalCost = Math.min(currentPUs, relationshipUpkeepTotalCost);
        relationshipUpkeepTotalCost = -1 * relationshipUpkeepTotalCost;
        if (relationshipUpkeepTotalCost != 0) {
            final int newTotal = currentPUs + relationshipUpkeepTotalCost;
            final String transcriptText2 = player.getName() + (relationshipUpkeepTotalCost < 0 ? " pays " : " taxes ") + (-1 * relationshipUpkeepTotalCost) + MyFormatter.pluralize(" PU", relationshipUpkeepTotalCost) + " in order to maintain current relationships with other players, and ends the turn with " + newTotal + MyFormatter.pluralize(" PU", newTotal);
            bridge.getHistoryWriter().startEvent(transcriptText2);
            endTurnReport.append("<br />").append(transcriptText2).append("<br />");
            final Change upkeep = ChangeFactory.changeResourcesChange(player, pus, relationshipUpkeepTotalCost);
            bridge.addChange(upkeep);
        }
    }
    if (GameStepPropertiesHelper.isRepairUnits(data)) {
        MoveDelegate.repairMultipleHitPointUnits(bridge, bridge.getPlayerId());
    }
    if (isGiveUnitsByTerritory() && pa != null && pa.getGiveUnitControl() != null && !pa.getGiveUnitControl().isEmpty()) {
        changeUnitOwnership(bridge);
    }
    needToInitialize = false;
    showEndTurnReport(endTurnReport.toString());
}
Also used : Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) Resource(games.strategy.engine.data.Resource) CompositeChange(games.strategy.engine.data.CompositeChange) Change(games.strategy.engine.data.Change) PlayerAttachment(games.strategy.triplea.attachments.PlayerAttachment) Relationship(games.strategy.engine.data.RelationshipTracker.Relationship) CompositeChange(games.strategy.engine.data.CompositeChange)

Example 24 with GameData

use of games.strategy.engine.data.GameData in project triplea by triplea-game.

the class EndTurnDelegate method createUnits.

private String createUnits(final IDelegateBridge bridge) {
    final StringBuilder endTurnReport = new StringBuilder();
    final GameData data = getData();
    final PlayerID player = data.getSequence().getStep().getPlayerId();
    final Predicate<Unit> myCreatorsMatch = Matches.unitIsOwnedBy(player).and(Matches.unitCreatesUnits());
    final CompositeChange change = new CompositeChange();
    for (final Territory t : data.getMap().getTerritories()) {
        final Collection<Unit> myCreators = CollectionUtils.getMatches(t.getUnits().getUnits(), myCreatorsMatch);
        if (myCreators != null && !myCreators.isEmpty()) {
            final Collection<Unit> toAdd = new ArrayList<>();
            final Collection<Unit> toAddSea = new ArrayList<>();
            final Collection<Unit> toAddLand = new ArrayList<>();
            for (final Unit u : myCreators) {
                final UnitAttachment ua = UnitAttachment.get(u.getType());
                final IntegerMap<UnitType> createsUnitsMap = ua.getCreatesUnitsList();
                final Collection<UnitType> willBeCreated = createsUnitsMap.keySet();
                for (final UnitType ut : willBeCreated) {
                    if (UnitAttachment.get(ut).getIsSea() && Matches.territoryIsLand().test(t)) {
                        toAddSea.addAll(ut.create(createsUnitsMap.getInt(ut), player));
                    } else if (!UnitAttachment.get(ut).getIsSea() && !UnitAttachment.get(ut).getIsAir() && Matches.territoryIsWater().test(t)) {
                        toAddLand.addAll(ut.create(createsUnitsMap.getInt(ut), player));
                    } else {
                        toAdd.addAll(ut.create(createsUnitsMap.getInt(ut), player));
                    }
                }
            }
            if (!toAdd.isEmpty()) {
                final String transcriptText = player.getName() + " creates " + MyFormatter.unitsToTextNoOwner(toAdd) + " in " + t.getName();
                bridge.getHistoryWriter().startEvent(transcriptText, toAdd);
                endTurnReport.append(transcriptText).append("<br />");
                final Change place = ChangeFactory.addUnits(t, toAdd);
                change.add(place);
            }
            if (!toAddSea.isEmpty()) {
                final Predicate<Territory> myTerrs = Matches.territoryIsWater();
                final Collection<Territory> waterNeighbors = data.getMap().getNeighbors(t, myTerrs);
                if (waterNeighbors != null && !waterNeighbors.isEmpty()) {
                    final Territory tw = getRandomTerritory(waterNeighbors, bridge);
                    final String transcriptText = player.getName() + " creates " + MyFormatter.unitsToTextNoOwner(toAddSea) + " in " + tw.getName();
                    bridge.getHistoryWriter().startEvent(transcriptText, toAddSea);
                    endTurnReport.append(transcriptText).append("<br />");
                    final Change place = ChangeFactory.addUnits(tw, toAddSea);
                    change.add(place);
                }
            }
            if (!toAddLand.isEmpty()) {
                final Predicate<Territory> myTerrs = Matches.isTerritoryOwnedBy(player).and(Matches.territoryIsLand());
                final Collection<Territory> landNeighbors = data.getMap().getNeighbors(t, myTerrs);
                if (landNeighbors != null && !landNeighbors.isEmpty()) {
                    final Territory tl = getRandomTerritory(landNeighbors, bridge);
                    final String transcriptText = player.getName() + " creates " + MyFormatter.unitsToTextNoOwner(toAddLand) + " in " + tl.getName();
                    bridge.getHistoryWriter().startEvent(transcriptText, toAddLand);
                    endTurnReport.append(transcriptText).append("<br />");
                    final Change place = ChangeFactory.addUnits(tl, toAddLand);
                    change.add(place);
                }
            }
        }
    }
    if (!change.isEmpty()) {
        bridge.addChange(change);
    }
    return endTurnReport.toString();
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) ArrayList(java.util.ArrayList) CompositeChange(games.strategy.engine.data.CompositeChange) Change(games.strategy.engine.data.Change) Unit(games.strategy.engine.data.Unit) UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) UnitType(games.strategy.engine.data.UnitType) CompositeChange(games.strategy.engine.data.CompositeChange)

Example 25 with GameData

use of games.strategy.engine.data.GameData in project triplea by triplea-game.

the class EndTurnDelegate method addOtherResources.

@Override
protected String addOtherResources(final IDelegateBridge bridge) {
    final StringBuilder endTurnReport = new StringBuilder();
    final GameData data = bridge.getData();
    final CompositeChange change = new CompositeChange();
    final Collection<Territory> territories = data.getMap().getTerritoriesOwnedBy(player);
    final IntegerMap<Resource> production = getResourceProduction(territories, data);
    for (final Entry<Resource, Integer> resource : production.entrySet()) {
        final Resource r = resource.getKey();
        int toAdd = resource.getValue();
        int total = player.getResources().getQuantity(r) + toAdd;
        if (total < 0) {
            toAdd -= total;
            total = 0;
        }
        final String resourceText = player.getName() + " collects " + toAdd + " " + MyFormatter.pluralize(r.getName(), toAdd) + "; ends with " + total + " " + MyFormatter.pluralize(r.getName(), total) + " total";
        bridge.getHistoryWriter().startEvent(resourceText);
        endTurnReport.append(resourceText).append("<br />");
        change.add(ChangeFactory.changeResourcesChange(player, r, toAdd));
    }
    if (!change.isEmpty()) {
        bridge.addChange(change);
    }
    return endTurnReport.toString();
}
Also used : Territory(games.strategy.engine.data.Territory) GameData(games.strategy.engine.data.GameData) Resource(games.strategy.engine.data.Resource) CompositeChange(games.strategy.engine.data.CompositeChange)

Aggregations

GameData (games.strategy.engine.data.GameData)204 Unit (games.strategy.engine.data.Unit)100 PlayerID (games.strategy.engine.data.PlayerID)92 Territory (games.strategy.engine.data.Territory)92 ArrayList (java.util.ArrayList)83 TripleAUnit (games.strategy.triplea.TripleAUnit)64 HashSet (java.util.HashSet)50 CompositeChange (games.strategy.engine.data.CompositeChange)40 List (java.util.List)36 HashMap (java.util.HashMap)32 Set (java.util.Set)32 Route (games.strategy.engine.data.Route)31 UnitAttachment (games.strategy.triplea.attachments.UnitAttachment)30 Collection (java.util.Collection)29 UnitType (games.strategy.engine.data.UnitType)26 Change (games.strategy.engine.data.Change)24 Test (org.junit.jupiter.api.Test)23 Resource (games.strategy.engine.data.Resource)22 TestMapGameData (games.strategy.triplea.xml.TestMapGameData)22 Map (java.util.Map)21