public static PoliticalActionAttachment get(
     final PlayerID player,
     final String nameOfAttachment,
     final Collection<PlayerID> playersToSearch) {
   PoliticalActionAttachment rVal =
       (PoliticalActionAttachment) player.getAttachment(nameOfAttachment);
   if (rVal == null) {
     if (playersToSearch == null) {
       throw new IllegalStateException(
           "PoliticalActionAttachment: No attachment for:"
               + player.getName()
               + " with name: "
               + nameOfAttachment);
     } else {
       for (final PlayerID otherPlayer : playersToSearch) {
         if (otherPlayer == player) continue;
         rVal = (PoliticalActionAttachment) otherPlayer.getAttachment(nameOfAttachment);
         if (rVal != null) return rVal;
       }
       throw new IllegalStateException(
           "PoliticalActionAttachment: No attachment for:"
               + player.getName()
               + " with name: "
               + nameOfAttachment);
     }
   }
   return rVal;
 }
 public static void givesBackOriginalTerritories(final IDelegateBridge aBridge) {
   final GameData data = aBridge.getData();
   final CompositeChange change = new CompositeChange();
   final Collection<PlayerID> players = data.getPlayerList().getPlayers();
   for (final PlayerID p1 : players) {
     for (final PlayerID p2 : players) {
       if (!data.getRelationshipTracker().givesBackOriginalTerritories(p1, p2)) {
         continue;
       }
       for (final Territory t : data.getMap().getTerritoriesOwnedBy(p1)) {
         final PlayerID original = OriginalOwnerTracker.getOriginalOwner(t);
         if (original == null) {
           continue;
         }
         if (original.equals(p2)) {
           change.add(ChangeFactory.changeOwner(t, original));
         }
       }
     }
   }
   if (!change.isEmpty()) {
     aBridge.getHistoryWriter().startEvent("Giving back territories to original owners");
     aBridge.addChange(change);
   }
 }
  public static Map<String, Collection<String>> collectPlayerNamesAndAlliancesInTurnOrder(
      final GameData data) {

    final LinkedHashMap<String, Collection<String>> map =
        new LinkedHashMap<String, Collection<String>>();
    for (final PlayerID player : data.getPlayerList().getPlayers()) {
      map.put(player.getName(), data.getAllianceTracker().getAlliancesPlayerIsIn(player));
    }
    return map;
  }
  private static void getNeutralOutOfWarWithAllies(
      final PoliticalActionAttachment paa, final PlayerID player, final IDelegateBridge aBridge) {
    final GameData data = aBridge.getData();
    if (!games.strategy.triplea.Properties.getAlliancesCanChainTogether(data)) {
      return;
    }

    final Collection<PlayerID> players = data.getPlayerList().getPlayers();
    final Collection<PlayerID> p1AlliedWith =
        Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(player, data));
    final CompositeChange change = new CompositeChange();
    for (final String relationshipChangeString : paa.getRelationshipChange()) {
      final String[] relationshipChange = relationshipChangeString.split(":");
      final PlayerID p1 = data.getPlayerList().getPlayerID(relationshipChange[0]);
      final PlayerID p2 = data.getPlayerList().getPlayerID(relationshipChange[1]);
      if (!(p1.equals(player) || p2.equals(player))) {
        continue;
      }
      final PlayerID pOther = (p1.equals(player) ? p2 : p1);
      final RelationshipType currentType =
          data.getRelationshipTracker().getRelationshipType(p1, p2);
      final RelationshipType newType =
          data.getRelationshipTypeList().getRelationshipType(relationshipChange[2]);
      if (Matches.RelationshipTypeIsAtWar.match(currentType)
          && Matches.RelationshipTypeIsAtWar.invert().match(newType)) {
        final Collection<PlayerID> pOtherAlliedWith =
            Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(pOther, data));
        if (!pOtherAlliedWith.contains(pOther)) {
          pOtherAlliedWith.add(pOther);
        }
        if (!p1AlliedWith.contains(player)) {
          p1AlliedWith.add(player);
        }
        for (final PlayerID p3 : p1AlliedWith) {
          for (final PlayerID p4 : pOtherAlliedWith) {
            final RelationshipType currentOther =
                data.getRelationshipTracker().getRelationshipType(p3, p4);
            if (!currentOther.equals(newType)
                && Matches.RelationshipTypeIsAtWar.match(currentOther)) {
              change.add(ChangeFactory.relationshipChange(p3, p4, currentOther, newType));
              aBridge
                  .getHistoryWriter()
                  .addChildToEvent(
                      p3.getName()
                          + " and "
                          + p4.getName()
                          + " sign a "
                          + newType.getName()
                          + " treaty");
              MoveDelegate.getBattleTracker(data)
                  .addRelationshipChangesThisTurn(p3, p4, currentOther, newType);
            }
          }
        }
      }
    }
    if (!change.isEmpty()) {
      aBridge.addChange(change);
    }
  }
 /**
  * Changes all relationships
  *
  * @param paa the political action to change the relationships for
  */
 private void changeRelationships(final PoliticalActionAttachment paa) {
   getMyselfOutOfAlliance(paa, m_player, m_bridge);
   getNeutralOutOfWarWithAllies(paa, m_player, m_bridge);
   final CompositeChange change = new CompositeChange();
   for (final String relationshipChange : paa.getRelationshipChange()) {
     final String[] s = relationshipChange.split(":");
     final PlayerID player1 = getData().getPlayerList().getPlayerID(s[0]);
     final PlayerID player2 = getData().getPlayerList().getPlayerID(s[1]);
     final RelationshipType oldRelation =
         getData().getRelationshipTracker().getRelationshipType(player1, player2);
     final RelationshipType newRelation =
         getData().getRelationshipTypeList().getRelationshipType(s[2]);
     if (oldRelation.equals(newRelation)) {
       continue;
     }
     change.add(ChangeFactory.relationshipChange(player1, player2, oldRelation, newRelation));
     m_bridge
         .getHistoryWriter()
         .addChildToEvent(
             m_bridge.getPlayerID().getName()
                 + " succeeds on action: "
                 + MyFormatter.attachmentNameToText(paa.getName())
                 + ": Changing Relationship for "
                 + player1.getName()
                 + " and "
                 + player2.getName()
                 + " from "
                 + oldRelation.getName()
                 + " to "
                 + newRelation.getName());
     MoveDelegate.getBattleTracker(getData())
         .addRelationshipChangesThisTurn(player1, player2, oldRelation, newRelation);
     /*
      * creation of new battles is handled at the beginning of the battle delegate, in
      * "setupUnitsInSameTerritoryBattles", not here.
      * if (Matches.RelationshipTypeIsAtWar.match(newRelation))
      * TriggerAttachment.triggerMustFightBattle(player1, player2, m_bridge);
      */
   }
   if (!change.isEmpty()) {
     m_bridge.addChange(change);
   }
   chainAlliancesTogether(m_bridge);
 }
Example #6
0
 // attaches to a PlayerID
 public static TechAttachment get(final PlayerID id) {
   final TechAttachment attachment =
       (TechAttachment) id.getAttachment(Constants.TECH_ATTACHMENT_NAME);
   // dont crash, as a map xml may not set the tech attachment for all players, so just create a
   // new tech attachment for them
   if (attachment == null) {
     return new TechAttachment();
   }
   return attachment;
 }
Example #7
0
 @Override
 public float getUtility() {
   // if the king has been captured...
   if (m_kingX == -1 || m_kingY == -1) {
     if (m_kingPlayer) {
       return Integer.MIN_VALUE;
     } else {
       return Integer.MAX_VALUE;
     }
   }
   // or if the king is in the corner...
   else if ((m_kingX == 0 && (m_kingY == 0 || m_kingY == m_yDimension - 1))
       || (m_kingX == m_xDimension - 1 && (m_kingY == 0 || m_kingY == m_yDimension - 1))) {
     if (m_kingPlayer) {
       return Integer.MAX_VALUE;
     } else {
       return Integer.MIN_VALUE;
     }
   }
   // otherwise...
   else {
     float numPieces = 0;
     float numOpponentPieces = 0;
     // Count the number of pieces that each player has on the board
     for (final PlayerID p : squareOwner.values()) {
       if (!p.equals(PlayerID.NULL_PLAYERID)) {
         if (p.equals(getPlayerID())) {
           numPieces += 1.0;
         } else {
           numOpponentPieces += 1.0;
         }
       }
     }
     if (numPieces == 0) {
       return Integer.MIN_VALUE;
     } else if (numOpponentPieces == 0) {
       return Integer.MAX_VALUE;
     } else {
       return numPieces / numOpponentPieces;
     }
   }
 }
 public void fireRockets(final IDelegateBridge bridge, final PlayerID player) {
   final GameData data = bridge.getData();
   final Set<Territory> rocketTerritories = getTerritoriesWithRockets(data, player);
   if (rocketTerritories.isEmpty()) {
     bridge.getHistoryWriter().startEvent(player.getName() + " has no rockets to fire");
     // getRemote(bridge).reportMessage("No rockets to fire", "No rockets to fire");
     return;
   }
   if (isWW2V2(data) || isAllRocketsAttack(data)) fireWW2V2(bridge, player, rocketTerritories);
   else fireWW2V1(bridge, player, rocketTerritories);
 }
 /**
  * @param player
  * @return gets the valid actions for this player.
  */
 public static Collection<PoliticalActionAttachment> getValidActions(
     final PlayerID player,
     final HashMap<ICondition, Boolean> testedConditions,
     final GameData data) {
   if (!games.strategy.triplea.Properties.getUsePolitics(data) || !player.amNotDeadYet(data))
     return new ArrayList<PoliticalActionAttachment>();
   return Match.getMatches(
       getPoliticalActionAttachments(player),
       new CompositeMatchAnd<PoliticalActionAttachment>(
           Matches.AbstractUserActionAttachmentCanBeAttempted(testedConditions),
           Matches.politicalActionAffectsAtLeastOneAlivePlayer(player, data)));
 }
Example #10
0
 public static TechAttachment get(final PlayerID id, final String nameOfAttachment) {
   if (!nameOfAttachment.equals(Constants.TECH_ATTACHMENT_NAME)) {
     throw new IllegalStateException(
         "TechAttachment may not yet get attachments not named:" + Constants.TECH_ATTACHMENT_NAME);
   }
   final TechAttachment attachment = (TechAttachment) id.getAttachment(nameOfAttachment);
   // dont crash, as a map xml may not set the tech attachment for all players, so just create a
   // new tech attachment for them
   if (attachment == null) {
     return new TechAttachment();
   }
   return attachment;
 }
 public static Collection<PoliticalActionAttachment> getPoliticalActionAttachments(
     final PlayerID player) {
   final ArrayList<PoliticalActionAttachment> returnList =
       new ArrayList<PoliticalActionAttachment>();
   final Map<String, IAttachment> map = player.getAttachments();
   final Iterator<String> iter = map.keySet().iterator();
   while (iter.hasNext()) {
     final IAttachment a = map.get(iter.next());
     if (a.getName().startsWith(Constants.POLITICALACTION_ATTACHMENT_PREFIX)
         && a instanceof PoliticalActionAttachment) returnList.add((PoliticalActionAttachment) a);
   }
   return returnList;
 }
Example #12
0
 @Override
 public void initialize(final IPlayerBridge bridge, final PlayerID id) {
   super.initialize(bridge, id);
   m_xDimension = getGameData().getMap().getXDimension();
   m_yDimension = getGameData().getMap().getYDimension();
   {
     final PlayerAttachment pa = (PlayerAttachment) id.getAttachment("playerAttachment");
     if (pa != null) {
       if (pa.getNeedsKing()) {
         m_kingPlayer = true;
       }
       cutoffDepth = pa.getAlphaBetaSearchDepth();
     } else {
       m_kingPlayer = false;
     }
   }
   m_opponent = null;
   for (final PlayerID p : getGameData().getPlayerList().getPlayers()) {
     if (!p.equals(id) && !p.equals(PlayerID.NULL_PLAYERID)) {
       m_opponent = p;
       break;
     }
   }
 }
 private void fireWW2V1(
     final IDelegateBridge bridge, final PlayerID player, final Set<Territory> rocketTerritories) {
   final GameData data = bridge.getData();
   final Set<Territory> targets = new HashSet<Territory>();
   for (final Territory territory : rocketTerritories) {
     targets.addAll(getTargetsWithinRange(territory, data, player));
   }
   if (targets.isEmpty()) {
     bridge
         .getHistoryWriter()
         .startEvent(player.getName() + " has no targets to attack with rockets");
     // getRemote(bridge).reportMessage("No targets to attack with rockets", "No targets to attack
     // with rockets");
     return;
   }
   final Territory attacked = getTarget(targets, player, bridge, null);
   if (attacked != null) fireRocket(player, attacked, bridge, null);
 }
 @Override
 public double getValue(final PlayerID player, final GameData data) {
   int rVal = 0;
   for (final Territory place : data.getMap().getTerritories()) {
     final TerritoryAttachment ta = TerritoryAttachment.get(place);
     /*
      * Match will Check if terr is a Land Convoy Route and check ownership of neighboring Sea Zone, and also check if
      * territory is
      * contested
      */
     if (ta != null
         && player != null
         && player.equals(place.getOwner())
         && Matches.territoryCanCollectIncomeFrom(player, data).match(place)) {
       rVal += ta.getProduction();
     }
   }
   rVal *= Properties.getPU_Multiplier(data);
   return rVal;
 }
Example #15
0
 @Override
 public Collection<GameState<Move>> successors() {
   final PlayerID successorPlayer = m_otherPlayer;
   final Collection<GameState<Move>> successors = new ArrayList<GameState<Move>>();
   int countCurrentPlayerPieces = 0;
   for (final Entry<Integer, PlayerID> start : this.squareOwner.entrySet()) {
     final PlayerID s_owner = start.getValue();
     // Only consider squares that player owns
     if (successorPlayer.equals(s_owner)) {
       countCurrentPlayerPieces++;
       final int startX = start.getKey() / m_xDimension; // (m_maxX-1);
       final int startY = start.getKey() % m_xDimension; // (m_maxX-1);
       boolean kingIsMoving;
       if (startX == m_kingX && startY == m_kingY) {
         kingIsMoving = true;
       } else {
         kingIsMoving = false;
       }
       for (int x = startX - 1; x >= 0; x--) {
         final PlayerID destination = this.get(x, startY);
         if (destination.equals(PlayerID.NULL_PLAYERID)) {
           if (kingIsMoving || !isKingsSquare(x, startY)) {
             final Move move =
                 new Move(
                     new Pair<Integer, Integer>(startX, startY),
                     new Pair<Integer, Integer>(x, startY));
             successors.add(new State(move, this));
           }
         } else {
           break;
         }
       }
       for (int x = startX + 1; x < m_xDimension; x++) {
         final PlayerID destination = this.get(x, startY);
         if (destination.equals(PlayerID.NULL_PLAYERID)) {
           if (kingIsMoving || !isKingsSquare(x, startY)) {
             final Move move =
                 new Move(
                     new Pair<Integer, Integer>(startX, startY),
                     new Pair<Integer, Integer>(x, startY));
             successors.add(new State(move, this));
           }
         } else {
           break;
         }
       }
       for (int y = startY - 1; y >= 0; y--) {
         final PlayerID destination = this.get(startX, y);
         if (destination.equals(PlayerID.NULL_PLAYERID)) {
           if (kingIsMoving || !isKingsSquare(startX, y)) {
             final Move move =
                 new Move(
                     new Pair<Integer, Integer>(startX, startY),
                     new Pair<Integer, Integer>(startX, y));
             successors.add(new State(move, this));
           }
         } else {
           break;
         }
       }
       for (int y = startY + 1; y < m_yDimension; y++) {
         final PlayerID destination = this.get(startX, y);
         if (destination.equals(PlayerID.NULL_PLAYERID)) {
           if (kingIsMoving || !isKingsSquare(startX, y)) {
             final Move move =
                 new Move(
                     new Pair<Integer, Integer>(startX, startY),
                     new Pair<Integer, Integer>(startX, y));
             successors.add(new State(move, this));
           }
         } else {
           break;
         }
       }
     }
   }
   return successors;
 }
 public static void chainAlliancesTogether(final IDelegateBridge aBridge) {
   final GameData data = aBridge.getData();
   if (!games.strategy.triplea.Properties.getAlliancesCanChainTogether(data)) {
     return;
   }
   final Collection<RelationshipType> allTypes =
       data.getRelationshipTypeList().getAllRelationshipTypes();
   RelationshipType alliedType = null;
   RelationshipType warType = null;
   for (final RelationshipType type : allTypes) {
     if (type.getRelationshipTypeAttachment().getIsDefaultWarPosition()) {
       warType = type;
     } else if (type.getRelationshipTypeAttachment().getAlliancesCanChainTogether()) {
       alliedType = type;
     }
   }
   if (alliedType == null) {
     return;
   }
   // first do alliances. then, do war (since we don't want to declare war on a potential ally).
   final Collection<PlayerID> players = data.getPlayerList().getPlayers();
   for (final PlayerID p1 : players) {
     final HashSet<PlayerID> p1NewAllies = new HashSet<>();
     final Collection<PlayerID> p1AlliedWith =
         Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(p1, data));
     for (final PlayerID p2 : p1AlliedWith) {
       p1NewAllies.addAll(
           Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(p2, data)));
     }
     p1NewAllies.removeAll(p1AlliedWith);
     p1NewAllies.remove(p1);
     for (final PlayerID p3 : p1NewAllies) {
       if (!data.getRelationshipTracker().getRelationshipType(p1, p3).equals(alliedType)) {
         final RelationshipType current =
             data.getRelationshipTracker().getRelationshipType(p1, p3);
         aBridge.addChange(ChangeFactory.relationshipChange(p1, p3, current, alliedType));
         aBridge
             .getHistoryWriter()
             .addChildToEvent(
                 p1.getName()
                     + " and "
                     + p3.getName()
                     + " are joined together in an "
                     + alliedType.getName()
                     + " treaty");
         MoveDelegate.getBattleTracker(data)
             .addRelationshipChangesThisTurn(p1, p3, current, alliedType);
       }
     }
   }
   // now war
   if (warType == null) {
     return;
   }
   for (final PlayerID p1 : players) {
     final HashSet<PlayerID> p1NewWar = new HashSet<>();
     final Collection<PlayerID> p1WarWith = Match.getMatches(players, Matches.isAtWar(p1, data));
     final Collection<PlayerID> p1AlliedWith =
         Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(p1, data));
     for (final PlayerID p2 : p1AlliedWith) {
       p1NewWar.addAll(Match.getMatches(players, Matches.isAtWar(p2, data)));
     }
     p1NewWar.removeAll(p1WarWith);
     p1NewWar.remove(p1);
     for (final PlayerID p3 : p1NewWar) {
       if (!data.getRelationshipTracker().getRelationshipType(p1, p3).equals(warType)) {
         final RelationshipType current =
             data.getRelationshipTracker().getRelationshipType(p1, p3);
         aBridge.addChange(ChangeFactory.relationshipChange(p1, p3, current, warType));
         aBridge
             .getHistoryWriter()
             .addChildToEvent(
                 p1.getName()
                     + " and "
                     + p3.getName()
                     + " declare "
                     + warType.getName()
                     + " on each other");
         MoveDelegate.getBattleTracker(data)
             .addRelationshipChangesThisTurn(p1, p3, current, warType);
       }
     }
   }
 }
 private 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(
               new CompositeMatchAnd<Unit>(
                   Matches.enemyUnit(player, data), Matches.unitIsBeingTransported().invert()));
   final Collection<Unit> enemyTargetsTotal =
       Match.getMatches(
           enemyUnits, Matches.UnitIsAtMaxDamageOrNotCanBeDamaged(attackedTerritory).invert());
   final Collection<Unit> targets = new ArrayList<Unit>();
   final Collection<Unit> rockets;
   // attackFrom could be null if WW2V1
   if (attackFrom == null) rockets = null;
   else
     rockets =
         new ArrayList<Unit>(
             Match.getMatches(attackFrom.getUnits().getUnits(), rocketMatch(player, data)));
   final int numberOfAttacks =
       (rockets == null
           ? 1
           : Math.min(
               TechAbilityAttachment.getRocketNumberPerTerritory(player, data),
               TechAbilityAttachment.getRocketDiceNumber(rockets, data)));
   if (numberOfAttacks <= 0) return;
   final String transcript;
   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<UnitType>();
     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 =
         Match.getMatches(enemyTargetsTotal, Matches.unitIsOfTypes(legalTargetsForTheseRockets));
     if (enemyTargets.isEmpty()) return; // TODO: this sucks
     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 =
       !games.strategy.triplea.Properties.getUseBombingMaxDiceSidesAndBonus(data)
           || rockets == null;
   int cost = 0;
   if (!games.strategy.triplea.Properties.getLL_DAMAGE_ONLY(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) {
         cost += r + 1; // we are zero based
       }
       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();
         int bonus = ua.getBombingBonus();
         // both could be -1, meaning they were not set. if they were not set, then we use default
         // dice sides for the map, and zero for the bonus.
         if (maxDice < 0) maxDice = diceSides;
         if (bonus < 0) bonus = 0;
         // 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 = rolls[i] + highestBonus;
           rolls[i] = r;
           cost += r + 1; // we are zero based
         }
         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;
         cost += r + 1; // we are zero based
       }
       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();
         // both could be -1, meaning they were not set. if they were not set, then we use default
         // dice sides for the map, and zero for the bonus.
         if (maxDice < 0 || doNotUseBombingBonus) maxDice = diceSides;
         if (bonus < 0 || doNotUseBombingBonus) bonus = 0;
         // now, regardless of whether they were set or not, we have to apply "low luck" to them,
         // meaning in this case that we reduce the 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 = rolls[i] + highestBonus;
           rolls[i] = r;
           cost += r + 1; // we are zero based
         }
         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<Unit>();
     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.getPU_Multiplier(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<Unit>(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 (Match.someMatch(targets, Matches.UnitCanDieFromReachingMaxDamage)) {
     final List<Unit> unitsCanDie =
         Match.getMatches(targets, Matches.UnitCanDieFromReachingMaxDamage);
     unitsCanDie.retainAll(
         Match.getMatches(
             unitsCanDie, Matches.UnitIsAtMaxDamageOrNotCanBeDamaged(attackedTerritory)));
     if (!unitsCanDie.isEmpty()) {
       // targets.removeAll(unitsCanDie);
       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.getName());
 }
Example #18
0
 private void layoutPlayerPanel(final SetupPanel parent) {
   final GameData data = m_gameSelectorModel.getGameData();
   m_localPlayerPanel.removeAll();
   m_playerTypes.clear();
   m_localPlayerPanel.setLayout(new GridBagLayout());
   if (data == null) {
     m_localPlayerPanel.add(new JLabel("No game selected!"));
     return;
   }
   final Collection<String> disableable = data.getPlayerList().getPlayersThatMayBeDisabled();
   final HashMap<String, Boolean> playersEnablementListing =
       data.getPlayerList().getPlayersEnabledListing();
   final Map<String, String> reloadSelections = PlayerID.currentPlayers(data);
   final String[] playerTypes = data.getGameLoader().getServerPlayerTypes();
   final String[] playerNames = data.getPlayerList().getNames();
   // if the xml was created correctly, this list will be in turn order. we want to keep it that
   // way.
   int gridx = 0;
   int gridy = 0;
   if (!disableable.isEmpty() || playersEnablementListing.containsValue(Boolean.FALSE)) {
     final JLabel enableLabel = new JLabel("Use");
     enableLabel.setForeground(Color.black);
     m_localPlayerPanel.add(
         enableLabel,
         new GridBagConstraints(
             gridx++,
             gridy,
             1,
             1,
             0,
             0,
             GridBagConstraints.WEST,
             GridBagConstraints.NONE,
             new Insets(0, 5, 5, 0),
             0,
             0));
   }
   final JLabel nameLabel = new JLabel("Name");
   nameLabel.setForeground(Color.black);
   m_localPlayerPanel.add(
       nameLabel,
       new GridBagConstraints(
           gridx++,
           gridy,
           1,
           1,
           0,
           0,
           GridBagConstraints.WEST,
           GridBagConstraints.NONE,
           new Insets(0, 5, 5, 0),
           0,
           0));
   final JLabel typeLabel = new JLabel("Type");
   typeLabel.setForeground(Color.black);
   m_localPlayerPanel.add(
       typeLabel,
       new GridBagConstraints(
           gridx++,
           gridy,
           1,
           1,
           0,
           0,
           GridBagConstraints.WEST,
           GridBagConstraints.NONE,
           new Insets(0, 5, 5, 0),
           0,
           0));
   final JLabel allianceLabel = new JLabel("Alliance");
   allianceLabel.setForeground(Color.black);
   m_localPlayerPanel.add(
       allianceLabel,
       new GridBagConstraints(
           gridx++,
           gridy,
           1,
           1,
           0,
           0,
           GridBagConstraints.WEST,
           GridBagConstraints.NONE,
           new Insets(0, 7, 5, 5),
           0,
           0));
   for (final String playerName : playerNames) {
     final PBEMLocalPlayerComboBoxSelector selector =
         new PBEMLocalPlayerComboBoxSelector(
             playerName,
             reloadSelections,
             disableable,
             playersEnablementListing,
             data.getAllianceTracker()
                 .getAlliancesPlayerIsIn(data.getPlayerList().getPlayerID(playerName)),
             playerTypes,
             parent);
     m_playerTypes.add(selector);
     selector.layout(++gridy, m_localPlayerPanel);
   }
   m_localPlayerPanel.validate();
   m_localPlayerPanel.invalidate();
 }
Example #19
0
 private void checkForCaptures(final int endX, final int endY) {
   for (final Entry<Integer, PlayerID> s : squareOwner.entrySet()) {
     final int squareX = s.getKey() / m_xDimension;
     final int squareY = s.getKey() % m_xDimension;
     final PlayerID s_owner = s.getValue();
     // PlayerID owner = s_owner;
     if (s_owner.equals(m_otherPlayer)) {
       if (squareX == endX) {
         if (squareY == endY + 1) {
           final PlayerID above = get(endX, endY + 2);
           if (above != null && above.equals(m_playerPerformingMove)) {
             // Can the king be captured?
             if (squareX == m_kingX && squareY == m_kingY) {
               final PlayerID left = get(endX - 1, endY + 1);
               final PlayerID right = get(endX + 1, endY + 1);
               if (left != null
                   && right != null
                   && left.equals(m_playerPerformingMove)
                   && right.equals(m_playerPerformingMove)) {
                 squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
                 m_kingX = -1;
                 m_kingY = -1;
               }
             }
             // Can a pawn be captured?
             else {
               squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
             }
           }
         } else if (squareY == endY - 1) {
           final PlayerID below = get(endX, endY - 2);
           if (below != null && below.equals(m_playerPerformingMove)) {
             // Can the king be captured?
             if (squareX == m_kingX && squareY == m_kingY) {
               System.out.println(
                   "Possible king capture with king at (" + squareX + "," + squareY + ")");
               final PlayerID left = get(endX - 1, endY - 1);
               final PlayerID right = get(endX + 1, endY - 1);
               if (left != null
                   && right != null
                   && left.equals(m_playerPerformingMove)
                   && right.equals(m_playerPerformingMove)) {
                 squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
                 m_kingX = -1;
                 m_kingY = -1;
               }
             }
             // Can a pawn be captured?
             else {
               squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
             }
           }
         }
       }
       if (endY == squareY) {
         if (squareX == endX + 1) {
           final PlayerID right = get(endX + 2, endY);
           if (right != null && right.equals(m_playerPerformingMove)) {
             // Can the king be captured?
             if (squareX == m_kingX && squareY == m_kingY) {
               System.out.println(
                   "Possible king capture with king at (" + squareX + "," + squareY + ")");
               final PlayerID above = get(endX + 1, endY - 1);
               final PlayerID below = get(endX + 1, endY + 1);
               if (above != null
                   && below != null
                   && above.equals(m_playerPerformingMove)
                   && below.equals(m_playerPerformingMove)) {
                 squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
                 m_kingX = -1;
                 m_kingY = -1;
               }
             }
             // Can a pawn be captured?
             else {
               squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
             }
           }
         } else if (squareX == endX - 1) {
           final PlayerID left = get(endX - 2, endY);
           if (left != null && left.equals(m_playerPerformingMove)) {
             // Can the king be captured?
             if (squareX == m_kingX && squareY == m_kingY) {
               System.out.println(
                   "Possible king capture with king at (" + squareX + "," + squareY + ")");
               final PlayerID above = get(endX - 1, endY - 1);
               final PlayerID below = get(endX - 1, endY + 1);
               if (above != null
                   && below != null
                   && above.equals(m_playerPerformingMove)
                   && below.equals(m_playerPerformingMove)) {
                 squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
                 m_kingX = -1;
                 m_kingY = -1;
               }
             }
             // Can a pawn be captured?
             else {
               squareOwner.put(squareX * m_xDimension + squareY, PlayerID.NULL_PLAYERID);
             }
           }
         }
       }
     }
   }
 }