예제 #1
0
  // Is used if one Territory attacks another returns true if ownedby player has won
  public boolean Attack(Territory defterritory) {

    // Used Variables get initialized
    int attackarmys;
    int defarmys;

    // Get positioned armys on this territory which is attacking and cap them on 3
    attackarmys = (this.CheckArmyCount() - 1);
    if (attackarmys >= 3) {
      attackarmys = 3;
    }
    // Get positioned armys on the other territory which is defending and cap them on 2
    defarmys = (defterritory.CheckArmyCount());
    if (defarmys >= 2) {
      defarmys = 2;
    }
    // If 1 or more army are attacking
    if (attackarmys >= 1) {

      // Create Random Generator
      Random randomGenerator = new Random();

      // Create Arrays for representing the dices
      int[] attackeyes = new int[attackarmys];
      int[] defeyes = new int[defarmys];

      // Get random numbers for the attackdices
      for (int i = 0; i < attackarmys; i++) {
        attackeyes[i] = randomGenerator.nextInt(6) + 1;
      }
      // Get random numbers for the defensedices
      for (int i = 0; i < defarmys; i++) {
        defeyes[i] = randomGenerator.nextInt(6) + 1;
      }
      // Sort the Arrays by number
      java.util.Arrays.sort(attackeyes);
      java.util.Arrays.sort(defeyes);

      // Go through the arrays starting with the highest element
      for (int i = 1; i < (defarmys + 1) && i < (attackarmys + 1); i++) {
        // Check if the attackdice is greater than the defensedice
        if (attackeyes[attackarmys - i] > defeyes[defarmys - i]) {
          System.out.println(
              "Rollwin:"
                  + i
                  + " - Eyes:"
                  + attackeyes[attackarmys - i]
                  + "/"
                  + defeyes[defarmys - i]);
          // If 1 army of the defending territory was removed and the corresponding army was beaten
          // (completely)
          if (defterritory.removeArmies(1, this.ownedby)) {
            // Take over the territory with the attacking armys
            defterritory.enforceArmies(attackarmys - i, this.ownedby);
            // And remove them by their former territory
            this.removeArmies(attackarmys - i, this.ownedby);
            // Return true for a successful attack
            return true;
          }

        } else {
          System.out.println(
              "Rolllose:"
                  + i
                  + " - Eyes:"
                  + attackeyes[attackarmys - i]
                  + "/"
                  + defeyes[defarmys - i]);
          // Else remove one army of the attackers
          this.removeArmies(1, this.ownedby);
        }
      }
    }
    return false;
  }