Search in sources :

Example 6 with ITripleAPlayer

use of games.strategy.triplea.player.ITripleAPlayer in project triplea by triplea-game.

the class RocketsFireHelper method fireRocket.

private static void fireRocket(final PlayerID player, final Territory attackedTerritory, final IDelegateBridge bridge, final Territory attackFrom) {
    final GameData data = bridge.getData();
    final PlayerID attacked = attackedTerritory.getOwner();
    final Resource pus = data.getResourceList().getResource(Constants.PUS);
    final boolean damageFromBombingDoneToUnits = isDamageFromBombingDoneToUnitsInsteadOfTerritories(data);
    // unit damage vs territory damage
    final Collection<Unit> enemyUnits = attackedTerritory.getUnits().getMatches(Matches.enemyUnit(player, data).and(Matches.unitIsBeingTransported().negate()));
    final Collection<Unit> enemyTargetsTotal = CollectionUtils.getMatches(enemyUnits, Matches.unitIsAtMaxDamageOrNotCanBeDamaged(attackedTerritory).negate());
    final Collection<Unit> rockets;
    // attackFrom could be null if WW2V1
    if (attackFrom == null) {
        rockets = null;
    } else {
        rockets = new ArrayList<>(CollectionUtils.getMatches(attackFrom.getUnits().getUnits(), rocketMatch(player)));
    }
    final int numberOfAttacks = (rockets == null ? 1 : Math.min(TechAbilityAttachment.getRocketNumberPerTerritory(player, data), TechAbilityAttachment.getRocketDiceNumber(rockets, data)));
    if (numberOfAttacks <= 0) {
        return;
    }
    final Collection<Unit> targets = new ArrayList<>();
    if (damageFromBombingDoneToUnits) {
        // TODO: rockets needs to be completely redone to allow for multiple rockets to fire at different targets, etc
        // etc.
        final HashSet<UnitType> legalTargetsForTheseRockets = new HashSet<>();
        if (rockets == null) {
            legalTargetsForTheseRockets.addAll(data.getUnitTypeList().getAllUnitTypes());
        } else {
            // a hack for now, we let the rockets fire at anyone who could be targetted by any rocket
            for (final Unit r : rockets) {
                legalTargetsForTheseRockets.addAll(UnitAttachment.get(r.getType()).getBombingTargets(data));
            }
        }
        final Collection<Unit> enemyTargets = CollectionUtils.getMatches(enemyTargetsTotal, Matches.unitIsOfTypes(legalTargetsForTheseRockets));
        if (enemyTargets.isEmpty()) {
            // TODO: this sucks
            return;
        }
        Unit target = null;
        if (enemyTargets.size() == 1) {
            target = enemyTargets.iterator().next();
        } else {
            while (target == null) {
                final ITripleAPlayer iplayer = (ITripleAPlayer) bridge.getRemotePlayer(player);
                target = iplayer.whatShouldBomberBomb(attackedTerritory, enemyTargets, rockets);
            }
        }
        if (target == null) {
            throw new IllegalStateException("No Targets in " + attackedTerritory.getName());
        }
        targets.add(target);
    }
    final boolean doNotUseBombingBonus = !Properties.getUseBombingMaxDiceSidesAndBonus(data) || rockets == null;
    int cost = 0;
    final String transcript;
    if (!Properties.getLowLuckDamageOnly(data)) {
        if (doNotUseBombingBonus || rockets == null) {
            // no low luck, and no bonus, so just roll based on the map's dice sides
            final int[] rolls = bridge.getRandom(data.getDiceSides(), numberOfAttacks, player, DiceType.BOMBING, "Rocket fired by " + player.getName() + " at " + attacked.getName());
            for (final int r : rolls) {
                // we are zero based
                cost += r + 1;
            }
            transcript = "Rockets " + (attackFrom == null ? "" : "in " + attackFrom.getName()) + " roll: " + MyFormatter.asDice(rolls);
        } else {
            // we must use bombing bonus
            int highestMaxDice = 0;
            int highestBonus = 0;
            final int diceSides = data.getDiceSides();
            for (final Unit u : rockets) {
                final UnitAttachment ua = UnitAttachment.get(u.getType());
                int maxDice = ua.getBombingMaxDieSides();
                final int bonus = ua.getBombingBonus();
                // map, and zero for the bonus.
                if (maxDice < 0) {
                    maxDice = diceSides;
                }
                // we only roll once for rockets, so if there are other rockets here we just roll for the best rocket
                if ((bonus + ((maxDice + 1) / 2)) > (highestBonus + ((highestMaxDice + 1) / 2))) {
                    highestMaxDice = maxDice;
                    highestBonus = bonus;
                }
            }
            // now we roll, or don't if there is nothing to roll.
            if (highestMaxDice > 0) {
                final int[] rolls = bridge.getRandom(highestMaxDice, numberOfAttacks, player, DiceType.BOMBING, "Rocket fired by " + player.getName() + " at " + attacked.getName());
                for (int i = 0; i < rolls.length; i++) {
                    final int r = Math.max(-1, rolls[i] + highestBonus);
                    rolls[i] = r;
                    // we are zero based
                    cost += r + 1;
                }
                transcript = "Rockets " + (attackFrom == null ? "" : "in " + attackFrom.getName()) + " roll: " + MyFormatter.asDice(rolls);
            } else {
                cost = highestBonus * numberOfAttacks;
                transcript = "Rockets " + (attackFrom == null ? "" : "in " + attackFrom.getName()) + " do " + highestBonus + " damage for each rocket";
            }
        }
    } else {
        if (doNotUseBombingBonus || rockets == null) {
            // no bonus, so just roll based on the map's dice sides, but modify for LL
            final int maxDice = (data.getDiceSides() + 1) / 3;
            final int bonus = (data.getDiceSides() + 1) / 3;
            final int[] rolls = bridge.getRandom(maxDice, numberOfAttacks, player, DiceType.BOMBING, "Rocket fired by " + player.getName() + " at " + attacked.getName());
            for (int i = 0; i < rolls.length; i++) {
                final int r = rolls[i] + bonus;
                rolls[i] = r;
                // we are zero based
                cost += r + 1;
            }
            transcript = "Rockets " + (attackFrom == null ? "" : "in " + attackFrom.getName()) + " roll: " + MyFormatter.asDice(rolls);
        } else {
            int highestMaxDice = 0;
            int highestBonus = 0;
            final int diceSides = data.getDiceSides();
            for (final Unit u : rockets) {
                final UnitAttachment ua = UnitAttachment.get(u.getType());
                int maxDice = ua.getBombingMaxDieSides();
                int bonus = ua.getBombingBonus();
                // map, and zero for the bonus.
                if (maxDice < 0 || doNotUseBombingBonus) {
                    maxDice = diceSides;
                }
                if (doNotUseBombingBonus) {
                    bonus = 0;
                }
                // luck by 2/3.
                if (maxDice >= 5) {
                    bonus += (maxDice + 1) / 3;
                    maxDice = (maxDice + 1) / 3;
                }
                // we only roll once for rockets, so if there are other rockets here we just roll for the best rocket
                if ((bonus + ((maxDice + 1) / 2)) > (highestBonus + ((highestMaxDice + 1) / 2))) {
                    highestMaxDice = maxDice;
                    highestBonus = bonus;
                }
            }
            // now we roll, or don't if there is nothing to roll.
            if (highestMaxDice > 0) {
                final int[] rolls = bridge.getRandom(highestMaxDice, numberOfAttacks, player, DiceType.BOMBING, "Rocket fired by " + player.getName() + " at " + attacked.getName());
                for (int i = 0; i < rolls.length; i++) {
                    final int r = Math.max(-1, rolls[i] + highestBonus);
                    rolls[i] = r;
                    // we are zero based
                    cost += r + 1;
                }
                transcript = "Rockets " + (attackFrom == null ? "" : "in " + attackFrom.getName()) + " roll: " + MyFormatter.asDice(rolls);
            } else {
                cost = highestBonus * numberOfAttacks;
                transcript = "Rockets " + (attackFrom == null ? "" : "in " + attackFrom.getName()) + " do " + highestBonus + " damage for each rocket";
            }
        }
    }
    int territoryProduction = TerritoryAttachment.getProduction(attackedTerritory);
    if (damageFromBombingDoneToUnits && !targets.isEmpty()) {
        // we are doing damage to 'target', not to the territory
        final Unit target = targets.iterator().next();
        // UnitAttachment ua = UnitAttachment.get(target.getType());
        final TripleAUnit taUnit = (TripleAUnit) target;
        final int damageLimit = taUnit.getHowMuchMoreDamageCanThisUnitTake(target, attackedTerritory);
        cost = Math.max(0, Math.min(cost, damageLimit));
        final int totalDamage = taUnit.getUnitDamage() + cost;
        // Record production lost
        // DelegateFinder.moveDelegate(data).PUsLost(attackedTerritory, cost);
        // apply the hits to the targets
        final IntegerMap<Unit> damageMap = new IntegerMap<>();
        damageMap.put(target, totalDamage);
        bridge.addChange(ChangeFactory.bombingUnitDamage(damageMap));
    // attackedTerritory.notifyChanged();
    // in WW2V2, limit rocket attack cost to production value of factory.
    } else if (isWW2V2(data) || isLimitRocketDamageToProduction(data)) {
        // If we are limiting total PUs lost then take that into account
        if (isPuCap(data) || isLimitRocketDamagePerTurn(data)) {
            final int alreadyLost = DelegateFinder.moveDelegate(data).pusAlreadyLost(attackedTerritory);
            territoryProduction -= alreadyLost;
            territoryProduction = Math.max(0, territoryProduction);
        }
        if (cost > territoryProduction) {
            cost = territoryProduction;
        }
    }
    // Record the PUs lost
    DelegateFinder.moveDelegate(data).pusLost(attackedTerritory, cost);
    if (damageFromBombingDoneToUnits && !targets.isEmpty()) {
        getRemote(bridge).reportMessage("Rocket attack in " + attackedTerritory.getName() + " does " + cost + " damage to " + targets.iterator().next(), "Rocket attack in " + attackedTerritory.getName() + " does " + cost + " damage to " + targets.iterator().next());
        bridge.getHistoryWriter().startEvent("Rocket attack in " + attackedTerritory.getName() + " does " + cost + " damage to " + targets.iterator().next());
    } else {
        cost *= Properties.getPuMultiplier(data);
        getRemote(bridge).reportMessage("Rocket attack in " + attackedTerritory.getName() + " costs:" + cost, "Rocket attack in " + attackedTerritory.getName() + " costs:" + cost);
        // Trying to remove more PUs than the victim has is A Bad Thing[tm]
        final int availForRemoval = attacked.getResources().getQuantity(pus);
        if (cost > availForRemoval) {
            cost = availForRemoval;
        }
        final String transcriptText = attacked.getName() + " lost " + cost + " PUs to rocket attack by " + player.getName();
        bridge.getHistoryWriter().startEvent(transcriptText);
        final Change rocketCharge = ChangeFactory.changeResourcesChange(attacked, pus, -cost);
        bridge.addChange(rocketCharge);
    }
    bridge.getHistoryWriter().addChildToEvent(transcript, rockets == null ? null : new ArrayList<>(rockets));
    // this is null in WW2V1
    if (attackFrom != null) {
        if (rockets != null && !rockets.isEmpty()) {
            // TODO: only a certain number fired...
            final Change change = ChangeFactory.markNoMovementChange(Collections.singleton(rockets.iterator().next()));
            bridge.addChange(change);
        } else {
            throw new IllegalStateException("No rockets?" + attackFrom.getUnits().getUnits());
        }
    }
    // kill any units that can die if they have reached max damage (veqryn)
    if (targets.stream().anyMatch(Matches.unitCanDieFromReachingMaxDamage())) {
        final List<Unit> unitsCanDie = CollectionUtils.getMatches(targets, Matches.unitCanDieFromReachingMaxDamage());
        unitsCanDie.retainAll(CollectionUtils.getMatches(unitsCanDie, Matches.unitIsAtMaxDamageOrNotCanBeDamaged(attackedTerritory)));
        if (!unitsCanDie.isEmpty()) {
            final Change removeDead = ChangeFactory.removeUnits(attackedTerritory, unitsCanDie);
            final String transcriptText = MyFormatter.unitsToText(unitsCanDie) + " lost in " + attackedTerritory.getName();
            bridge.getHistoryWriter().addChildToEvent(transcriptText, unitsCanDie);
            bridge.addChange(removeDead);
        }
    }
    // play a sound
    if (cost > 0) {
        bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_BOMBING_ROCKET, player);
    }
}
Also used : IntegerMap(games.strategy.util.IntegerMap) PlayerID(games.strategy.engine.data.PlayerID) GameData(games.strategy.engine.data.GameData) Resource(games.strategy.engine.data.Resource) ArrayList(java.util.ArrayList) Change(games.strategy.engine.data.Change) TripleAUnit(games.strategy.triplea.TripleAUnit) Unit(games.strategy.engine.data.Unit) TripleAUnit(games.strategy.triplea.TripleAUnit) ITripleAPlayer(games.strategy.triplea.player.ITripleAPlayer) UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) UnitType(games.strategy.engine.data.UnitType) HashSet(java.util.HashSet)

Example 7 with ITripleAPlayer

use of games.strategy.triplea.player.ITripleAPlayer in project triplea by triplea-game.

the class StrategicBombingRaidBattle method notifyAaHits.

private void notifyAaHits(final IDelegateBridge bridge, final DiceRoll dice, final CasualtyDetails casualties, final String currentTypeAa) {
    getDisplay(bridge).casualtyNotification(m_battleID, REMOVE_PREFIX + currentTypeAa + CASUALTIES_SUFFIX, dice, m_attacker, new ArrayList<>(casualties.getKilled()), new ArrayList<>(casualties.getDamaged()), Collections.emptyMap());
    final Thread t = new Thread(() -> {
        try {
            final ITripleAPlayer defender = (ITripleAPlayer) bridge.getRemotePlayer(m_defender);
            defender.confirmEnemyCasualties(m_battleID, "Press space to continue", m_attacker);
        } catch (final Exception e) {
        // ignore
        }
    }, "click to continue waiter");
    t.start();
    final ITripleAPlayer attacker = (ITripleAPlayer) bridge.getRemotePlayer(m_attacker);
    attacker.confirmOwnCasualties(m_battleID, "Press space to continue");
    bridge.leaveDelegateExecution();
    Interruptibles.join(t);
    bridge.enterDelegateExecution();
}
Also used : ITripleAPlayer(games.strategy.triplea.player.ITripleAPlayer)

Example 8 with ITripleAPlayer

use of games.strategy.triplea.player.ITripleAPlayer in project triplea by triplea-game.

the class TechnologyDelegate method rollTech.

@Override
public TechResults rollTech(final int techRolls, final TechnologyFrontier techToRollFor, final int newTokens, final IntegerMap<PlayerID> whoPaysHowMuch) {
    int rollCount = techRolls;
    if (isWW2V3TechModel()) {
        rollCount = newTokens;
    }
    final boolean canPay = checkEnoughMoney(rollCount, whoPaysHowMuch);
    if (!canPay) {
        return new TechResults("Not enough money to pay for that many tech rolls.");
    }
    chargeForTechRolls(rollCount, whoPaysHowMuch);
    int currTokens = 0;
    if (isWW2V3TechModel()) {
        currTokens = player.getResources().getQuantity(Constants.TECH_TOKENS);
    }
    final GameData data = getData();
    if (getAvailableTechs(player, data).isEmpty()) {
        if (isWW2V3TechModel()) {
            final Resource techTokens = data.getResourceList().getResource(Constants.TECH_TOKENS);
            final String transcriptText = player.getName() + " No more available tech advances.";
            bridge.getHistoryWriter().startEvent(transcriptText);
            final Change removeTokens = ChangeFactory.changeResourcesChange(bridge.getPlayerId(), techTokens, -currTokens);
            bridge.addChange(removeTokens);
        }
        return new TechResults("No more available tech advances.");
    }
    final String annotation = player.getName() + " rolling for tech.";
    final int[] random;
    int techHits;
    int remainder = 0;
    final int diceSides = data.getDiceSides();
    if (BaseEditDelegate.getEditMode(data)) {
        final ITripleAPlayer tripleaPlayer = getRemotePlayer();
        random = tripleaPlayer.selectFixedDice(techRolls, diceSides, true, annotation, diceSides);
        techHits = getTechHits(random);
    } else if (isLowLuckTechOnly()) {
        techHits = techRolls / diceSides;
        remainder = techRolls % diceSides;
        if (remainder > 0) {
            random = bridge.getRandom(diceSides, 1, player, DiceType.TECH, annotation);
            if (random[0] + 1 <= remainder) {
                techHits++;
            }
        } else {
            random = bridge.getRandom(diceSides, 1, player, DiceType.TECH, annotation);
            remainder = diceSides;
        }
    } else {
        random = bridge.getRandom(diceSides, techRolls, player, DiceType.TECH, annotation);
        techHits = getTechHits(random);
    }
    final boolean isRevisedModel = isWW2V2() || (isSelectableTechRoll() && !isWW2V3TechModel());
    final String directedTechInfo = isRevisedModel ? " for " + techToRollFor.getTechs().get(0) : "";
    final DiceRoll renderDice = (isLowLuckTechOnly() ? new DiceRoll(random, techHits, remainder, false) : new DiceRoll(random, techHits, diceSides - 1, true));
    bridge.getHistoryWriter().startEvent(player.getName() + (random.length > 1 ? " roll " : " rolls : ") + MyFormatter.asDice(random) + directedTechInfo + " and gets " + techHits + " " + MyFormatter.pluralize("hit", techHits), renderDice);
    if (isWW2V3TechModel() && (techHits > 0 || Properties.getRemoveAllTechTokensAtEndOfTurn(data))) {
        techCategory = techToRollFor;
        // remove all the tokens
        final Resource techTokens = data.getResourceList().getResource(Constants.TECH_TOKENS);
        final String transcriptText = player.getName() + " removing all Technology Tokens after " + (techHits > 0 ? "successful" : "unsuccessful") + " research.";
        bridge.getHistoryWriter().startEvent(transcriptText);
        final Change removeTokens = ChangeFactory.changeResourcesChange(bridge.getPlayerId(), techTokens, -currTokens);
        bridge.addChange(removeTokens);
    }
    final Collection<TechAdvance> advances;
    if (isRevisedModel) {
        if (techHits > 0) {
            advances = Collections.singletonList(techToRollFor.getTechs().get(0));
        } else {
            advances = Collections.emptyList();
        }
    } else {
        advances = getTechAdvances(techHits);
    }
    // Put in techs so they can be activated later.
    techs.put(player, advances);
    final List<String> advancesAsString = new ArrayList<>();
    int count = advances.size();
    final StringBuilder text = new StringBuilder();
    for (final TechAdvance advance : advances) {
        text.append(advance.getName());
        count--;
        advancesAsString.add(advance.getName());
        if (count > 1) {
            text.append(", ");
        }
        if (count == 1) {
            text.append(" and ");
        }
    }
    final String transcriptText = player.getName() + " discover " + text;
    if (advances.size() > 0) {
        bridge.getHistoryWriter().startEvent(transcriptText);
        // play a sound
        getSoundChannel().playSoundForAll(SoundPath.CLIP_TECHNOLOGY_SUCCESSFUL, player);
    } else {
        getSoundChannel().playSoundForAll(SoundPath.CLIP_TECHNOLOGY_FAILURE, player);
    }
    return new TechResults(random, remainder, techHits, advancesAsString, player);
}
Also used : GameData(games.strategy.engine.data.GameData) Resource(games.strategy.engine.data.Resource) ArrayList(java.util.ArrayList) Change(games.strategy.engine.data.Change) ITripleAPlayer(games.strategy.triplea.player.ITripleAPlayer) TechResults(games.strategy.triplea.delegate.dataObjects.TechResults)

Example 9 with ITripleAPlayer

use of games.strategy.triplea.player.ITripleAPlayer in project triplea by triplea-game.

the class TechnologyDelegate method getTechAdvances.

private Collection<TechAdvance> getTechAdvances(int hits) {
    final List<TechAdvance> available;
    if (hits > 0 && isWW2V3TechModel()) {
        available = getAvailableAdvancesForCategory(techCategory);
        hits = 1;
    } else {
        available = getAvailableAdvances();
    }
    if (available.isEmpty()) {
        return Collections.emptyList();
    }
    if (hits >= available.size()) {
        return available;
    }
    if (hits == 0) {
        return Collections.emptyList();
    }
    final Collection<TechAdvance> newAdvances = new ArrayList<>(hits);
    final String annotation = player.getName() + " rolling to see what tech advances are aquired";
    final int[] random;
    if (isSelectableTechRoll() || BaseEditDelegate.getEditMode(getData())) {
        final ITripleAPlayer tripleaPlayer = getRemotePlayer();
        random = tripleaPlayer.selectFixedDice(hits, 0, true, annotation, available.size());
    } else {
        random = new int[hits];
        final List<Integer> rolled = new ArrayList<>();
        // hits guaranteed to be less than available at this point.
        for (int i = 0; i < hits; i++) {
            int roll = bridge.getRandom(available.size() - i, null, DiceType.ENGINE, annotation);
            for (final int r : rolled) {
                if (roll >= r) {
                    roll++;
                }
            }
            random[i] = roll;
            rolled.add(roll);
        }
    }
    final List<Integer> rolled = new ArrayList<>();
    for (final int element : random) {
        // check in case of dice chooser.
        if (!rolled.contains(element) && element < available.size()) {
            newAdvances.add(available.get(element));
            rolled.add(element);
        }
    }
    bridge.getHistoryWriter().startEvent("Rolls to resolve tech hits:" + MyFormatter.asDice(random));
    return newAdvances;
}
Also used : ArrayList(java.util.ArrayList) ITripleAPlayer(games.strategy.triplea.player.ITripleAPlayer)

Example 10 with ITripleAPlayer

use of games.strategy.triplea.player.ITripleAPlayer in project triplea by triplea-game.

the class AbstractEndTurnDelegate method showEndTurnReport.

protected void showEndTurnReport(final String endTurnReport) {
    if (endTurnReport != null && endTurnReport.trim().length() > 6 && !player.isAi()) {
        final ITripleAPlayer currentPlayer = getRemotePlayer(player);
        final String playerName = player.getName();
        currentPlayer.reportMessage("<html><b style=\"font-size:120%\" >" + END_TURN_REPORT_STRING + playerName + "</b><br /><br />" + endTurnReport + "</html>", END_TURN_REPORT_STRING + playerName);
    }
}
Also used : ITripleAPlayer(games.strategy.triplea.player.ITripleAPlayer)

Aggregations

ITripleAPlayer (games.strategy.triplea.player.ITripleAPlayer)14 GameData (games.strategy.engine.data.GameData)8 PlayerID (games.strategy.engine.data.PlayerID)8 Territory (games.strategy.engine.data.Territory)8 Unit (games.strategy.engine.data.Unit)8 ArrayList (java.util.ArrayList)8 TripleAUnit (games.strategy.triplea.TripleAUnit)7 Change (games.strategy.engine.data.Change)6 UnitType (games.strategy.engine.data.UnitType)6 UnitAttachment (games.strategy.triplea.attachments.UnitAttachment)6 ITestDelegateBridge (games.strategy.engine.data.ITestDelegateBridge)5 Route (games.strategy.engine.data.Route)5 List (java.util.List)5 Test (org.junit.jupiter.api.Test)5 ChangeFactory (games.strategy.engine.data.changefactory.ChangeFactory)4 ScriptedRandomSource (games.strategy.engine.random.ScriptedRandomSource)4 Constants (games.strategy.triplea.Constants)4 GameDataTestUtil.addTo (games.strategy.triplea.delegate.GameDataTestUtil.addTo)4 TestMapGameData (games.strategy.triplea.xml.TestMapGameData)4 Proxy (java.lang.reflect.Proxy)4