use of games.strategy.engine.data.Unit in project triplea by triplea-game.
the class AbstractPlaceDelegate method moveAirOntoNewCarriers.
// TODO Here's the spot for special air placement rules
protected String moveAirOntoNewCarriers(final Territory at, final Territory producer, final Collection<Unit> units, final PlayerID player, final CompositeChange placeChange) {
if (!at.isWater()) {
return null;
}
if (!canMoveExistingFightersToNewCarriers() || AirThatCantLandUtil.isLhtrCarrierProduction(getData())) {
return null;
}
if (units.stream().noneMatch(Matches.unitIsCarrier())) {
return null;
}
// do we have any spare carrier capacity
int capacity = AirMovementValidator.carrierCapacity(units, at);
// subtract fighters that have already been produced with this carrier
// this turn.
capacity -= AirMovementValidator.carrierCost(units);
if (capacity <= 0) {
return null;
}
if (!Matches.territoryIsLand().test(producer)) {
return null;
}
if (!producer.getUnits().anyMatch(Matches.unitCanProduceUnits())) {
return null;
}
final Predicate<Unit> ownedFighters = Matches.unitCanLandOnCarrier().and(Matches.unitIsOwnedBy(player));
if (!producer.getUnits().anyMatch(ownedFighters)) {
return null;
}
if (wasConquered(producer)) {
return null;
}
if (getAlreadyProduced(producer).stream().anyMatch(Matches.unitCanProduceUnits())) {
return null;
}
final List<Unit> fighters = producer.getUnits().getMatches(ownedFighters);
final Collection<Unit> movedFighters = getRemotePlayer().getNumberOfFightersToMoveToNewCarrier(fighters, producer);
if (movedFighters == null || movedFighters.isEmpty()) {
return null;
}
final Change change = ChangeFactory.moveUnits(producer, at, movedFighters);
placeChange.add(change);
return MyFormatter.unitsToTextNoOwner(movedFighters) + " moved from " + producer.getName() + " to " + at.getName();
}
use of games.strategy.engine.data.Unit in project triplea by triplea-game.
the class AbstractPlaceDelegate method getMaxUnitsToBePlacedFrom.
/**
* Returns -1 if can place unlimited units.
*/
protected int getMaxUnitsToBePlacedFrom(final Territory producer, final Collection<Unit> units, final Territory to, final PlayerID player, final boolean countSwitchedProductionToNeighbors, final Collection<Territory> notUsableAsOtherProducers, final Map<Territory, Integer> currentAvailablePlacementForOtherProducers) {
// we may have special units with requiresUnits restrictions
final Collection<Unit> unitsCanBePlacedByThisProducer = (isUnitPlacementRestrictions() ? CollectionUtils.getMatches(units, unitWhichRequiresUnitsHasRequiredUnits(producer, true)) : new ArrayList<>(units));
if (unitsCanBePlacedByThisProducer.size() <= 0) {
return 0;
}
// if its an original factory then unlimited production
// Can be null!
final TerritoryAttachment ta = TerritoryAttachment.get(producer);
final Predicate<Unit> factoryMatch = Matches.unitIsOwnedAndIsFactoryOrCanProduceUnits(player).and(Matches.unitIsBeingTransported().negate()).and(producer.isWater() ? Matches.unitIsLand().negate() : Matches.unitIsSea().negate());
final Collection<Unit> factoryUnits = producer.getUnits().getMatches(factoryMatch);
// boolean placementRestrictedByFactory = isPlacementRestrictedByFactory();
final boolean unitPlacementPerTerritoryRestricted = isUnitPlacementPerTerritoryRestricted();
final boolean originalFactory = (ta != null && ta.getOriginalFactory());
final boolean playerIsOriginalOwner = factoryUnits.size() > 0 && this.player.equals(getOriginalFactoryOwner(producer));
final RulesAttachment ra = (RulesAttachment) player.getAttachment(Constants.RULES_ATTACHMENT_NAME);
final Collection<Unit> alreadProducedUnits = getAlreadyProduced(producer);
final int unitCountAlreadyProduced = alreadProducedUnits.size();
if (originalFactory && playerIsOriginalOwner) {
if (ra != null && ra.getMaxPlacePerTerritory() != -1) {
return Math.max(0, ra.getMaxPlacePerTerritory() - unitCountAlreadyProduced);
}
return -1;
}
// Restricts based on the STARTING number of units in a territory (otherwise it is infinite placement)
if (unitPlacementPerTerritoryRestricted) {
if (ra != null && ra.getPlacementPerTerritory() > 0) {
final int allowedPlacement = ra.getPlacementPerTerritory();
final int ownedUnitsInTerritory = CollectionUtils.countMatches(to.getUnits().getUnits(), Matches.unitIsOwnedBy(player));
if (ownedUnitsInTerritory >= allowedPlacement) {
return 0;
}
if (ra.getMaxPlacePerTerritory() == -1) {
return -1;
}
return Math.max(0, ra.getMaxPlacePerTerritory() - unitCountAlreadyProduced);
}
}
// a factory can produce the same number of units as the number of PUs the territory generates each turn (or not, if
// it has canProduceXUnits)
final int maxConstructions = howManyOfEachConstructionCanPlace(to, producer, unitsCanBePlacedByThisProducer, player).totalValues();
final boolean wasFactoryThereAtStart = wasOwnedUnitThatCanProduceUnitsOrIsFactoryInTerritoryAtStartOfStep(producer, player);
// If there's NO factory, allow placement of the factory
if (!wasFactoryThereAtStart) {
if (ra != null && ra.getMaxPlacePerTerritory() > 0) {
return Math.max(0, Math.min(maxConstructions, ra.getMaxPlacePerTerritory() - unitCountAlreadyProduced));
}
return Math.max(0, maxConstructions);
}
// getHowMuchCanUnitProduce accounts for IncreasedFactoryProduction, but does not account for maxConstructions
int production = TripleAUnit.getProductionPotentialOfTerritory(unitsAtStartOfStepInTerritory(producer), producer, player, getData(), true, true);
// increase the production by the number of constructions allowed
if (maxConstructions > 0) {
production += maxConstructions;
}
// return 0 if less than 0
if (production < 0) {
return 0;
}
production += CollectionUtils.countMatches(alreadProducedUnits, Matches.unitIsConstruction());
// Now we check if units we have already produced here could be produced by a different producer
int unitCountHaveToAndHaveBeenBeProducedHere = unitCountAlreadyProduced;
if (countSwitchedProductionToNeighbors && unitCountAlreadyProduced > 0) {
if (notUsableAsOtherProducers == null) {
throw new IllegalStateException("notUsableAsOtherProducers cannot be null if countSwitchedProductionToNeighbors is true");
}
if (currentAvailablePlacementForOtherProducers == null) {
throw new IllegalStateException("currentAvailablePlacementForOtherProducers cannot be null if countSwitchedProductionToNeighbors is true");
}
int productionCanNotBeMoved = 0;
int productionThatCanBeTakenOver = 0;
// try to find a placement move (to an adjacent sea zone) that can be taken over by some other territory factory
for (final UndoablePlacement placementMove : placements) {
if (placementMove.getProducerTerritory().equals(producer)) {
final Territory placeTerritory = placementMove.getPlaceTerritory();
final Collection<Unit> unitsPlacedByCurrentPlacementMove = placementMove.getUnits();
// for our special 'move shit around' methods.
if (!placeTerritory.isWater() || (isUnitPlacementRestrictions() && unitsPlacedByCurrentPlacementMove.stream().anyMatch(Matches.unitRequiresUnitsOnCreation()))) {
productionCanNotBeMoved += unitsPlacedByCurrentPlacementMove.size();
} else {
final int maxProductionThatCanBeTakenOverFromThisPlacement = unitsPlacedByCurrentPlacementMove.size();
// find other producers for this placement move to the same water territory
final List<Territory> newPotentialOtherProducers = getAllProducers(placeTerritory, player, unitsCanBePlacedByThisProducer);
newPotentialOtherProducers.removeAll(notUsableAsOtherProducers);
newPotentialOtherProducers.sort(getBestProducerComparator(placeTerritory, unitsCanBePlacedByThisProducer, player));
int productionThatCanBeTakenOverFromThisPlacement = 0;
for (final Territory potentialOtherProducer : newPotentialOtherProducers) {
Integer potential = currentAvailablePlacementForOtherProducers.get(potentialOtherProducer);
if (potential == null) {
potential = getMaxUnitsToBePlacedFrom(potentialOtherProducer, unitsPlacedInTerritorySoFar(placeTerritory), placeTerritory, player);
}
if (potential == -1) {
currentAvailablePlacementForOtherProducers.put(potentialOtherProducer, -1);
productionThatCanBeTakenOverFromThisPlacement = maxProductionThatCanBeTakenOverFromThisPlacement;
break;
}
final int needed = maxProductionThatCanBeTakenOverFromThisPlacement - productionThatCanBeTakenOverFromThisPlacement;
final int surplus = potential - needed;
if (surplus > 0) {
currentAvailablePlacementForOtherProducers.put(potentialOtherProducer, surplus);
productionThatCanBeTakenOverFromThisPlacement += needed;
} else {
currentAvailablePlacementForOtherProducers.put(potentialOtherProducer, 0);
productionThatCanBeTakenOverFromThisPlacement += potential;
notUsableAsOtherProducers.add(potentialOtherProducer);
}
if (surplus >= 0) {
break;
}
}
if (productionThatCanBeTakenOverFromThisPlacement > maxProductionThatCanBeTakenOverFromThisPlacement) {
throw new IllegalStateException("productionThatCanBeTakenOverFromThisPlacement should never be larger " + "than maxProductionThatCanBeTakenOverFromThisPlacement");
}
productionThatCanBeTakenOver += productionThatCanBeTakenOverFromThisPlacement;
}
if (productionThatCanBeTakenOver >= unitCountAlreadyProduced - productionCanNotBeMoved) {
break;
}
}
}
unitCountHaveToAndHaveBeenBeProducedHere = Math.max(0, unitCountAlreadyProduced - productionThatCanBeTakenOver);
}
if (ra != null && ra.getMaxPlacePerTerritory() > 0) {
return Math.max(0, Math.min(production - unitCountHaveToAndHaveBeenBeProducedHere, ra.getMaxPlacePerTerritory() - unitCountHaveToAndHaveBeenBeProducedHere));
}
return Math.max(0, production - unitCountHaveToAndHaveBeenBeProducedHere);
}
use of games.strategy.engine.data.Unit in project triplea by triplea-game.
the class AbstractPlaceDelegate method placeUnits.
@Override
public String placeUnits(final Collection<Unit> units, final Territory at, final BidMode bidMode) {
if (units == null || units.isEmpty()) {
return null;
}
final String error = isValidPlacement(units, at, player);
if (error != null) {
return error;
}
final List<Territory> producers = getAllProducers(at, player, units);
producers.sort(getBestProducerComparator(at, units, player));
final IntegerMap<Territory> maxPlaceableMap = getMaxUnitsToBePlacedMap(units, at, player, true);
// sort both producers and units so that the "to/at" territory comes first, and so that all constructions come first
// this is because the PRODUCER for ALL CONSTRUCTIONS must be the SAME as the TERRITORY they are going into
final List<Unit> unitsLeftToPlace = new ArrayList<>(units);
unitsLeftToPlace.sort(getUnitConstructionComparator());
final List<Unit> remainingUnitsToPlace = new ArrayList<>(player.getUnits().getUnits());
remainingUnitsToPlace.removeAll(unitsLeftToPlace);
while (!unitsLeftToPlace.isEmpty() && !producers.isEmpty()) {
// Get next producer territory
final Territory producer = producers.remove(0);
int maxPlaceable = maxPlaceableMap.getInt(producer);
if (maxPlaceable == 0) {
if (bidMode == BidMode.NOT_BID) {
continue;
}
maxPlaceable = 1;
}
// units may have special restrictions like RequiresUnits
final List<Unit> unitsCanBePlacedByThisProducer;
if (bidMode == BidMode.BID) {
unitsCanBePlacedByThisProducer = new ArrayList<>(unitsLeftToPlace);
} else {
unitsCanBePlacedByThisProducer = (isUnitPlacementRestrictions() ? CollectionUtils.getMatches(unitsLeftToPlace, unitWhichRequiresUnitsHasRequiredUnits(producer, true)) : new ArrayList<>(unitsLeftToPlace));
}
unitsCanBePlacedByThisProducer.sort(getHardestToPlaceWithRequiresUnitsRestrictions(true));
final int maxForThisProducer = getMaxUnitsToBePlacedFrom(producer, unitsCanBePlacedByThisProducer, at, player);
// don't forget that -1 == infinite
if (maxForThisProducer == -1 || maxForThisProducer >= unitsCanBePlacedByThisProducer.size()) {
performPlaceFrom(producer, unitsCanBePlacedByThisProducer, at, player);
unitsLeftToPlace.removeAll(unitsCanBePlacedByThisProducer);
continue;
}
final int neededExtra = unitsCanBePlacedByThisProducer.size() - maxForThisProducer;
if (maxPlaceable > maxForThisProducer) {
freePlacementCapacity(producer, neededExtra, unitsCanBePlacedByThisProducer, at, player);
final int newMaxForThisProducer = getMaxUnitsToBePlacedFrom(producer, unitsCanBePlacedByThisProducer, at, player);
if (newMaxForThisProducer != maxPlaceable && neededExtra > newMaxForThisProducer) {
throw new IllegalStateException("getMaxUnitsToBePlaced originally returned: " + maxPlaceable + ", \nWhich is not the same as it is returning after using freePlacementCapacity: " + newMaxForThisProducer + ", \nFor territory: " + at.getName() + ", Current Producer: " + producer.getName() + ", All Producers: " + producers + ", \nUnits Total: " + MyFormatter.unitsToTextNoOwner(units) + ", Units Left To Place By This Producer: " + MyFormatter.unitsToTextNoOwner(unitsCanBePlacedByThisProducer));
}
}
final Collection<Unit> placedUnits = CollectionUtils.getNMatches(unitsCanBePlacedByThisProducer, maxPlaceable, Matches.always());
performPlaceFrom(producer, placedUnits, at, player);
unitsLeftToPlace.removeAll(placedUnits);
}
if (!unitsLeftToPlace.isEmpty()) {
getDisplay().reportMessageToPlayers(Collections.singletonList(player), Collections.emptyList(), "Not enough unit production territories available", "Unit Placement Canceled");
}
// play a sound
if (units.stream().anyMatch(Matches.unitIsInfrastructure())) {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_PLACED_INFRASTRUCTURE, player);
} else if (units.stream().anyMatch(Matches.unitIsSea())) {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_PLACED_SEA, player);
} else if (units.stream().anyMatch(Matches.unitIsAir())) {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_PLACED_AIR, player);
} else {
bridge.getSoundChannelBroadcaster().playSoundForAll(SoundPath.CLIP_PLACED_LAND, player);
}
return null;
}
use of games.strategy.engine.data.Unit in project triplea by triplea-game.
the class AbstractPlaceDelegate method performPlaceFrom.
/**
* @param producer
* territory that produces the new units.
* @param placeableUnits
* the new units
* @param at
* territory where the new units get placed
*/
protected void performPlaceFrom(final Territory producer, final Collection<Unit> placeableUnits, final Territory at, final PlayerID player) {
final CompositeChange change = new CompositeChange();
// make sure we can place consuming units
final boolean didIt = canWeConsumeUnits(placeableUnits, at, true, change);
if (!didIt) {
throw new IllegalStateException("Something wrong with consuming/upgrading units");
}
final Collection<Unit> factoryAndInfrastructure = CollectionUtils.getMatches(placeableUnits, Matches.unitIsInfrastructure());
if (!factoryAndInfrastructure.isEmpty()) {
change.add(OriginalOwnerTracker.addOriginalOwnerChange(factoryAndInfrastructure, player));
}
// can we move planes to land there
final String movedAirTranscriptTextForHistory = moveAirOntoNewCarriers(at, producer, placeableUnits, player, change);
final Change remove = ChangeFactory.removeUnits(player, placeableUnits);
final Change place = ChangeFactory.addUnits(at, placeableUnits);
change.add(remove);
change.add(place);
final UndoablePlacement currentPlacement = new UndoablePlacement(change, producer, at, placeableUnits);
placements.add(currentPlacement);
updateUndoablePlacementIndexes();
final String transcriptText = MyFormatter.unitsToTextNoOwner(placeableUnits) + " placed in " + at.getName();
bridge.getHistoryWriter().startEvent(transcriptText, currentPlacement.getDescriptionObject());
if (movedAirTranscriptTextForHistory != null) {
bridge.getHistoryWriter().addChildToEvent(movedAirTranscriptTextForHistory);
}
bridge.addChange(change);
updateProducedMap(producer, placeableUnits);
}
use of games.strategy.engine.data.Unit in project triplea by triplea-game.
the class AbstractPlaceDelegate method howManyOfEachConstructionCanPlace.
/**
* @param to
* referring territory.
* @param units
* units to place
* @param player
* PlayerID
* @return an empty IntegerMap if you can't produce any constructions (will never return null)
*/
public IntegerMap<String> howManyOfEachConstructionCanPlace(final Territory to, final Territory producer, final Collection<Unit> units, final PlayerID player) {
// constructions can ONLY be produced BY the same territory that they are going into!
if (!to.equals(producer) || units == null || units.isEmpty() || units.stream().noneMatch(Matches.unitIsConstruction())) {
return new IntegerMap<>();
}
final Collection<Unit> unitsAtStartOfTurnInTo = unitsAtStartOfStepInTerritory(to);
final Collection<Unit> unitsInTo = to.getUnits().getUnits();
final Collection<Unit> unitsPlacedAlready = getAlreadyProduced(to);
// build an integer map of each unit we have in our list of held units, as well as integer maps for maximum units
// and units per turn
final IntegerMap<String> unitMapHeld = new IntegerMap<>();
final IntegerMap<String> unitMapMaxType = new IntegerMap<>();
final IntegerMap<String> unitMapTypePerTurn = new IntegerMap<>();
final int maxFactory = Properties.getFactoriesPerCountry(getData());
// Can be null!
final TerritoryAttachment terrAttachment = TerritoryAttachment.get(to);
int toProduction = 0;
if (terrAttachment != null) {
toProduction = terrAttachment.getProduction();
}
for (final Unit currentUnit : CollectionUtils.getMatches(units, Matches.unitIsConstruction())) {
final UnitAttachment ua = UnitAttachment.get(currentUnit.getType());
// account for any unit placement restrictions by territory
if (isUnitPlacementRestrictions()) {
final String[] terrs = ua.getUnitPlacementRestrictions();
final Collection<Territory> listedTerrs = getListedTerritories(terrs);
if (listedTerrs.contains(to)) {
continue;
}
if (ua.getCanOnlyBePlacedInTerritoryValuedAtX() != -1 && ua.getCanOnlyBePlacedInTerritoryValuedAtX() > toProduction) {
continue;
}
if (unitWhichRequiresUnitsHasRequiredUnits(to, false).negate().test(currentUnit)) {
continue;
}
}
// remove any units that require other units to be consumed on creation (veqryn)
if (Matches.unitConsumesUnitsOnCreation().test(currentUnit) && Matches.unitWhichConsumesUnitsHasRequiredUnits(unitsAtStartOfTurnInTo).negate().test(currentUnit)) {
continue;
}
unitMapHeld.add(ua.getConstructionType(), 1);
unitMapTypePerTurn.put(ua.getConstructionType(), ua.getConstructionsPerTerrPerTypePerTurn());
if (ua.getConstructionType().equals(Constants.CONSTRUCTION_TYPE_FACTORY)) {
unitMapMaxType.put(ua.getConstructionType(), maxFactory);
} else {
unitMapMaxType.put(ua.getConstructionType(), ua.getMaxConstructionsPerTypePerTerr());
}
}
final boolean moreWithoutFactory = Properties.getMoreConstructionsWithoutFactory(getData());
final boolean moreWithFactory = Properties.getMoreConstructionsWithFactory(getData());
final boolean unlimitedConstructions = Properties.getUnlimitedConstructions(getData());
final boolean wasFactoryThereAtStart = wasOwnedUnitThatCanProduceUnitsOrIsFactoryInTerritoryAtStartOfStep(to, player);
// build an integer map of each construction unit in the territory
final IntegerMap<String> unitMapTo = new IntegerMap<>();
if (unitsInTo.stream().anyMatch(Matches.unitIsConstruction())) {
for (final Unit currentUnit : CollectionUtils.getMatches(unitsInTo, Matches.unitIsConstruction())) {
final UnitAttachment ua = UnitAttachment.get(currentUnit.getType());
/*
* if (Matches.UnitIsFactory.test(currentUnit) && !ua.getIsConstruction())
* unitMapTO.add("factory", 1);
* else
*/
unitMapTo.add(ua.getConstructionType(), 1);
}
// account for units already in the territory, based on max
for (final String constructionType : unitMapHeld.keySet()) {
int unitMax = unitMapMaxType.getInt(constructionType);
if (wasFactoryThereAtStart && !constructionType.equals(Constants.CONSTRUCTION_TYPE_FACTORY) && !constructionType.endsWith("structure")) {
unitMax = Math.max(Math.max(unitMax, (moreWithFactory ? toProduction : 0)), (unlimitedConstructions ? 10000 : 0));
}
if (!wasFactoryThereAtStart && !constructionType.equals(Constants.CONSTRUCTION_TYPE_FACTORY) && !constructionType.endsWith("structure")) {
unitMax = Math.max(Math.max(unitMax, (moreWithoutFactory ? toProduction : 0)), (unlimitedConstructions ? 10000 : 0));
}
unitMapHeld.put(constructionType, Math.max(0, Math.min(unitMax - unitMapTo.getInt(constructionType), unitMapHeld.getInt(constructionType))));
}
}
// deal with already placed units
for (final Unit currentUnit : CollectionUtils.getMatches(unitsPlacedAlready, Matches.unitIsConstruction())) {
final UnitAttachment ua = UnitAttachment.get(currentUnit.getType());
unitMapTypePerTurn.add(ua.getConstructionType(), -1);
}
// modify this list based on how many we can place per turn
final IntegerMap<String> unitsAllowed = new IntegerMap<>();
for (final String constructionType : unitMapHeld.keySet()) {
final int unitAllowed = Math.max(0, Math.min(unitMapTypePerTurn.getInt(constructionType), unitMapHeld.getInt(constructionType)));
if (unitAllowed > 0) {
unitsAllowed.put(constructionType, unitAllowed);
}
}
// return our integer map
return unitsAllowed;
}
Aggregations