use of games.strategy.engine.data.GameData in project triplea by triplea-game.
the class ProPurchaseUtils method findBidTerritories.
/**
* Find all territories that bid units can be placed in and initialize data holders for them.
*
* @param player - current AI player
* @return - map of all available purchase and place territories
*/
public static Map<Territory, ProPurchaseTerritory> findBidTerritories(final PlayerID player) {
ProLogger.info("Find all bid territories");
final GameData data = ProData.getData();
// Find all territories that I can place units on
final Set<Territory> ownedOrHasUnitTerritories = new HashSet<>(data.getMap().getTerritoriesOwnedBy(player));
ownedOrHasUnitTerritories.addAll(ProData.myUnitTerritories);
final List<Territory> potentialTerritories = CollectionUtils.getMatches(ownedOrHasUnitTerritories, Matches.territoryIsPassableAndNotRestrictedAndOkByRelationships(player, data, false, false, false, false, false));
// Create purchase territory holder for each factory territory
final Map<Territory, ProPurchaseTerritory> purchaseTerritories = new HashMap<>();
for (final Territory t : potentialTerritories) {
final ProPurchaseTerritory ppt = new ProPurchaseTerritory(t, data, player, 1, true);
purchaseTerritories.put(t, ppt);
ProLogger.debug(ppt.toString());
}
return purchaseTerritories;
}
use of games.strategy.engine.data.GameData in project triplea by triplea-game.
the class ProSortMoveOptionsUtils method sortUnitNeededOptions.
public static Map<Unit, Set<Territory>> sortUnitNeededOptions(final PlayerID player, final Map<Unit, Set<Territory>> unitAttackOptions, final Map<Territory, ProTerritory> attackMap, final ProOddsCalculator calc) {
final GameData data = ProData.getData();
final List<Map.Entry<Unit, Set<Territory>>> list = new ArrayList<>(unitAttackOptions.entrySet());
list.sort((o1, o2) -> {
// Find number of territories that still need units
int numOptions1 = 0;
for (final Territory t : o1.getValue()) {
final ProTerritory patd = attackMap.get(t);
if (patd.getBattleResult() == null) {
patd.setBattleResult(calc.estimateAttackBattleResults(t, patd.getUnits(), patd.getMaxEnemyDefenders(player, data), patd.getBombardTerritoryMap().keySet()));
}
if (!patd.isCurrentlyWins()) {
numOptions1++;
}
}
int numOptions2 = 0;
for (final Territory t : o2.getValue()) {
final ProTerritory patd = attackMap.get(t);
if (patd.getBattleResult() == null) {
patd.setBattleResult(calc.estimateAttackBattleResults(t, patd.getUnits(), patd.getMaxEnemyDefenders(player, data), patd.getBombardTerritoryMap().keySet()));
}
if (!patd.isCurrentlyWins()) {
numOptions2++;
}
}
// Sort by number of move options then cost of unit then unit type
if (numOptions1 != numOptions2) {
return (numOptions1 - numOptions2);
}
if (ProData.unitValueMap.getInt(o1.getKey().getType()) != ProData.unitValueMap.getInt(o2.getKey().getType())) {
return (ProData.unitValueMap.getInt(o1.getKey().getType()) - ProData.unitValueMap.getInt(o2.getKey().getType()));
}
return o1.getKey().getType().getName().compareTo(o2.getKey().getType().getName());
});
final Map<Unit, Set<Territory>> sortedUnitAttackOptions = new LinkedHashMap<>();
for (final Map.Entry<Unit, Set<Territory>> entry : list) {
sortedUnitAttackOptions.put(entry.getKey(), entry.getValue());
}
return sortedUnitAttackOptions;
}
use of games.strategy.engine.data.GameData in project triplea by triplea-game.
the class ProSortMoveOptionsUtils method sortUnitNeededOptionsThenAttack.
public static Map<Unit, Set<Territory>> sortUnitNeededOptionsThenAttack(final PlayerID player, final Map<Unit, Set<Territory>> unitAttackOptions, final Map<Territory, ProTerritory> attackMap, final Map<Unit, Territory> unitTerritoryMap, final ProOddsCalculator calc) {
final GameData data = ProData.getData();
final List<Map.Entry<Unit, Set<Territory>>> list = new ArrayList<>(unitAttackOptions.entrySet());
list.sort((o1, o2) -> {
// Sort by number of territories that still need units
int numOptions1 = 0;
for (final Territory t : o1.getValue()) {
final ProTerritory patd = attackMap.get(t);
if (patd.getBattleResult() == null) {
patd.setBattleResult(calc.estimateAttackBattleResults(t, patd.getUnits(), patd.getMaxEnemyDefenders(player, data), patd.getBombardTerritoryMap().keySet()));
}
if (!patd.isCurrentlyWins()) {
numOptions1++;
}
}
int numOptions2 = 0;
for (final Territory t : o2.getValue()) {
final ProTerritory patd = attackMap.get(t);
if (patd.getBattleResult() == null) {
patd.setBattleResult(calc.estimateAttackBattleResults(t, patd.getUnits(), patd.getMaxEnemyDefenders(player, data), patd.getBombardTerritoryMap().keySet()));
}
if (!patd.isCurrentlyWins()) {
numOptions2++;
}
}
if (numOptions1 != numOptions2) {
return (numOptions1 - numOptions2);
}
if (numOptions1 == 0) {
return 0;
}
// Sort by attack efficiency
int minPower1 = Integer.MAX_VALUE;
for (final Territory t : o1.getValue()) {
if (!attackMap.get(t).isCurrentlyWins()) {
final List<Unit> defendingUnits = t.getUnits().getMatches(Matches.enemyUnit(player, data));
final List<Unit> sortedUnitsList = new ArrayList<>(attackMap.get(t).getUnits());
sortedUnitsList.sort(new UnitBattleComparator(false, ProData.unitValueMap, TerritoryEffectHelper.getEffects(t), data, false, false));
Collections.reverse(sortedUnitsList);
final int powerWithout = DiceRoll.getTotalPower(DiceRoll.getUnitPowerAndRollsForNormalBattles(sortedUnitsList, defendingUnits, false, false, data, t, TerritoryEffectHelper.getEffects(t), false, null), data);
sortedUnitsList.add(o1.getKey());
sortedUnitsList.sort(new UnitBattleComparator(false, ProData.unitValueMap, TerritoryEffectHelper.getEffects(t), data, false, false));
Collections.reverse(sortedUnitsList);
final int powerWith = DiceRoll.getTotalPower(DiceRoll.getUnitPowerAndRollsForNormalBattles(sortedUnitsList, defendingUnits, false, false, data, t, TerritoryEffectHelper.getEffects(t), false, null), data);
final int power = powerWith - powerWithout;
if (power < minPower1) {
minPower1 = power;
}
}
}
final UnitAttachment ua1 = UnitAttachment.get(o1.getKey().getType());
if (ua1.getIsAir()) {
minPower1 *= 10;
}
final double attackEfficiency1 = (double) minPower1 / ProData.unitValueMap.getInt(o1.getKey().getType());
int minPower2 = Integer.MAX_VALUE;
for (final Territory t : o2.getValue()) {
if (!attackMap.get(t).isCurrentlyWins()) {
final List<Unit> defendingUnits = t.getUnits().getMatches(Matches.enemyUnit(player, data));
final List<Unit> sortedUnitsList = new ArrayList<>(attackMap.get(t).getUnits());
sortedUnitsList.sort(new UnitBattleComparator(false, ProData.unitValueMap, TerritoryEffectHelper.getEffects(t), data, false, false));
Collections.reverse(sortedUnitsList);
final int powerWithout = DiceRoll.getTotalPower(DiceRoll.getUnitPowerAndRollsForNormalBattles(sortedUnitsList, defendingUnits, false, false, data, t, TerritoryEffectHelper.getEffects(t), false, null), data);
sortedUnitsList.add(o2.getKey());
sortedUnitsList.sort(new UnitBattleComparator(false, ProData.unitValueMap, TerritoryEffectHelper.getEffects(t), data, false, false));
Collections.reverse(sortedUnitsList);
final int powerWith = DiceRoll.getTotalPower(DiceRoll.getUnitPowerAndRollsForNormalBattles(sortedUnitsList, defendingUnits, false, false, data, t, TerritoryEffectHelper.getEffects(t), false, null), data);
final int power = powerWith - powerWithout;
if (power < minPower2) {
minPower2 = power;
}
}
}
final UnitAttachment ua2 = UnitAttachment.get(o2.getKey().getType());
if (ua2.getIsAir()) {
minPower2 *= 10;
}
final double attackEfficiency2 = (double) minPower2 / ProData.unitValueMap.getInt(o2.getKey().getType());
if (attackEfficiency1 != attackEfficiency2) {
return (attackEfficiency1 < attackEfficiency2) ? 1 : -1;
}
// Check if unit types are equal and is air then sort by average distance
if (o1.getKey().getType().equals(o2.getKey().getType())) {
final boolean isAirUnit = UnitAttachment.get(o1.getKey().getType()).getIsAir();
if (isAirUnit) {
int distance1 = 0;
for (final Territory t : o1.getValue()) {
if (!attackMap.get(t).isCurrentlyWins()) {
distance1 += data.getMap().getDistance_IgnoreEndForCondition(unitTerritoryMap.get(o1.getKey()), t, ProMatches.territoryCanMoveAirUnitsAndNoAa(player, data, true));
}
}
int distance2 = 0;
for (final Territory t : o2.getValue()) {
if (!attackMap.get(t).isCurrentlyWins()) {
distance2 += data.getMap().getDistance_IgnoreEndForCondition(unitTerritoryMap.get(o2.getKey()), t, ProMatches.territoryCanMoveAirUnitsAndNoAa(player, data, true));
}
}
if (distance1 != distance2) {
return distance1 - distance2;
}
}
}
return o1.getKey().getType().getName().compareTo(o2.getKey().getType().getName());
});
final Map<Unit, Set<Territory>> sortedUnitAttackOptions = new LinkedHashMap<>();
for (final Map.Entry<Unit, Set<Territory>> entry : list) {
sortedUnitAttackOptions.put(entry.getKey(), entry.getValue());
}
return sortedUnitAttackOptions;
}
use of games.strategy.engine.data.GameData in project triplea by triplea-game.
the class TripleAPlayer method purchase.
private void purchase(final boolean bid) {
if (getPlayerBridge().isGameOver()) {
return;
}
final PlayerID id = getPlayerId();
// play a sound for this phase
if (!bid && !soundPlayedAlreadyPurchase) {
ClipPlayer.play(SoundPath.CLIP_PHASE_PURCHASE, id);
soundPlayedAlreadyPurchase = true;
}
// Check if any factories need to be repaired
if (id.getRepairFrontier() != null && id.getRepairFrontier().getRules() != null && !id.getRepairFrontier().getRules().isEmpty()) {
final GameData data = getGameData();
if (isDamageFromBombingDoneToUnitsInsteadOfTerritories(data)) {
final Predicate<Unit> myDamaged = Matches.unitIsOwnedBy(id).and(Matches.unitHasTakenSomeBombingUnitDamage());
final Collection<Unit> damagedUnits = new ArrayList<>();
for (final Territory t : data.getMap().getTerritories()) {
damagedUnits.addAll(CollectionUtils.getMatches(t.getUnits().getUnits(), myDamaged));
}
if (damagedUnits.size() > 0) {
final HashMap<Unit, IntegerMap<RepairRule>> repair = ui.getRepair(id, bid, GameStepPropertiesHelper.getRepairPlayers(data, id));
if (repair != null) {
final IPurchaseDelegate purchaseDel;
try {
purchaseDel = (IPurchaseDelegate) getPlayerBridge().getRemoteDelegate();
} catch (final ClassCastException e) {
final String errorContext = "PlayerBridge step name: " + getPlayerBridge().getStepName() + ", Remote class name: " + getPlayerBridge().getRemoteDelegate().getClass();
// for some reason the client is not seeing or getting these errors, so print to err too
System.err.println(errorContext);
ClientLogger.logQuietly(errorContext, e);
throw new IllegalStateException(errorContext, e);
}
final String error = purchaseDel.purchaseRepair(repair);
if (error != null) {
ui.notifyError(error);
// dont give up, keep going
purchase(bid);
}
}
}
}
}
final IntegerMap<ProductionRule> prod = ui.getProduction(id, bid);
if (prod == null) {
return;
}
final IPurchaseDelegate purchaseDel;
try {
purchaseDel = (IPurchaseDelegate) getPlayerBridge().getRemoteDelegate();
} catch (final ClassCastException e) {
final String errorContext = "PlayerBridge step name: " + getPlayerBridge().getStepName() + ", Remote class name: " + getPlayerBridge().getRemoteDelegate().getClass();
// for some reason the client is not seeing or getting these errors, so print to err too
System.err.println(errorContext);
ClientLogger.logQuietly(errorContext, e);
throw new IllegalStateException(errorContext, e);
}
final String purchaseError = purchaseDel.purchase(prod);
if (purchaseError != null) {
ui.notifyError(purchaseError);
// dont give up, keep going
purchase(bid);
}
}
use of games.strategy.engine.data.GameData in project triplea by triplea-game.
the class AbstractAi method politicalActions.
protected void politicalActions() {
final IPoliticsDelegate remotePoliticsDelegate = (IPoliticsDelegate) getPlayerBridge().getRemoteDelegate();
final GameData data = getGameData();
final PlayerID id = getPlayerId();
final float numPlayers = data.getPlayerList().getPlayers().size();
final PoliticsDelegate politicsDelegate = DelegateFinder.politicsDelegate(data);
// We want to test the conditions each time to make sure they are still valid
if (Math.random() < .5) {
final List<PoliticalActionAttachment> actionChoicesTowardsWar = AiPoliticalUtils.getPoliticalActionsTowardsWar(id, politicsDelegate.getTestedConditions(), data);
if (actionChoicesTowardsWar != null && !actionChoicesTowardsWar.isEmpty()) {
Collections.shuffle(actionChoicesTowardsWar);
int i = 0;
// should we use bridge's random source here?
final double random = Math.random();
int maxWarActionsPerTurn = (random < .5 ? 0 : (random < .9 ? 1 : (random < .99 ? 2 : (int) numPlayers / 2)));
if ((maxWarActionsPerTurn > 0) && (CollectionUtils.countMatches(data.getRelationshipTracker().getRelationships(id), Matches.relationshipIsAtWar())) / numPlayers < 0.4) {
if (Math.random() < .9) {
maxWarActionsPerTurn = 0;
} else {
maxWarActionsPerTurn = 1;
}
}
final Iterator<PoliticalActionAttachment> actionWarIter = actionChoicesTowardsWar.iterator();
while (actionWarIter.hasNext() && maxWarActionsPerTurn > 0) {
final PoliticalActionAttachment action = actionWarIter.next();
if (!Matches.abstractUserActionAttachmentCanBeAttempted(politicsDelegate.getTestedConditions()).test(action)) {
continue;
}
i++;
if (i > maxWarActionsPerTurn) {
break;
}
remotePoliticsDelegate.attemptAction(action);
}
}
} else {
final List<PoliticalActionAttachment> actionChoicesOther = AiPoliticalUtils.getPoliticalActionsOther(id, politicsDelegate.getTestedConditions(), data);
if (actionChoicesOther != null && !actionChoicesOther.isEmpty()) {
Collections.shuffle(actionChoicesOther);
int i = 0;
// should we use bridge's random source here?
final double random = Math.random();
final int maxOtherActionsPerTurn = (random < .3 ? 0 : (random < .6 ? 1 : (random < .9 ? 2 : (random < .99 ? 3 : (int) numPlayers))));
final Iterator<PoliticalActionAttachment> actionOtherIter = actionChoicesOther.iterator();
while (actionOtherIter.hasNext() && maxOtherActionsPerTurn > 0) {
final PoliticalActionAttachment action = actionOtherIter.next();
if (!Matches.abstractUserActionAttachmentCanBeAttempted(politicsDelegate.getTestedConditions()).test(action)) {
continue;
}
if (action.getCostPu() > 0 && action.getCostPu() > id.getResources().getQuantity(Constants.PUS)) {
continue;
}
i++;
if (i > maxOtherActionsPerTurn) {
break;
}
remotePoliticsDelegate.attemptAction(action);
}
}
}
}
Aggregations