Search in sources :

Example 26 with Territory

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

the class TriggerAttachment method setRemoveUnits.

private void setRemoveUnits(final String value) throws GameParseException {
    if (value == null) {
        m_removeUnits = null;
        return;
    }
    if (m_removeUnits == null) {
        m_removeUnits = new HashMap<>();
    }
    final String[] s = value.split(":");
    if (s.length < 1) {
        throw new GameParseException("Empty removeUnits list" + thisErrorMsg());
    }
    int count;
    int i = 0;
    try {
        count = getInt(s[0]);
        i++;
    } catch (final Exception e) {
        count = 1;
    }
    if (s.length < 1 || (s.length == 1 && count != -1)) {
        throw new GameParseException("Empty removeUnits list" + thisErrorMsg());
    }
    final Collection<Territory> territories = new ArrayList<>();
    final Territory terr = getData().getMap().getTerritory(s[i]);
    if (terr == null) {
        if (s[i].equalsIgnoreCase("all")) {
            territories.addAll(getData().getMap().getTerritories());
        } else {
            throw new GameParseException("Territory does not exist " + s[i] + thisErrorMsg());
        }
    } else {
        territories.add(terr);
    }
    i++;
    final IntegerMap<UnitType> map = new IntegerMap<>();
    for (; i < s.length; i++) {
        final Collection<UnitType> types = new ArrayList<>();
        final UnitType tp = getData().getUnitTypeList().getUnitType(s[i]);
        if (tp == null) {
            if (s[i].equalsIgnoreCase("all")) {
                types.addAll(getData().getUnitTypeList().getAllUnitTypes());
            } else {
                throw new GameParseException("UnitType does not exist " + s[i] + thisErrorMsg());
            }
        } else {
            types.add(tp);
        }
        for (final UnitType type : types) {
            map.add(type, count);
        }
    }
    for (final Territory t : territories) {
        if (m_removeUnits.containsKey(t)) {
            map.add(m_removeUnits.get(t));
        }
        m_removeUnits.put(t, map);
    }
}
Also used : IntegerMap(games.strategy.util.IntegerMap) Territory(games.strategy.engine.data.Territory) ArrayList(java.util.ArrayList) GameParseException(games.strategy.engine.data.GameParseException) GameParseException(games.strategy.engine.data.GameParseException) UnitType(games.strategy.engine.data.UnitType)

Example 27 with Territory

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

the class TriggerAttachment method setTerritories.

private void setTerritories(final String names) throws GameParseException {
    final String[] s = names.split(":");
    for (final String element : s) {
        final Territory terr = getData().getMap().getTerritory(element);
        if (terr == null) {
            throw new GameParseException("Could not find territory. name:" + element + thisErrorMsg());
        }
        m_territories.add(terr);
    }
}
Also used : Territory(games.strategy.engine.data.Territory) GameParseException(games.strategy.engine.data.GameParseException)

Example 28 with Territory

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

the class TriggerAttachment method triggerTerritoryPropertyChange.

public static void triggerTerritoryPropertyChange(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) {
    Collection<TriggerAttachment> trigs = CollectionUtils.getMatches(satisfiedTriggers, territoryPropertyMatch());
    if (testWhen) {
        trigs = CollectionUtils.getMatches(trigs, whenOrDefaultMatch(beforeOrAfter, stepName));
    }
    if (testUses) {
        trigs = CollectionUtils.getMatches(trigs, availableUses);
    }
    final CompositeChange change = new CompositeChange();
    final HashSet<Territory> territoriesNeedingReDraw = new HashSet<>();
    for (final TriggerAttachment t : trigs) {
        if (testChance && !t.testChance(bridge)) {
            continue;
        }
        if (useUses) {
            t.use(bridge);
        }
        for (final Tuple<String, String> property : t.getTerritoryProperty()) {
            for (final Territory territory : t.getTerritories()) {
                territoriesNeedingReDraw.add(territory);
                String newValue = property.getSecond();
                boolean clearFirst = false;
                // test if we are resetting the variable first, and if so, remove the leading "-reset-" or "-clear-"
                if (newValue.length() > 0 && (newValue.startsWith(PREFIX_CLEAR) || newValue.startsWith(PREFIX_RESET))) {
                    newValue = newValue.replaceFirst(PREFIX_CLEAR, "").replaceFirst(PREFIX_RESET, "");
                    clearFirst = true;
                }
                // covers TerritoryAttachment, CanalAttachment
                if (t.getTerritoryAttachmentName().getFirst().equals("TerritoryAttachment")) {
                    final TerritoryAttachment attachment = TerritoryAttachment.get(territory, t.getTerritoryAttachmentName().getSecond());
                    if (attachment == null) {
                        // water territories may not have an attachment, so this could be null
                        throw new IllegalStateException("Triggers: No territory attachment for:" + territory.getName());
                    }
                    if (newValue.equals(attachment.getRawPropertyString(property.getFirst()))) {
                        continue;
                    }
                    if (clearFirst && newValue.length() < 1) {
                        change.add(ChangeFactory.attachmentPropertyReset(attachment, property.getFirst()));
                    } else {
                        change.add(ChangeFactory.attachmentPropertyChange(attachment, newValue, property.getFirst(), clearFirst));
                    }
                    bridge.getHistoryWriter().startEvent(MyFormatter.attachmentNameToText(t.getName()) + ": Setting " + property.getFirst() + (newValue.length() > 0 ? " to " + newValue : " cleared ") + " for " + t.getTerritoryAttachmentName().getSecond() + " attached to " + territory.getName());
                } else if (t.getTerritoryAttachmentName().getFirst().equals("CanalAttachment")) {
                    final CanalAttachment attachment = CanalAttachment.get(territory, t.getTerritoryAttachmentName().getSecond());
                    if (newValue.equals(attachment.getRawPropertyString(property.getFirst()))) {
                        continue;
                    }
                    if (clearFirst && newValue.length() < 1) {
                        change.add(ChangeFactory.attachmentPropertyReset(attachment, property.getFirst()));
                    } else {
                        change.add(ChangeFactory.attachmentPropertyChange(attachment, newValue, property.getFirst(), clearFirst));
                    }
                    bridge.getHistoryWriter().startEvent(MyFormatter.attachmentNameToText(t.getName()) + ": Setting " + property.getFirst() + (newValue.length() > 0 ? " to " + newValue : " cleared ") + " for " + t.getTerritoryAttachmentName().getSecond() + " attached to " + territory.getName());
                }
            // TODO add other attachment changes here if they attach to a territory
            }
        }
    }
    if (!change.isEmpty()) {
        bridge.addChange(change);
        for (final Territory territory : territoriesNeedingReDraw) {
            territory.notifyAttachmentChanged();
        }
    }
}
Also used : Territory(games.strategy.engine.data.Territory) CompositeChange(games.strategy.engine.data.CompositeChange) HashSet(java.util.HashSet)

Example 29 with Territory

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

the class MoveDelegate method giveBonusMovementToUnits.

static Change giveBonusMovementToUnits(final PlayerID player, final GameData data, final Territory t) {
    final CompositeChange change = new CompositeChange();
    for (final Unit u : t.getUnits().getUnits()) {
        if (Matches.unitCanBeGivenBonusMovementByFacilitiesInItsTerritory(t, player, data).test(u)) {
            if (!Matches.isUnitAllied(player, data).test(u)) {
                continue;
            }
            int bonusMovement = Integer.MIN_VALUE;
            final Predicate<Unit> givesBonusUnit = Matches.alliedUnit(player, data).and(Matches.unitCanGiveBonusMovementToThisUnit(u));
            final Collection<Unit> givesBonusUnits = new ArrayList<>(CollectionUtils.getMatches(t.getUnits().getUnits(), givesBonusUnit));
            if (Matches.unitIsSea().test(u)) {
                final Predicate<Unit> givesBonusUnitLand = givesBonusUnit.and(Matches.unitIsLand());
                final Set<Territory> neighbors = new HashSet<>(data.getMap().getNeighbors(t, Matches.territoryIsLand()));
                for (final Territory current : neighbors) {
                    givesBonusUnits.addAll(CollectionUtils.getMatches(current.getUnits().getUnits(), givesBonusUnitLand));
                }
            } else if (Matches.unitIsLand().test(u)) {
                final Predicate<Unit> givesBonusUnitSea = givesBonusUnit.and(Matches.unitIsSea());
                final Set<Territory> neighbors = new HashSet<>(data.getMap().getNeighbors(t, Matches.territoryIsWater()));
                for (final Territory current : neighbors) {
                    givesBonusUnits.addAll(CollectionUtils.getMatches(current.getUnits().getUnits(), givesBonusUnitSea));
                }
            }
            for (final Unit bonusGiver : givesBonusUnits) {
                final int tempBonus = UnitAttachment.get(bonusGiver.getType()).getGivesMovement().getInt(u.getType());
                if (tempBonus > bonusMovement) {
                    bonusMovement = tempBonus;
                }
            }
            if (bonusMovement != Integer.MIN_VALUE && bonusMovement != 0) {
                bonusMovement = Math.max(bonusMovement, (UnitAttachment.get(u.getType()).getMovement(player) * -1));
                change.add(ChangeFactory.unitPropertyChange(u, bonusMovement, TripleAUnit.BONUS_MOVEMENT));
            }
        }
    }
    return change;
}
Also used : Territory(games.strategy.engine.data.Territory) HashSet(java.util.HashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) CompositeChange(games.strategy.engine.data.CompositeChange) TripleAUnit(games.strategy.triplea.TripleAUnit) Unit(games.strategy.engine.data.Unit) HashSet(java.util.HashSet) Predicate(java.util.function.Predicate)

Example 30 with Territory

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

the class MoveDelegate method move.

@Override
public String move(final Collection<Unit> units, final Route route, final Collection<Unit> transportsThatCanBeLoaded, final Map<Unit, Collection<Unit>> newDependents) {
    final GameData data = getData();
    // the reason we use this, is if we are in edit mode, we may have a different unit owner than the current player
    final PlayerID player = getUnitsOwner(units);
    final MoveValidationResult result = MoveValidator.validateMove(units, route, player, transportsThatCanBeLoaded, newDependents, GameStepPropertiesHelper.isNonCombatMove(data, false), movesToUndo, data);
    final StringBuilder errorMsg = new StringBuilder(100);
    final int numProblems = result.getTotalWarningCount() - (result.hasError() ? 0 : 1);
    final String numErrorsMsg = numProblems > 0 ? ("; " + numProblems + " " + MyFormatter.pluralize("error", numProblems) + " not shown") : "";
    if (result.hasError()) {
        return errorMsg.append(result.getError()).append(numErrorsMsg).toString();
    }
    if (result.hasDisallowedUnits()) {
        return errorMsg.append(result.getDisallowedUnitWarning(0)).append(numErrorsMsg).toString();
    }
    boolean isKamikaze = false;
    final boolean getKamikazeAir = Properties.getKamikazeAirplanes(data);
    Collection<Unit> kamikazeUnits = new ArrayList<>();
    // confirm kamikaze moves, and remove them from unresolved units
    if (getKamikazeAir || units.stream().anyMatch(Matches.unitIsKamikaze())) {
        kamikazeUnits = result.getUnresolvedUnits(MoveValidator.NOT_ALL_AIR_UNITS_CAN_LAND);
        if (kamikazeUnits.size() > 0 && getRemotePlayer().confirmMoveKamikaze()) {
            for (final Unit unit : kamikazeUnits) {
                if (getKamikazeAir || Matches.unitIsKamikaze().test(unit)) {
                    result.removeUnresolvedUnit(MoveValidator.NOT_ALL_AIR_UNITS_CAN_LAND, unit);
                    isKamikaze = true;
                }
            }
        }
    }
    if (result.hasUnresolvedUnits()) {
        return errorMsg.append(result.getUnresolvedUnitWarning(0)).append(numErrorsMsg).toString();
    }
    // allow user to cancel move if aa guns will fire
    final AAInMoveUtil aaInMoveUtil = new AAInMoveUtil();
    aaInMoveUtil.initialize(bridge);
    final Collection<Territory> aaFiringTerritores = aaInMoveUtil.getTerritoriesWhereAaWillFire(route, units);
    if (!aaFiringTerritores.isEmpty()) {
        if (!getRemotePlayer().confirmMoveInFaceOfAa(aaFiringTerritores)) {
            return null;
        }
    }
    // do the move
    final UndoableMove currentMove = new UndoableMove(units, route);
    final String transcriptText = MyFormatter.unitsToTextNoOwner(units) + " moved from " + route.getStart().getName() + " to " + route.getEnd().getName();
    bridge.getHistoryWriter().startEvent(transcriptText, currentMove.getDescriptionObject());
    if (isKamikaze) {
        bridge.getHistoryWriter().addChildToEvent("This was a kamikaze move, for at least some of the units", kamikazeUnits);
    }
    tempMovePerformer = new MovePerformer();
    tempMovePerformer.initialize(this);
    tempMovePerformer.moveUnits(units, route, player, transportsThatCanBeLoaded, newDependents, currentMove);
    tempMovePerformer = null;
    return null;
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) 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) MoveValidationResult(games.strategy.triplea.delegate.dataObjects.MoveValidationResult)

Aggregations

Territory (games.strategy.engine.data.Territory)420 Unit (games.strategy.engine.data.Unit)254 TripleAUnit (games.strategy.triplea.TripleAUnit)195 PlayerID (games.strategy.engine.data.PlayerID)164 ArrayList (java.util.ArrayList)160 Test (org.junit.jupiter.api.Test)140 Route (games.strategy.engine.data.Route)137 ITestDelegateBridge (games.strategy.engine.data.ITestDelegateBridge)118 GameData (games.strategy.engine.data.GameData)94 HashSet (java.util.HashSet)87 UnitType (games.strategy.engine.data.UnitType)65 HashMap (java.util.HashMap)65 ScriptedRandomSource (games.strategy.engine.random.ScriptedRandomSource)50 Collection (java.util.Collection)47 IntegerMap (games.strategy.util.IntegerMap)45 Set (java.util.Set)41 ProTerritory (games.strategy.triplea.ai.pro.data.ProTerritory)39 TerritoryAttachment (games.strategy.triplea.attachments.TerritoryAttachment)37 List (java.util.List)36 ProPurchaseTerritory (games.strategy.triplea.ai.pro.data.ProPurchaseTerritory)34