Search in sources :

Example 31 with PlayerID

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

the class UserActionAttachment method setActivateTrigger.

private void setActivateTrigger(final String value) throws GameParseException {
    // triggerName:numberOfTimes:useUses:testUses:testConditions:testChance
    final String[] s = value.split(":");
    if (s.length != 6) {
        throw new GameParseException("activateTrigger must have 6 parts: triggerName:numberOfTimes:useUses:testUses:testConditions:testChance" + thisErrorMsg());
    }
    TriggerAttachment trigger = null;
    for (final PlayerID player : getData().getPlayerList().getPlayers()) {
        for (final TriggerAttachment ta : TriggerAttachment.getTriggers(player, null)) {
            if (ta.getName().equals(s[0])) {
                trigger = ta;
                break;
            }
        }
        if (trigger != null) {
            break;
        }
    }
    if (trigger == null) {
        throw new GameParseException("No TriggerAttachment named: " + s[0] + thisErrorMsg());
    }
    String options = value;
    options = options.replaceFirst((s[0] + ":"), "");
    final int numberOfTimes = getInt(s[1]);
    if (numberOfTimes < 0) {
        throw new GameParseException("activateTrigger must be positive for the number of times to fire: " + s[1] + thisErrorMsg());
    }
    getBool(s[2]);
    getBool(s[3]);
    getBool(s[4]);
    getBool(s[5]);
    m_activateTrigger.add(Tuple.of(s[0], options));
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) GameParseException(games.strategy.engine.data.GameParseException)

Example 32 with PlayerID

use of games.strategy.engine.data.PlayerID 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 33 with PlayerID

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

the class AAInMoveUtil method fireAa.

/**
 * Fire the aa units in the given territory, hits are removed from units.
 */
private void fireAa(final Territory territory, final Collection<Unit> units, final UndoableMove currentMove) {
    if (units.isEmpty()) {
        return;
    }
    final PlayerID movingPlayer = movingPlayer(units);
    final HashMap<String, HashSet<UnitType>> airborneTechTargetsAllowed = TechAbilityAttachment.getAirborneTargettedByAa(movingPlayer, getData());
    final List<Unit> defendingAa = territory.getUnits().getMatches(Matches.unitIsAaThatCanFire(units, airborneTechTargetsAllowed, movingPlayer, Matches.unitIsAaForFlyOverOnly(), 1, true, getData()));
    // comes ordered alphabetically already
    final List<String> aaTypes = UnitAttachment.getAllOfTypeAas(defendingAa);
    // stacks are backwards
    Collections.reverse(aaTypes);
    for (final String currentTypeAa : aaTypes) {
        final Collection<Unit> currentPossibleAa = CollectionUtils.getMatches(defendingAa, Matches.unitIsAaOfTypeAa(currentTypeAa));
        final Set<UnitType> targetUnitTypesForThisTypeAa = UnitAttachment.get(currentPossibleAa.iterator().next().getType()).getTargetsAa(getData());
        final Set<UnitType> airborneTypesTargettedToo = airborneTechTargetsAllowed.get(currentTypeAa);
        final Collection<Unit> validTargetedUnitsForThisRoll = CollectionUtils.getMatches(units, Matches.unitIsOfTypes(targetUnitTypesForThisTypeAa).or(Matches.unitIsAirborne().and(Matches.unitIsOfTypes(airborneTypesTargettedToo))));
        // once we fire the AA guns, we can't undo
        // otherwise you could keep undoing and redoing
        // until you got the roll you wanted
        currentMove.setCantUndo("Move cannot be undone after " + currentTypeAa + " has fired.");
        final DiceRoll[] dice = new DiceRoll[1];
        final IExecutable rollDice = new IExecutable() {

            private static final long serialVersionUID = 4714364489659654758L;

            @Override
            public void execute(final ExecutionStack stack, final IDelegateBridge bridge) {
                // get rid of units already killed, so we don't target them twice
                validTargetedUnitsForThisRoll.removeAll(m_casualties);
                if (!validTargetedUnitsForThisRoll.isEmpty()) {
                    dice[0] = DiceRoll.rollAa(validTargetedUnitsForThisRoll, currentPossibleAa, AAInMoveUtil.this.bridge, territory, true);
                }
            }
        };
        final IExecutable selectCasualties = new IExecutable() {

            private static final long serialVersionUID = -8633263235214834617L;

            @Override
            public void execute(final ExecutionStack stack, final IDelegateBridge bridge) {
                if (!validTargetedUnitsForThisRoll.isEmpty()) {
                    final int hitCount = dice[0].getHits();
                    if (hitCount == 0) {
                        if (currentTypeAa.equals("AA")) {
                            AAInMoveUtil.this.bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_BATTLE_AA_MISS, findDefender(currentPossibleAa, territory));
                        } else {
                            AAInMoveUtil.this.bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_BATTLE_X_PREFIX + currentTypeAa.toLowerCase() + SoundPath.CLIP_BATTLE_X_MISS, findDefender(currentPossibleAa, territory));
                        }
                        getRemotePlayer().reportMessage("No " + currentTypeAa + " hits in " + territory.getName(), "No " + currentTypeAa + " hits in " + territory.getName());
                    } else {
                        if (currentTypeAa.equals("AA")) {
                            AAInMoveUtil.this.bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_BATTLE_AA_HIT, findDefender(currentPossibleAa, territory));
                        } else {
                            AAInMoveUtil.this.bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_BATTLE_X_PREFIX + currentTypeAa.toLowerCase() + SoundPath.CLIP_BATTLE_X_HIT, findDefender(currentPossibleAa, territory));
                        }
                        selectCasualties(dice[0], units, validTargetedUnitsForThisRoll, currentPossibleAa, defendingAa, territory, currentTypeAa);
                    }
                }
            }
        };
        // push in reverse order of execution
        m_executionStack.push(selectCasualties);
        m_executionStack.push(rollDice);
    }
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) Unit(games.strategy.engine.data.Unit) UnitType(games.strategy.engine.data.UnitType) HashSet(java.util.HashSet) IDelegateBridge(games.strategy.engine.delegate.IDelegateBridge)

Example 34 with PlayerID

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

the class AbstractEndTurnDelegate method rollWarBondsForFriends.

private String rollWarBondsForFriends(final IDelegateBridge delegateBridge, final PlayerID player, final GameData data) {
    final int count = TechAbilityAttachment.getWarBondDiceNumber(player, data);
    final int sides = TechAbilityAttachment.getWarBondDiceSides(player, data);
    if (sides <= 0 || count <= 0) {
        return "";
    }
    // basically, if we are sharing our technology with someone, and we have warbonds but they do not, then we roll our
    // warbonds and give
    // them the proceeds (Global 1940)
    final PlayerAttachment playerattachment = PlayerAttachment.get(player);
    if (playerattachment == null) {
        return "";
    }
    final Collection<PlayerID> shareWith = playerattachment.getShareTechnology();
    if (shareWith == null || shareWith.isEmpty()) {
        return "";
    }
    // take first one
    PlayerID giveWarBondsTo = null;
    for (final PlayerID p : shareWith) {
        final int diceCount = TechAbilityAttachment.getWarBondDiceNumber(p, data);
        final int diceSides = TechAbilityAttachment.getWarBondDiceSides(p, data);
        if (diceSides <= 0 && diceCount <= 0) {
            // they cannot have this tech)
            if (canPlayerCollectIncome(p, data)) {
                giveWarBondsTo = p;
                break;
            }
        }
    }
    if (giveWarBondsTo == null) {
        return "";
    }
    final String annotation = player.getName() + " rolling to resolve War Bonds, and giving results to " + giveWarBondsTo.getName() + ": ";
    final DiceRoll dice = DiceRoll.rollNDice(delegateBridge, count, sides, player, DiceType.NONCOMBAT, annotation);
    int totalWarBonds = 0;
    for (int i = 0; i < dice.size(); i++) {
        totalWarBonds += dice.getDie(i).getValue() + 1;
    }
    final Resource pus = data.getResourceList().getResource(Constants.PUS);
    final int currentPUs = giveWarBondsTo.getResources().getQuantity(pus);
    final String transcriptText = player.getName() + " rolls " + totalWarBonds + MyFormatter.pluralize(" PU", totalWarBonds) + " from War Bonds, giving the total to " + giveWarBondsTo.getName() + ", who ends with " + (currentPUs + totalWarBonds) + MyFormatter.pluralize(" PU", (currentPUs + totalWarBonds)) + " total";
    delegateBridge.getHistoryWriter().startEvent(transcriptText);
    final Change change = ChangeFactory.changeResourcesChange(giveWarBondsTo, pus, totalWarBonds);
    delegateBridge.addChange(change);
    getRemotePlayer(player).reportMessage(annotation + MyFormatter.asDice(dice), annotation + MyFormatter.asDice(dice));
    return transcriptText + "<br />";
}
Also used : PlayerAttachment(games.strategy.triplea.attachments.PlayerAttachment) PlayerID(games.strategy.engine.data.PlayerID) Resource(games.strategy.engine.data.Resource) CompositeChange(games.strategy.engine.data.CompositeChange) Change(games.strategy.engine.data.Change)

Example 35 with PlayerID

use of games.strategy.engine.data.PlayerID 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)

Aggregations

PlayerID (games.strategy.engine.data.PlayerID)323 Territory (games.strategy.engine.data.Territory)163 Unit (games.strategy.engine.data.Unit)133 Test (org.junit.jupiter.api.Test)122 TripleAUnit (games.strategy.triplea.TripleAUnit)104 ITestDelegateBridge (games.strategy.engine.data.ITestDelegateBridge)94 GameData (games.strategy.engine.data.GameData)90 ArrayList (java.util.ArrayList)79 UnitType (games.strategy.engine.data.UnitType)74 Route (games.strategy.engine.data.Route)67 ScriptedRandomSource (games.strategy.engine.random.ScriptedRandomSource)46 HashSet (java.util.HashSet)44 Change (games.strategy.engine.data.Change)29 CompositeChange (games.strategy.engine.data.CompositeChange)29 IntegerMap (games.strategy.util.IntegerMap)29 List (java.util.List)29 HashMap (java.util.HashMap)28 Collection (java.util.Collection)27 Resource (games.strategy.engine.data.Resource)25 UnitAttachment (games.strategy.triplea.attachments.UnitAttachment)23