use of games.strategy.triplea.attachments.PlayerAttachment in project triplea by triplea-game.
the class TechActivationDelegate method shareTechnology.
private void shareTechnology() {
final PlayerAttachment pa = PlayerAttachment.get(player);
if (pa == null) {
return;
}
final Collection<PlayerID> shareWith = pa.getShareTechnology();
if (shareWith == null || shareWith.isEmpty()) {
return;
}
final GameData data = getData();
final Collection<TechAdvance> currentAdvances = TechTracker.getCurrentTechAdvances(player, data);
for (final PlayerID p : shareWith) {
final Collection<TechAdvance> availableTechs = TechnologyDelegate.getAvailableTechs(p, data);
final Collection<TechAdvance> toGive = CollectionUtils.intersection(currentAdvances, availableTechs);
if (!toGive.isEmpty()) {
// Start event
bridge.getHistoryWriter().startEvent(player.getName() + " giving technology to " + p.getName() + ": " + advancesAsString(toGive));
for (final TechAdvance advance : toGive) {
TechTracker.addAdvance(p, bridge, advance);
}
}
}
}
use of games.strategy.triplea.attachments.PlayerAttachment in project triplea by triplea-game.
the class TechnologyDelegate method delegateCurrentlyRequiresUserInput.
@Override
public boolean delegateCurrentlyRequiresUserInput() {
if (!Properties.getTechDevelopment(getData())) {
return false;
}
if (!TerritoryAttachment.doWeHaveEnoughCapitalsToProduce(player, getData())) {
return false;
}
if (Properties.getWW2V3TechModel(getData())) {
final Resource techtokens = getData().getResourceList().getResource(Constants.TECH_TOKENS);
if (techtokens != null) {
final int techTokens = player.getResources().getQuantity(techtokens);
if (techTokens > 0) {
return true;
}
}
}
final int techCost = TechTracker.getTechCost(player);
int money = player.getResources().getQuantity(Constants.PUS);
if (money < techCost) {
final PlayerAttachment pa = PlayerAttachment.get(player);
if (pa == null) {
return false;
}
final Collection<PlayerID> helpPay = pa.getHelpPayTechCost();
if (helpPay == null || helpPay.isEmpty()) {
return false;
}
for (final PlayerID p : helpPay) {
money += p.getResources().getQuantity(Constants.PUS);
}
return money >= techCost;
}
return true;
}
use of games.strategy.triplea.attachments.PlayerAttachment in project triplea by triplea-game.
the class BattleTracker method takeOver.
public void takeOver(final Territory territory, final PlayerID id, final IDelegateBridge bridge, final UndoableMove changeTracker, final Collection<Unit> arrivingUnits) {
// This could be NULL if unowned water
final TerritoryAttachment ta = TerritoryAttachment.get(territory);
if (ta == null) {
// TODO: allow capture/destroy of infrastructure on unowned water
return;
}
final GameData data = bridge.getData();
final Collection<Unit> arrivedUnits = (arrivingUnits == null ? null : new ArrayList<>(arrivingUnits));
final RelationshipTracker relationshipTracker = data.getRelationshipTracker();
final boolean isTerritoryOwnerAnEnemy = relationshipTracker.canTakeOverOwnedTerritory(id, territory.getOwner());
// check to make sure attackers have more than just transports. If they don't, exit here.
if (territory.isWater() && arrivedUnits != null) {
// Total Attacking Sea units = all units - land units - air units - submerged subs
// Also subtract transports & subs (if they can't control sea zones)
int totalMatches = arrivedUnits.size() - CollectionUtils.countMatches(arrivedUnits, Matches.unitIsLand()) - CollectionUtils.countMatches(arrivedUnits, Matches.unitIsAir()) - CollectionUtils.countMatches(arrivedUnits, Matches.unitIsSubmerged());
// If transports are restricted from controlling sea zones, subtract them
final Predicate<Unit> transportsCanNotControl = Matches.unitIsTransportAndNotDestroyer().and(Matches.unitIsTransportButNotCombatTransport());
if (!Properties.getTransportControlSeaZone(data)) {
totalMatches -= CollectionUtils.countMatches(arrivedUnits, transportsCanNotControl);
}
// If subs are restricted from controlling sea zones, subtract them
if (Properties.getSubControlSeaZoneRestricted(data)) {
totalMatches -= CollectionUtils.countMatches(arrivedUnits, Matches.unitIsSub());
}
if (totalMatches == 0) {
return;
}
}
// If it was a Convoy Route- check ownership of the associated neighboring territory and set message
if (ta.getConvoyRoute()) {
// we could be part of a convoy route for another territory
final Collection<Territory> attachedConvoyTo = TerritoryAttachment.getWhatTerritoriesThisIsUsedInConvoysFor(territory, data);
for (final Territory convoy : attachedConvoyTo) {
final TerritoryAttachment cta = TerritoryAttachment.get(convoy);
if (!cta.getConvoyRoute()) {
continue;
}
final PlayerID convoyOwner = convoy.getOwner();
if (relationshipTracker.isAllied(id, convoyOwner)) {
if (CollectionUtils.getMatches(cta.getConvoyAttached(), Matches.isTerritoryAllied(convoyOwner, data)).size() <= 0) {
bridge.getHistoryWriter().addChildToEvent(convoyOwner.getName() + " gains " + cta.getProduction() + " production in " + convoy.getName() + " for the liberation the convoy route in " + territory.getName());
}
} else if (relationshipTracker.isAtWar(id, convoyOwner)) {
if (CollectionUtils.getMatches(cta.getConvoyAttached(), Matches.isTerritoryAllied(convoyOwner, data)).size() == 1) {
bridge.getHistoryWriter().addChildToEvent(convoyOwner.getName() + " loses " + cta.getProduction() + " production in " + convoy.getName() + " due to the capture of the convoy route in " + territory.getName());
}
}
}
}
// if neutral, we may charge money to enter
if (territory.getOwner().isNull() && !territory.isWater() && Properties.getNeutralCharge(data) >= 0) {
final Resource pus = data.getResourceList().getResource(Constants.PUS);
final int puChargeIdeal = -Properties.getNeutralCharge(data);
final int puChargeReal = Math.min(0, Math.max(puChargeIdeal, -id.getResources().getQuantity(pus)));
final Change neutralFee = ChangeFactory.changeResourcesChange(id, pus, puChargeReal);
bridge.addChange(neutralFee);
if (changeTracker != null) {
changeTracker.addChange(neutralFee);
}
if (puChargeIdeal == puChargeReal) {
bridge.getHistoryWriter().addChildToEvent(id.getName() + " loses " + -puChargeReal + " " + MyFormatter.pluralize("PU", -puChargeReal) + " for violating " + territory.getName() + "s neutrality.");
} else {
System.out.println("Player, " + id.getName() + " attacks a Neutral territory, and should have had to pay " + puChargeIdeal + ", but did not have enough PUs to pay! This is a bug.");
bridge.getHistoryWriter().addChildToEvent(id.getName() + " loses " + -puChargeReal + " " + MyFormatter.pluralize("PU", -puChargeReal) + " for violating " + territory.getName() + "s neutrality. Correct amount to charge is: " + puChargeIdeal + ". Player should not have been able to make this attack!");
}
}
// instead it is relying on the fact that the capital should be owned by the person it is attached to
if (isTerritoryOwnerAnEnemy && ta.getCapital() != null) {
// if the capital is owned by the capitols player take the money
final PlayerID whoseCapital = data.getPlayerList().getPlayerId(ta.getCapital());
final PlayerAttachment pa = PlayerAttachment.get(id);
final PlayerAttachment paWhoseCapital = PlayerAttachment.get(whoseCapital);
final List<Territory> capitalsList = new ArrayList<>(TerritoryAttachment.getAllCurrentlyOwnedCapitals(whoseCapital, data));
// we are losing one right now, so it is < not <=
if (paWhoseCapital != null && paWhoseCapital.getRetainCapitalNumber() < capitalsList.size()) {
// do nothing, we keep our money since we still control enough capitals
bridge.getHistoryWriter().addChildToEvent(id.getName() + " captures one of " + whoseCapital.getName() + " capitals");
} else if (whoseCapital.equals(territory.getOwner())) {
final Resource pus = data.getResourceList().getResource(Constants.PUS);
final int capturedPuCount = whoseCapital.getResources().getQuantity(pus);
if (pa != null) {
if (isPacificTheater(data)) {
final Change changeVp = ChangeFactory.attachmentPropertyChange(pa, (capturedPuCount + pa.getCaptureVps()), "captureVps");
bridge.addChange(changeVp);
if (changeTracker != null) {
changeTracker.addChange(changeVp);
}
}
}
final Change remove = ChangeFactory.changeResourcesChange(whoseCapital, pus, -capturedPuCount);
bridge.addChange(remove);
if (paWhoseCapital != null && paWhoseCapital.getDestroysPUs()) {
bridge.getHistoryWriter().addChildToEvent(id.getName() + " destroys " + capturedPuCount + MyFormatter.pluralize("PU", capturedPuCount) + " while taking " + whoseCapital.getName() + " capital");
if (changeTracker != null) {
changeTracker.addChange(remove);
}
} else {
bridge.getHistoryWriter().addChildToEvent(id.getName() + " captures " + capturedPuCount + MyFormatter.pluralize("PU", capturedPuCount) + " while taking " + whoseCapital.getName() + " capital");
if (changeTracker != null) {
changeTracker.addChange(remove);
}
final Change add = ChangeFactory.changeResourcesChange(id, pus, capturedPuCount);
bridge.addChange(add);
if (changeTracker != null) {
changeTracker.addChange(add);
}
}
// remove all the tokens of the captured player
final Resource tokens = data.getResourceList().getResource(Constants.TECH_TOKENS);
if (tokens != null) {
final int currTokens = whoseCapital.getResources().getQuantity(Constants.TECH_TOKENS);
final Change removeTokens = ChangeFactory.changeResourcesChange(whoseCapital, tokens, -currTokens);
bridge.addChange(removeTokens);
if (changeTracker != null) {
changeTracker.addChange(removeTokens);
}
}
}
}
// is this an allied territory, revert to original owner if it is, unless they dont own there captital
final PlayerID terrOrigOwner = OriginalOwnerTracker.getOriginalOwner(territory);
PlayerID newOwner = id;
// then we do not worry about this.
if (isTerritoryOwnerAnEnemy && terrOrigOwner != null && relationshipTracker.isAllied(terrOrigOwner, id) && !terrOrigOwner.equals(territory.getOwner())) {
final List<Territory> capitalsListOwned = new ArrayList<>(TerritoryAttachment.getAllCurrentlyOwnedCapitals(terrOrigOwner, data));
if (!capitalsListOwned.isEmpty()) {
newOwner = terrOrigOwner;
} else {
newOwner = id;
final List<Territory> capitalsListOriginal = new ArrayList<>(TerritoryAttachment.getAllCapitals(terrOrigOwner, data));
for (final Territory current : capitalsListOriginal) {
if (territory.equals(current) || current.getOwner().equals(PlayerID.NULL_PLAYERID)) {
// if a neutral controls our capital, our territories get liberated (ie: china in ww2v3)
newOwner = terrOrigOwner;
}
}
}
}
// then we set that here (except we don't set it if we are liberating allied owned territory)
if (isTerritoryOwnerAnEnemy && newOwner.equals(id) && Matches.territoryHasWhenCapturedByGoesTo().test(territory)) {
for (final String value : ta.getWhenCapturedByGoesTo()) {
final String[] s = value.split(":");
final PlayerID capturingPlayer = data.getPlayerList().getPlayerId(s[0]);
final PlayerID goesToPlayer = data.getPlayerList().getPlayerId(s[1]);
if (capturingPlayer.equals(goesToPlayer)) {
continue;
}
if (capturingPlayer.equals(id)) {
newOwner = goesToPlayer;
break;
}
}
}
if (isTerritoryOwnerAnEnemy) {
final Change takeOver = ChangeFactory.changeOwner(territory, newOwner);
bridge.getHistoryWriter().addChildToEvent(takeOver.toString());
bridge.addChange(takeOver);
if (changeTracker != null) {
changeTracker.addChange(takeOver);
changeTracker.addToConquered(territory);
}
// play a sound
if (territory.isWater()) {
// should probably see if there is something actually happening for water
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_TERRITORY_CAPTURE_SEA, id);
} else if (ta.getCapital() != null) {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_TERRITORY_CAPTURE_CAPITAL, id);
} else if (m_blitzed.contains(territory) && arrivedUnits.stream().anyMatch(Matches.unitCanBlitz())) {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_TERRITORY_CAPTURE_BLITZ, id);
} else {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_TERRITORY_CAPTURE_LAND, id);
}
}
// TODO: see if necessary
if (territory.getUnits().anyMatch(Matches.unitIsEnemyOf(data, id).and(Matches.unitCanBeDamaged()))) {
final IBattle bombingBattle = getPendingBattle(territory, true, null);
if (bombingBattle != null) {
final BattleResults results = new BattleResults(bombingBattle, WhoWon.DRAW, data);
getBattleRecords().addResultToBattle(id, bombingBattle.getBattleId(), null, 0, 0, BattleRecord.BattleResultDescription.NO_BATTLE, results);
bombingBattle.cancelBattle(bridge);
removeBattle(bombingBattle);
throw new IllegalStateException("Bombing Raids should be dealt with first! Be sure the battle has dependencies set correctly!");
}
}
captureOrDestroyUnits(territory, id, newOwner, bridge, changeTracker);
// Also check to make sure playerAttachment even HAS a capital to fix abend
if (isTerritoryOwnerAnEnemy && terrOrigOwner != null && ta.getCapital() != null && TerritoryAttachment.getAllCapitals(terrOrigOwner, data).contains(territory) && relationshipTracker.isAllied(terrOrigOwner, id)) {
// if it is give it back to the original owner
final Collection<Territory> originallyOwned = OriginalOwnerTracker.getOriginallyOwned(data, terrOrigOwner);
final List<Territory> friendlyTerritories = CollectionUtils.getMatches(originallyOwned, Matches.isTerritoryAllied(terrOrigOwner, data));
// give back the factories as well.
for (final Territory item : friendlyTerritories) {
if (item.getOwner() == terrOrigOwner) {
continue;
}
final Change takeOverFriendlyTerritories = ChangeFactory.changeOwner(item, terrOrigOwner);
bridge.addChange(takeOverFriendlyTerritories);
bridge.getHistoryWriter().addChildToEvent(takeOverFriendlyTerritories.toString());
if (changeTracker != null) {
changeTracker.addChange(takeOverFriendlyTerritories);
}
final Collection<Unit> units = CollectionUtils.getMatches(item.getUnits().getUnits(), Matches.unitIsInfrastructure());
if (!units.isEmpty()) {
final Change takeOverNonComUnits = ChangeFactory.changeOwner(units, terrOrigOwner, territory);
bridge.addChange(takeOverNonComUnits);
if (changeTracker != null) {
changeTracker.addChange(takeOverNonComUnits);
}
}
}
}
// (they may want to unload from the transport and attack)
if (Matches.territoryIsWater().test(territory) && arrivedUnits != null) {
arrivedUnits.removeAll(CollectionUtils.getMatches(arrivedUnits, Matches.unitIsLand()));
}
markWasInCombat(arrivedUnits, bridge, changeTracker);
}
use of games.strategy.triplea.attachments.PlayerAttachment in project triplea by triplea-game.
the class EndRoundDelegate method start.
@Override
public void start() {
super.start();
if (gameOver) {
return;
}
String victoryMessage;
final GameData data = getData();
if (isPacificTheater()) {
final PlayerID japanese = data.getPlayerList().getPlayerId(Constants.PLAYER_NAME_JAPANESE);
final PlayerAttachment pa = PlayerAttachment.get(japanese);
if (pa != null && pa.getVps() >= 22) {
victoryMessage = "Axis achieve VP victory";
bridge.getHistoryWriter().startEvent(victoryMessage);
final Collection<PlayerID> winners = data.getAllianceTracker().getPlayersInAlliance(data.getAllianceTracker().getAlliancesPlayerIsIn(japanese).iterator().next());
signalGameOver(victoryMessage, winners, bridge);
}
}
// Check for Winning conditions
if (isTotalVictory()) {
// Check for Win by Victory Cities
victoryMessage = " achieve TOTAL VICTORY with ";
checkVictoryCities(bridge, victoryMessage, " Total Victory VCs");
}
if (isHonorableSurrender()) {
victoryMessage = " achieve an HONORABLE VICTORY with ";
checkVictoryCities(bridge, victoryMessage, " Honorable Victory VCs");
}
if (isProjectionOfPower()) {
victoryMessage = " achieve victory through a PROJECTION OF POWER with ";
checkVictoryCities(bridge, victoryMessage, " Projection of Power VCs");
}
if (isEconomicVictory()) {
// Check for regular economic victory
for (final String allianceName : data.getAllianceTracker().getAlliances()) {
final int victoryAmount = getEconomicVictoryAmount(data, allianceName);
final Set<PlayerID> teamMembers = data.getAllianceTracker().getPlayersInAlliance(allianceName);
int teamProd = 0;
for (final PlayerID player : teamMembers) {
teamProd += getProduction(player);
if (teamProd >= victoryAmount) {
victoryMessage = allianceName + " achieve economic victory";
bridge.getHistoryWriter().startEvent(victoryMessage);
final Collection<PlayerID> winners = data.getAllianceTracker().getPlayersInAlliance(allianceName);
// Added this to end the game on victory conditions
signalGameOver(victoryMessage, winners, bridge);
}
}
}
}
// now check for generic trigger based victories
if (isTriggeredVictory()) {
// First set up a match for what we want to have fire as a default in this delegate. List out as a composite match
// OR.
// use 'null, null' because this is the Default firing location for any trigger that does NOT have 'when' set.
final Predicate<TriggerAttachment> endRoundDelegateTriggerMatch = AbstractTriggerAttachment.availableUses.and(AbstractTriggerAttachment.whenOrDefaultMatch(null, null)).and(TriggerAttachment.activateTriggerMatch().or(TriggerAttachment.victoryMatch()));
// get all possible triggers based on this match.
final HashSet<TriggerAttachment> toFirePossible = TriggerAttachment.collectForAllTriggersMatching(new HashSet<>(data.getPlayerList().getPlayers()), endRoundDelegateTriggerMatch);
if (!toFirePossible.isEmpty()) {
// get all conditions possibly needed by these triggers, and then test them.
final HashMap<ICondition, Boolean> testedConditions = TriggerAttachment.collectTestsForAllTriggers(toFirePossible, bridge);
// get all triggers that are satisfied based on the tested conditions.
final Set<TriggerAttachment> toFireTestedAndSatisfied = new HashSet<>(CollectionUtils.getMatches(toFirePossible, AbstractTriggerAttachment.isSatisfiedMatch(testedConditions)));
// now list out individual types to fire, once for each of the matches above.
TriggerAttachment.triggerActivateTriggerOther(testedConditions, toFireTestedAndSatisfied, bridge, null, null, true, true, true, true);
// will call
TriggerAttachment.triggerVictory(toFireTestedAndSatisfied, bridge, null, null, true, true, true, true);
// signalGameOver itself
}
}
if (isWW2V2() || isWW2V3()) {
return;
}
final PlayerList playerList = data.getPlayerList();
// now test older maps that only use these 5 players, to see if someone has won
final PlayerID russians = playerList.getPlayerId(Constants.PLAYER_NAME_RUSSIANS);
final PlayerID germans = playerList.getPlayerId(Constants.PLAYER_NAME_GERMANS);
final PlayerID british = playerList.getPlayerId(Constants.PLAYER_NAME_BRITISH);
final PlayerID japanese = playerList.getPlayerId(Constants.PLAYER_NAME_JAPANESE);
final PlayerID americans = playerList.getPlayerId(Constants.PLAYER_NAME_AMERICANS);
if (germans == null || russians == null || british == null || japanese == null || americans == null || playerList.size() > 5) {
return;
}
// Quick check to see who still owns their own capital
final boolean russia = TerritoryAttachment.getFirstOwnedCapitalOrFirstUnownedCapital(russians, data).getOwner().equals(russians);
final boolean germany = TerritoryAttachment.getFirstOwnedCapitalOrFirstUnownedCapital(germans, data).getOwner().equals(germans);
final boolean britain = TerritoryAttachment.getFirstOwnedCapitalOrFirstUnownedCapital(british, data).getOwner().equals(british);
final boolean japan = TerritoryAttachment.getFirstOwnedCapitalOrFirstUnownedCapital(japanese, data).getOwner().equals(japanese);
final boolean america = TerritoryAttachment.getFirstOwnedCapitalOrFirstUnownedCapital(americans, data).getOwner().equals(americans);
int count = 0;
if (!russia) {
count++;
}
if (!britain) {
count++;
}
if (!america) {
count++;
}
victoryMessage = " achieve a military victory";
if (germany && japan && count >= 2) {
bridge.getHistoryWriter().startEvent("Axis" + victoryMessage);
final Collection<PlayerID> winners = data.getAllianceTracker().getPlayersInAlliance("Axis");
signalGameOver("Axis" + victoryMessage, winners, bridge);
}
if (russia && !germany && britain && !japan && america) {
bridge.getHistoryWriter().startEvent("Allies" + victoryMessage);
final Collection<PlayerID> winners = data.getAllianceTracker().getPlayersInAlliance("Allies");
signalGameOver("Allies" + victoryMessage, winners, bridge);
}
}
use of games.strategy.triplea.attachments.PlayerAttachment in project triplea by triplea-game.
the class AbstractEndTurnDelegate method changeUnitOwnership.
private static void changeUnitOwnership(final IDelegateBridge bridge) {
final PlayerID player = bridge.getPlayerId();
final PlayerAttachment pa = PlayerAttachment.get(player);
final Collection<PlayerID> possibleNewOwners = pa.getGiveUnitControl();
final Collection<Territory> territories = bridge.getData().getMap().getTerritories();
final CompositeChange change = new CompositeChange();
final Collection<Tuple<Territory, Collection<Unit>>> changeList = new ArrayList<>();
for (final Territory currTerritory : territories) {
final TerritoryAttachment ta = TerritoryAttachment.get(currTerritory);
// if ownership should change in this territory
if (ta != null && ta.getChangeUnitOwners() != null && !ta.getChangeUnitOwners().isEmpty()) {
final Collection<PlayerID> terrNewOwners = ta.getChangeUnitOwners();
for (final PlayerID terrNewOwner : terrNewOwners) {
if (possibleNewOwners.contains(terrNewOwner)) {
// PlayerOwnerChange
final Collection<Unit> units = currTerritory.getUnits().getMatches(Matches.unitOwnedBy(player).and(Matches.unitCanBeGivenByTerritoryTo(terrNewOwner)));
if (!units.isEmpty()) {
change.add(ChangeFactory.changeOwner(units, terrNewOwner, currTerritory));
changeList.add(Tuple.of(currTerritory, units));
}
}
}
}
}
if (!change.isEmpty() && !changeList.isEmpty()) {
if (changeList.size() == 1) {
final Tuple<Territory, Collection<Unit>> tuple = changeList.iterator().next();
bridge.getHistoryWriter().startEvent("Some Units in " + tuple.getFirst().getName() + " change ownership: " + MyFormatter.unitsToTextNoOwner(tuple.getSecond()), tuple.getSecond());
} else {
bridge.getHistoryWriter().startEvent("Units Change Ownership");
for (final Tuple<Territory, Collection<Unit>> tuple : changeList) {
bridge.getHistoryWriter().addChildToEvent("Some Units in " + tuple.getFirst().getName() + " change ownership: " + MyFormatter.unitsToTextNoOwner(tuple.getSecond()), tuple.getSecond());
}
}
bridge.addChange(change);
}
}
Aggregations