public ClanPosition getPosition(String pos) {
   if (pos == null) return null;
   pos = pos.trim();
   if (CMath.isInteger(pos)) {
     int i = CMath.s_int(pos);
     if ((i >= 0) && (i < positions.length)) return positions[i];
   }
   for (ClanPosition P : positions) if (P.getID().equalsIgnoreCase(pos)) return P;
   return null;
 }
 public void setXpCalculationFormulaStr(String newXpCalculationFormula) {
   if (newXpCalculationFormula == null) newXpCalculationFormula = "";
   xpCalculationFormulaStr = newXpCalculationFormula;
   if (xpCalculationFormulaStr.trim().length() == 0)
     this.xpCalculationFormula = CMath.compileMathExpression(DEFAULT_XP_FORMULA);
   else
     try {
       this.xpCalculationFormula = CMath.compileMathExpression(xpCalculationFormulaStr);
     } catch (Exception e) {
       Log.errOut("DefaultClanGovernment", e.getMessage());
     }
 }
 public Item buildMyThing(MOB mob, Room room) {
   Area A = room.getArea();
   boolean bonusWorthy = (Druid_MyPlants.myPlant(room, mob, 0) == null);
   Vector V = Druid_MyPlants.myAreaPlantRooms(mob, room.getArea());
   int pct = 0;
   if (A.getAreaIStats()[Area.Stats.VISITABLE_ROOMS.ordinal()] > 10)
     pct =
         (int)
             Math.round(
                 100.0
                     * CMath.div(
                         V.size(), A.getAreaIStats()[Area.Stats.VISITABLE_ROOMS.ordinal()]));
   Item I = buildMyPlant(mob, room);
   if ((I != null)
       && ((mob.charStats().getCurrentClass().baseClass().equalsIgnoreCase("Druid"))
           || (CMSecurity.isASysOp(mob)))) {
     if (!CMLib.law().isACity(A)) {
       if (pct > 0) {
         int newPct =
             (int)
                 Math.round(
                     100.0
                         * CMath.div(
                             V.size(), A.getAreaIStats()[Area.Stats.VISITABLE_ROOMS.ordinal()]));
         if ((newPct >= 50) && (A.fetchEffect("Chant_DruidicConnection") == null)) {
           Ability A2 = CMClass.getAbility("Chant_DruidicConnection");
           if (A2 != null) A2.invoke(mob, A, true, 0);
         }
       }
     } else if ((bonusWorthy) && (!mob.isMonster())) {
       long[] num = (long[]) plantBonuses.get(mob.Name() + "/" + room.getArea().Name());
       if ((num == null)
           || (System.currentTimeMillis() - num[1]
               > (room.getArea().getTimeObj().getDaysInMonth()
                   * room.getArea().getTimeObj().getHoursInDay()
                   * CMProps.getMillisPerMudHour()))) {
         num = new long[2];
         plantBonuses.remove(mob.Name() + "/" + room.getArea().Name());
         plantBonuses.put(mob.Name() + "/" + room.getArea().Name(), num);
         num[1] = System.currentTimeMillis();
       }
       if (V.size() >= num[0]) {
         num[0]++;
         if (num[0] < 19) {
           mob.tell("You have made this city greener.");
           CMLib.leveler().postExperience(mob, null, null, (int) num[0], false);
         }
       }
     }
   }
   return I;
 }
Exemple #4
0
 public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException {
   if (!mob.isMonster()) {
     if ((CMath.bset(mob.getBitmap(), MOB.ATT_MXP))
         || (mob.session().clientTelnetMode(Session.TELNET_MXP))) {
       if (mob.session().clientTelnetMode(Session.TELNET_MXP))
         mob.session().rawOut("\033[3z \033[7z");
       mob.setBitmap(CMath.unsetb(mob.getBitmap(), MOB.ATT_MXP));
       mob.session().changeTelnetMode(Session.TELNET_MXP, false);
       mob.session().setClientTelnetMode(Session.TELNET_MXP, false);
       mob.tell("MXP codes are disabled.\n\r");
     } else mob.tell("MXP codes are already disabled.\n\r");
   }
   return false;
 }
Exemple #5
0
  public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException {
    boolean quiet = false;

    if (mob == null) return false;
    Room R = mob.location();
    if (R == null) return false;
    if ((commands.size() > 2)
        && (commands.lastElement() instanceof String)
        && (((String) commands.lastElement()).equalsIgnoreCase("UNOBTRUSIVELY"))) {
      commands.removeElementAt(commands.size() - 1);
      quiet = true;
    }
    if ((commands.size() > 1) && (commands.elementAt(1) instanceof MOB))
      return processFollow(mob, (MOB) commands.elementAt(1), quiet);

    if (commands.size() < 2) {
      mob.tell("Follow whom?");
      return false;
    }

    String whomToFollow = CMParms.combine(commands, 1);
    if ((whomToFollow.equalsIgnoreCase("self") || whomToFollow.equalsIgnoreCase("me"))
        || (mob.name().toUpperCase().startsWith(whomToFollow))) {
      nofollow(mob, true, quiet);
      return false;
    }
    MOB target = R.fetchInhabitant(whomToFollow);
    if ((target == null) || (!CMLib.flags().canBeSeenBy(target, mob))) {
      mob.tell("I don't see them here.");
      return false;
    }
    if ((target.isMonster()) && (!mob.isMonster())) {
      mob.tell("You cannot follow '" + target.name() + "'.");
      return false;
    }
    if (CMath.bset(target.getBitmap(), MOB.ATT_NOFOLLOW)) {
      mob.tell(target.name() + " is not accepting followers.");
      return false;
    }
    MOB ultiTarget = target.amUltimatelyFollowing();
    if ((ultiTarget != null) && (CMath.bset(ultiTarget.getBitmap(), MOB.ATT_NOFOLLOW))) {
      mob.tell(ultiTarget.name() + " is not accepting followers.");
      return false;
    }
    processFollow(mob, target, quiet);
    return false;
  }
 public int castingQuality(MOB mob, Physical target) {
   if (mob != null) {
     Room R = mob.location();
     if (R != null) {
       if (CMath.bset(weatherQue(R), WEATHERQUE_RAIN))
         return super.castingQuality(mob, target, Ability.QUALITY_BENEFICIAL_SELF);
     }
   }
   return super.castingQuality(mob, target);
 }
  public boolean okMessage(final Environmental myHost, final CMMsg msg) {
    if (affected == null) return super.okMessage(myHost, msg);

    if (affected instanceof MOB) {
      MOB mob = (MOB) affected;
      if ((msg.amITarget(mob))
          && (!msg.amISource(mob))
          && (mob.location() != msg.source().location())
          && (msg.tool() != null)
          && (msg.tool() instanceof Ability)
          && (CMath.bset(((Ability) msg.tool()).flags(), Ability.FLAG_SUMMONING))
          && (!mob.amDead())) {
        msg.source()
            .location()
            .showHappens(
                CMMsg.MSG_OK_VISUAL, "Magical energy fizzles and is absorbed into the air!");
        return false;
      }
    } else if (affected instanceof Room) {
      Room R = (Room) affected;
      if ((msg.tool() != null)
          && (msg.tool() instanceof Ability)
          && (CMath.bset(((Ability) msg.tool()).flags(), Ability.FLAG_SUMMONING))) {
        Ability A = (Ability) msg.tool();
        if (((A.classificationCode() & Ability.ALL_ACODES) == Ability.ACODE_CHANT)
            || ((A.classificationCode() & Ability.ALL_ACODES) == Ability.ACODE_SPELL)
            || ((A.classificationCode() & Ability.ALL_ACODES) == Ability.ACODE_PRAYER)
            || ((A.classificationCode() & Ability.ALL_ACODES) == Ability.ACODE_SONG)) {
          if ((msg.source().location() != null) && (msg.source().location() != R))
            msg.source()
                .location()
                .showHappens(
                    CMMsg.MSG_OK_VISUAL, "Magical energy fizzles and is absorbed into the air!");
          R.showHappens(
              CMMsg.MSG_OK_VISUAL, "Magical energy fizzles and is absorbed into the air!");
        }
        return false;
      }
    }
    return super.okMessage(myHost, msg);
  }
  protected List<List<String>> loadRecipes() {
    String filename = parametersFile();
    List<List<String>> recipes =
        (List<List<String>>) Resources.getResource("PARSED_RECIPE: " + filename);
    if (recipes == null) {
      StringBuffer str =
          new CMFile(Resources.buildResourcePath("skills") + filename, null, true).text();
      recipes = loadList(str);
      if (recipes.size() == 0) Log.errOut("LeatherWorking", "Recipes not found!");
      else {
        List<List<String>> pleaseAdd = new Vector();
        for (int r = 0; r < recipes.size(); r++) {
          List<String> V = recipes.get(r);
          if (V.size() > 0) {
            String name = (String) V.get(RCP_FINALNAME);
            int baseLevel = CMath.s_int((String) V.get(RCP_LEVEL)) + 2;

            List<String> V1 = new XVector<String>(V);
            V1.set(RCP_FINALNAME, "Cuirbouli " + name);
            V1.set(RCP_LEVEL, "" + (baseLevel + 37));
            pleaseAdd.add(V1);

            V1 = new XVector<String>(V);
            V1.set(RCP_FINALNAME, "Reinforced " + name);
            V1.set(RCP_LEVEL, "" + (baseLevel + 45));
            pleaseAdd.add(V1);

            V1 = new XVector<String>(V);
            V1.set(RCP_FINALNAME, "Masterwork " + name);
            V1.set(RCP_LEVEL, "" + (baseLevel + 54));
            pleaseAdd.add(V1);

            V1 = new XVector<String>(V);
            V1.set(RCP_FINALNAME, "Laminar " + name);
            V1.set(RCP_LEVEL, "" + (baseLevel + 63));
            pleaseAdd.add(V1);

            V1 = new XVector<String>(V);
            V1.set(RCP_FINALNAME, "Battlemoulded " + name);
            V1.set(RCP_LEVEL, "" + (baseLevel + 72));
            pleaseAdd.add(V1);

            V.set(RCP_FINALNAME, "Designer " + name);
            V.set(RCP_LEVEL, "" + (baseLevel + 30));
          }
        }
        for (int i = 0; i < pleaseAdd.size(); i++) recipes.add(pleaseAdd.get(i));
      }
      Resources.submitResource("PARSED_RECIPE: " + filename, recipes);
    }
    return recipes;
  }
 public void setStat(String code, String val) {
   if (CMLib.coffeeMaker().getGenItemCodeNum(code) >= 0)
     CMLib.coffeeMaker().setGenItemStat(this, code, val);
   else
     switch (getCodeNum(code)) {
       case 0:
         setClanID(val);
         break;
       case 1:
         setCIType(CMath.s_parseListIntExpression(ClanItem.CI_DESC, val));
         break;
       default:
         CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val);
         break;
     }
 }
Exemple #10
0
  public String healthText(MOB viewer, MOB mob) {
    double pct = (CMath.div(mob.curState().getHitPoints(), mob.maxState().getHitPoints()));

    if (pct < .10) return "^r" + mob.displayName(viewer) + "^r is facing a cold death!^N";
    else if (pct < .20) return "^r" + mob.displayName(viewer) + "^r is covered in blood.^N";
    else if (pct < .30)
      return "^r" + mob.displayName(viewer) + "^r is bleeding badly from lots of wounds.^N";
    else if (pct < .40)
      return "^y" + mob.displayName(viewer) + "^y has numerous bloody wounds and gashes.^N";
    else if (pct < .50)
      return "^y" + mob.displayName(viewer) + "^y has some bloody wounds and gashes.^N";
    else if (pct < .60) return "^p" + mob.displayName(viewer) + "^p has a few bloody wounds.^N";
    else if (pct < .70) return "^p" + mob.displayName(viewer) + "^p is cut and bruised heavily.^N";
    else if (pct < .80)
      return "^g" + mob.displayName(viewer) + "^g has some minor cuts and bruises.^N";
    else if (pct < .90)
      return "^g" + mob.displayName(viewer) + "^g has a few bruises and scratched scales.^N";
    else if (pct < .99) return "^g" + mob.displayName(viewer) + "^g has a few small bruises.^N";
    else return "^c" + mob.displayName(viewer) + "^c is in perfect health.^N";
  }
  public String getHelpStr() {
    if (getLongDesc().length() == 0) return null;
    if (helpStr == null) {
      StringBuilder str = new StringBuilder("\n\rOrganization type: " + getName() + "\n\r\n\r");
      str.append(getLongDesc()).append("\n\r");
      str.append("\n\rAuthority Chart:\n\r\n\r");
      final List<ClanPosition> showablePositions = new Vector<ClanPosition>();
      for (ClanPosition P : getPositions()) {
        boolean showMe = false;
        for (Clan.Authority a : P.getFunctionChart()) if (a == Authority.CAN_DO) showMe = true;
        if (showMe) showablePositions.add(P);
      }
      final List<ClanPosition> sortedPositions = new Vector<ClanPosition>();
      while (sortedPositions.size() < showablePositions.size()) {
        ClanPosition highPos = null;
        for (ClanPosition P : showablePositions)
          if ((!sortedPositions.contains(P))
              && ((highPos == null) || (highPos.getRank() < P.getRank()))) highPos = P;
        sortedPositions.add(highPos);
      }
      final int[] posses = new int[sortedPositions.size()];
      int posTotalLen = 0;
      for (int p = 0; p < sortedPositions.size(); p++) {
        posses[p] = sortedPositions.get(p).getName().length() + 2;
        posTotalLen += posses[p];
      }
      int funcMaxLen = 0;
      int funcTotal = 0;
      String[] functionNames = new String[Clan.Function.values().length];
      for (int f = 0; f < Clan.Function.values().length; f++) {
        Clan.Function func = Clan.Function.values()[f];
        funcTotal += func.name().length() + 1;
        if (func.name().length() > funcMaxLen) funcMaxLen = func.name().length() + 1;
        functionNames[f] = func.name();
      }
      int funcAvg = funcTotal / Clan.Function.values().length;
      int funcMaxAvg = (int) CMath.round((double) funcAvg * 1.3);
      while ((funcMaxLen > funcMaxAvg) && ((funcMaxAvg + posTotalLen) > 78)) funcMaxLen--;
      if (posses.length > 0)
        while ((funcMaxLen + posTotalLen) > 78) {
          int highPos = 0;
          for (int p = 1; p < sortedPositions.size(); p++)
            if (posses[p] > posses[highPos]) highPos = p;
          posTotalLen--;
          posses[highPos]--;
        }

      final int commandColLen = funcMaxLen;
      str.append(CMStrings.padRight("Command", commandColLen - 1)).append("!");
      for (int p = 0; p < posses.length; p++) {
        ClanPosition pos = sortedPositions.get(p);
        String name = CMStrings.capitalizeAndLower(pos.getName().replace('_', ' '));
        str.append(CMStrings.padRight(name, posses[p] - 1));
        if (p < posses.length - 1) str.append("!");
      }
      str.append("\n\r");
      Object lineDraw =
          new Object() {
            private static final String line =
                "----------------------------------------------------------------------------";

            public String toString() {
              StringBuilder s = new StringBuilder("");
              s.append(line.substring(0, commandColLen - 1)).append("+");
              for (int p = 0; p < posses.length; p++) {
                s.append(CMStrings.padRight(line, posses[p] - 1));
                if (p < posses.length - 1) s.append("+");
              }
              return s.toString();
            }
          };
      str.append(lineDraw.toString()).append("\n\r");
      for (Clan.Function func : Clan.Function.values()) {
        String fname = CMStrings.capitalizeAndLower(func.toString().replace('_', ' '));
        str.append(CMStrings.padRight(fname, commandColLen - 1)).append("!");
        for (int p = 0; p < sortedPositions.size(); p++) {
          ClanPosition pos = sortedPositions.get(p);
          Authority auth = pos.getFunctionChart()[func.ordinal()];
          String x = "";
          if (auth == Authority.CAN_DO) x = "X";
          else if (auth == Authority.MUST_VOTE_ON) x = "v";
          str.append(CMStrings.padCenter(x, posses[p] - 1));
          if (p < posses.length - 1) str.append("!");
        }
        str.append("\n\r").append(lineDraw.toString()).append("\n\r");
      }
      /*
      protected String[] 	clanEffectNames			=null;
      protected int[] 	clanEffectLevels		=null;
      protected String[] 	clanEffectParms			=null;
      protected String[] 	clanAbilityNames		=null;
      protected int[] 	clanAbilityLevels		=null;
      protected int[] 	clanAbilityProficiencies=null;
      protected boolean[] clanAbilityQuals		=null;
      */

      if ((clanAbilityLevels != null)
          && (clanEffectLevels != null)
          && (clanAbilityLevels.length > 0)
          && (clanEffectLevels.length > 0)) {
        str.append("\n\rBenefits per Clan Level:\n\r");
        int maxLevel = -1;
        for (int x : clanEffectLevels) if (x > maxLevel) maxLevel = x;
        for (int x : clanAbilityLevels) if (x > maxLevel) maxLevel = x;
        for (int l = 1; l <= maxLevel; l++) {
          final List<String> levelBenefits = new LinkedList<String>();
          for (int x = 0; x < clanEffectLevels.length; x++)
            if (clanEffectLevels[x] == l) {
              final Ability A = CMClass.getAbility(clanEffectNames[x]);
              if (A != null) {
                A.setMiscText(clanEffectParms[x]);
                String desc = A.accountForYourself();
                if ((desc == null) || (desc.length() == 0))
                  desc = "Members gain the following effect: " + A.name();
                levelBenefits.add(desc);
              }
            }
          for (int x = 0; x < clanAbilityLevels.length; x++)
            if (clanAbilityLevels[x] == l) {
              final Ability A = CMClass.getAbility(clanAbilityNames[x]);
              if (A != null) {
                if (clanAbilityQuals[x]) levelBenefits.add("Members qualify for: " + A.name());
                else levelBenefits.add("Members automatically gain: " + A.name());
              }
            }
          for (final String bene : levelBenefits) str.append("Level " + l + ": " + bene + "\n\r");
        }
      }
      helpStr = str.toString();
    }
    return helpStr;
  }
 public void setStat(String code, String val) {
   int num = 0;
   int numDex = code.length();
   while ((numDex > 0) && (Character.isDigit(code.charAt(numDex - 1)))) numDex--;
   if (numDex < code.length()) {
     num = CMath.s_int(code.substring(numDex));
     code = code.substring(0, numDex);
   }
   final GOVT_STAT_CODES stat = getStatIndex(code);
   if (stat == null) {
     return;
   }
   switch (stat) {
     case NAME:
       name = val;
       break;
     case AUTOROLE:
       {
         ClanPosition P = getPosition(val);
         if (P != null) autoRole = P.getRoleID();
         break;
       }
     case ACCEPTPOS:
       {
         ClanPosition P = getPosition(val);
         if (P != null) acceptPos = P.getRoleID();
         break;
       }
     case SHORTDESC:
       shortDesc = val;
       break;
     case LONGDESC:
       longDesc = val;
       break;
     case XPLEVELFORMULA:
       setXpCalculationFormulaStr(val);
       break;
     case REQUIREDMASK:
       requiredMaskStr = val;
       break;
     case ISPUBLIC:
       isPublic = CMath.s_bool(val);
       break;
     case ISFAMILYONLY:
       isFamilyOnly = CMath.s_bool(val);
       break;
     case OVERRIDEMINMEMBERS:
       {
         if (val.length() == 0) overrideMinMembers = null;
         else overrideMinMembers = Integer.valueOf(CMath.s_int(val));
         break;
       }
     case CONQUESTENABLED:
       conquestEnabled = CMath.s_bool(val);
       break;
     case CONQUESTITEMLOYALTY:
       conquestItemLoyalty = CMath.s_bool(val);
       break;
     case CONQUESTDEITYBASIS:
       conquestByWorship = CMath.s_bool(val);
       break;
     case MAXVOTEDAYS:
       maxVoteDays = CMath.s_int(val);
       break;
     case VOTEQUORUMPCT:
       voteQuorumPct = CMath.s_int(val);
       break;
     case AUTOPROMOTEBY:
       {
         Clan.AutoPromoteFlag flag =
             (Clan.AutoPromoteFlag) CMath.s_valueOf(Clan.AutoPromoteFlag.values(), val);
         if (flag != null) autoPromoteBy = flag;
         break;
       }
     case VOTEFUNCS:
       {
         final Vector<String> funcs = CMParms.parseCommas(val.toUpperCase().trim(), true);
         for (ClanPosition pos : positions) {
           for (int a = 0; a < Function.values().length; a++)
             if (pos.getFunctionChart()[a] == Authority.MUST_VOTE_ON)
               pos.getFunctionChart()[a] = Authority.CAN_NOT_DO;
           for (final String funcName : funcs) {
             Authority auth = (Authority) CMath.s_valueOf(Function.values(), funcName);
             if (auth != null) pos.getFunctionChart()[auth.ordinal()] = Authority.MUST_VOTE_ON;
           }
         }
         break;
       }
     case NUMRABLE:
       clanAbilityMap = null;
       if (CMath.s_int(val) == 0) {
         clanAbilityNames = null;
         clanAbilityProficiencies = null;
         clanAbilityQuals = null;
         clanAbilityLevels = null;
       } else {
         clanAbilityNames = new String[CMath.s_int(val)];
         clanAbilityProficiencies = new int[CMath.s_int(val)];
         clanAbilityQuals = new boolean[CMath.s_int(val)];
         clanAbilityLevels = new int[CMath.s_int(val)];
       }
       break;
     case GETRABLE:
       {
         if (clanAbilityNames == null) clanAbilityNames = new String[num + 1];
         clanAbilityNames[num] = val;
         break;
       }
     case GETRABLEPROF:
       {
         if (clanAbilityProficiencies == null) clanAbilityProficiencies = new int[num + 1];
         clanAbilityProficiencies[num] = CMath.s_parseIntExpression(val);
         break;
       }
     case GETRABLEQUAL:
       {
         if (clanAbilityQuals == null) clanAbilityQuals = new boolean[num + 1];
         clanAbilityQuals[num] = CMath.s_bool(val);
         break;
       }
     case GETRABLELVL:
       {
         if (clanAbilityLevels == null) clanAbilityLevels = new int[num + 1];
         clanAbilityLevels[num] = CMath.s_parseIntExpression(val);
         break;
       }
     case NUMREFF:
       clanEffectMap = null;
       if (CMath.s_int(val) == 0) {
         clanEffectNames = null;
         clanEffectParms = null;
         clanEffectLevels = null;
       } else {
         clanEffectNames = new String[CMath.s_int(val)];
         clanEffectParms = new String[CMath.s_int(val)];
         clanEffectLevels = new int[CMath.s_int(val)];
       }
       break;
     case GETREFF:
       {
         if (clanEffectNames == null) clanEffectNames = new String[num + 1];
         clanEffectNames[num] = val;
         break;
       }
     case GETREFFPARM:
       {
         if (clanEffectParms == null) clanEffectParms = new String[num + 1];
         clanEffectParms[num] = val;
         break;
       }
     case GETREFFLVL:
       {
         if (clanEffectLevels == null) clanEffectLevels = new int[num + 1];
         clanEffectLevels[num] = CMath.s_int(val);
         break;
       }
     default:
       Log.errOut("Clan", "setStat:Unhandled:" + stat.toString());
       break;
   }
 }
/*
Copyright 2012 Ben Cherrington

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class DefaultClanGovernment implements ClanGovernment {
  public String ID() {
    return "DefaultClanGovernment";
  }

  /** If this is a default government type, this is its ID, otherwise -1 */
  public int ID;
  /** The name of this government type, which is its identifier when ID above is -1 */
  public String name;
  /** The role automatically assigned to those who apply successfully */
  public int autoRole;
  /** The role automatically assigned to those who are accepted */
  public int acceptPos;
  /** A short description of this government type for players */
  public String shortDesc;
  /** A long description of this government type for players */
  public String longDesc;
  /** Zapper mask for requirements to even apply */
  public String requiredMaskStr;
  /** Whether this clan type is shown on the list */
  public boolean isPublic;
  /** Whether mambers must all be in the same family */
  public boolean isFamilyOnly;
  /** The number of minimum members for the clan to survive -- overrides marblemud.ini */
  public Integer overrideMinMembers;
  /** Whether conquest is enabled for this clan */
  public boolean conquestEnabled;
  /** Whether clan items increase loyalty in conquered areas for this clan type */
  public boolean conquestItemLoyalty;
  /** Whether loyalty and conquest are determined by what deity the mobs are */
  public boolean conquestByWorship;
  /** maximum number of mud days a vote will go on for */
  public int maxVoteDays;
  /** minimum % of voters who must have voted for a vote to be valid if time expires */
  public int voteQuorumPct;
  /** uncompiled level xp calculation formula */
  public String xpCalculationFormulaStr;
  /** Whether this is the default government */
  public boolean isDefault = false;
  /** The list of ClanPosition objects for each holdable position in this government */
  public ClanPosition[] positions;
  /** Whether an unfilled topRole is automatically filled by those who meet its innermask */
  public Clan.AutoPromoteFlag autoPromoteBy;

  // derived variable
  public static final List<Ability> empty = new ReadOnlyList<Ability>(new Vector<Ability>());
  public static final String DEFAULT_XP_FORMULA = "(500 * @x1) + (1000 * @x1 * @x1 * @x1)";
  public LinkedList<CMath.CompiledOperation> xpCalculationFormula =
      CMath.compileMathExpression(DEFAULT_XP_FORMULA);

  // derived and internal vars
  protected Map<Integer, List<Ability>> clanAbilityMap = null;
  protected Map<Integer, List<Ability>> clanEffectMap = null;
  protected String[] clanEffectNames = null;
  protected int[] clanEffectLevels = null;
  protected String[] clanEffectParms = null;
  protected String[] clanAbilityNames = null;
  protected int[] clanAbilityLevels = null;
  protected int[] clanAbilityProficiencies = null;
  protected boolean[] clanAbilityQuals = null;

  /** return a new instance of the object */
  public CMObject newInstance() {
    try {
      return (CMObject) getClass().newInstance();
    } catch (Exception e) {
      return new DefaultClanGovernment();
    }
  }

  public void initializeClass() {}

  public int compareTo(CMObject o) {
    return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));
  }

  public CMObject copyOf() {
    try {
      return (ClanGovernment) this.clone();
    } catch (CloneNotSupportedException e) {
      return new DefaultClanGovernment();
    }
  }

  public int getID() {
    return ID;
  }

  public void setID(int iD) {
    ID = iD;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAutoRole() {
    return autoRole;
  }

  public void setAutoRole(int autoRole) {
    this.autoRole = autoRole;
  }

  public int getAcceptPos() {
    return acceptPos;
  }

  public void setAcceptPos(int acceptPos) {
    this.acceptPos = acceptPos;
  }

  public String getShortDesc() {
    return shortDesc;
  }

  public void setShortDesc(String shortDesc) {
    this.shortDesc = shortDesc;
  }

  public String getLongDesc() {
    return longDesc;
  }

  public void setLongDesc(String longDesc) {
    this.longDesc = longDesc;
    this.helpStr = null;
  }

  public String getRequiredMaskStr() {
    return requiredMaskStr;
  }

  public void setRequiredMaskStr(String requiredMaskStr) {
    this.requiredMaskStr = requiredMaskStr;
  }

  public boolean isPublic() {
    return isPublic;
  }

  public void setPublic(boolean isPublic) {
    this.isPublic = isPublic;
  }

  public boolean isFamilyOnly() {
    return isFamilyOnly;
  }

  public void setFamilyOnly(boolean isFamilyOnly) {
    this.isFamilyOnly = isFamilyOnly;
  }

  public Integer getOverrideMinMembers() {
    return overrideMinMembers;
  }

  public void setOverrideMinMembers(Integer overrideMinMembers) {
    this.overrideMinMembers = overrideMinMembers;
  }

  public boolean isConquestEnabled() {
    return conquestEnabled;
  }

  public void setConquestEnabled(boolean conquestEnabled) {
    this.conquestEnabled = conquestEnabled;
  }

  public boolean isConquestItemLoyalty() {
    return conquestItemLoyalty;
  }

  public void setConquestItemLoyalty(boolean conquestItemLoyalty) {
    this.conquestItemLoyalty = conquestItemLoyalty;
  }

  public boolean isConquestByWorship() {
    return conquestByWorship;
  }

  public void setConquestByWorship(boolean conquestByWorship) {
    this.conquestByWorship = conquestByWorship;
  }

  public int getMaxVoteDays() {
    return maxVoteDays;
  }

  public void setMaxVoteDays(int maxVoteDays) {
    this.maxVoteDays = maxVoteDays;
  }

  public int getVoteQuorumPct() {
    return voteQuorumPct;
  }

  public void setVoteQuorumPct(int voteQuorumPct) {
    this.voteQuorumPct = voteQuorumPct;
  }

  public String getXpCalculationFormulaStr() {
    return xpCalculationFormulaStr == null ? "" : xpCalculationFormulaStr;
  }

  public LinkedList<CMath.CompiledOperation> getXPCalculationFormula() {
    return xpCalculationFormula;
  }

  public void setXpCalculationFormulaStr(String newXpCalculationFormula) {
    if (newXpCalculationFormula == null) newXpCalculationFormula = "";
    xpCalculationFormulaStr = newXpCalculationFormula;
    if (xpCalculationFormulaStr.trim().length() == 0)
      this.xpCalculationFormula = CMath.compileMathExpression(DEFAULT_XP_FORMULA);
    else
      try {
        this.xpCalculationFormula = CMath.compileMathExpression(xpCalculationFormulaStr);
      } catch (Exception e) {
        Log.errOut("DefaultClanGovernment", e.getMessage());
      }
  }

  public boolean isDefault() {
    return isDefault;
  }

  public void setDefault(boolean isDefault) {
    this.isDefault = isDefault;
  }

  public ClanPosition[] getPositions() {
    return positions;
  }

  public void setPositions(ClanPosition[] positions) {
    this.positions = positions;
  }

  public Clan.AutoPromoteFlag getAutoPromoteBy() {
    return autoPromoteBy;
  }

  public void setAutoPromoteBy(Clan.AutoPromoteFlag autoPromoteBy) {
    this.autoPromoteBy = autoPromoteBy;
  }

  public int[] getLevelProgression() {
    return levelProgression;
  }

  public void setLevelProgression(int[] levelProgression) {
    this.levelProgression = levelProgression;
  }

  // the follow are derived, or post-create set options:
  /** The list of xp amounts to progress in level */
  public int[] levelProgression = new int[0];
  /** A save help entry of this government type for players */
  public String helpStr = null;

  public ClanPosition getPosition(String pos) {
    if (pos == null) return null;
    pos = pos.trim();
    if (CMath.isInteger(pos)) {
      int i = CMath.s_int(pos);
      if ((i >= 0) && (i < positions.length)) return positions[i];
    }
    for (ClanPosition P : positions) if (P.getID().equalsIgnoreCase(pos)) return P;
    return null;
  }

  public void delPosition(ClanPosition pos) {
    List<ClanPosition> newPos = new LinkedList<ClanPosition>();
    for (ClanPosition P : positions) if (P != pos) newPos.add(P);
    positions = newPos.toArray(new ClanPosition[0]);
  }

  public ClanPosition addPosition() {
    Authority[] pows = new Authority[Function.values().length];
    for (int i = 0; i < pows.length; i++) pows[i] = Authority.CAN_NOT_DO;
    Set<Integer> roles = new HashSet<Integer>();
    int highestRank = 0;
    for (ClanPosition pos : positions) {
      roles.add(Integer.valueOf(pos.getRoleID()));
      if (highestRank < pos.getRank()) highestRank = pos.getRank();
    }
    if (positions.length > 0)
      for (int i = 0; i < pows.length; i++) pows[i] = positions[0].getFunctionChart()[i];
    positions = Arrays.copyOf(positions, positions.length + 1);
    ClanPosition P = (ClanPosition) CMClass.getCommon("DefaultClanPosition");
    P.setID(positions.length + "" + Math.random());
    P.setRoleID(0);
    P.setRank(highestRank);
    P.setName("Unnamed");
    P.setPluralName("Unnameds");
    P.setMax(Integer.MAX_VALUE);
    P.setInnerMaskStr("");
    P.setFunctionChart(pows);
    P.setPublic(true);
    positions[positions.length - 1] = P;
    for (int i = 0; i < positions.length; i++)
      if (!roles.contains(Integer.valueOf(i))) {
        P.setRoleID(i);
        break;
      }
    return P;
  }

  private static enum GOVT_STAT_CODES {
    NAME,
    AUTOROLE,
    ACCEPTPOS,
    SHORTDESC,
    REQUIREDMASK,
    ISPUBLIC,
    ISFAMILYONLY,
    OVERRIDEMINMEMBERS,
    CONQUESTENABLED,
    CONQUESTITEMLOYALTY,
    CONQUESTDEITYBASIS,
    MAXVOTEDAYS,
    VOTEQUORUMPCT,
    AUTOPROMOTEBY,
    VOTEFUNCS,
    LONGDESC,
    XPLEVELFORMULA,
    NUMRABLE,
    GETRABLE,
    GETRABLEPROF,
    GETRABLEQUAL,
    GETRABLELVL,
    NUMREFF,
    GETREFF,
    GETREFFPARM,
    GETREFFLVL,
  }

  public String[] getStatCodes() {
    return CMParms.toStringArray(GOVT_STAT_CODES.values());
  }

  public int getSaveStatIndex() {
    return GOVT_STAT_CODES.values().length;
  }

  private GOVT_STAT_CODES getStatIndex(String code) {
    return (GOVT_STAT_CODES) CMath.s_valueOf(GOVT_STAT_CODES.values(), code);
  }

  public String getStat(String code) {
    int num = 0;
    int numDex = code.length();
    while ((numDex > 0) && (Character.isDigit(code.charAt(numDex - 1)))) numDex--;
    if (numDex < code.length()) {
      num = CMath.s_int(code.substring(numDex));
      code = code.substring(0, numDex);
    }
    final GOVT_STAT_CODES stat = getStatIndex(code);
    if (stat == null) {
      return "";
    }
    switch (stat) {
      case NAME:
        return name;
      case AUTOROLE:
        return (autoRole < 0 || autoRole > positions.length) ? "" : positions[autoRole].getID();
      case ACCEPTPOS:
        return (acceptPos < 0 || acceptPos > positions.length) ? "" : positions[acceptPos].getID();
      case SHORTDESC:
        return shortDesc;
      case LONGDESC:
        return longDesc;
      case XPLEVELFORMULA:
        return xpCalculationFormulaStr == null ? "" : xpCalculationFormulaStr;
      case REQUIREDMASK:
        return requiredMaskStr;
      case ISPUBLIC:
        return Boolean.toString(isPublic);
      case ISFAMILYONLY:
        return Boolean.toString(isFamilyOnly);
      case OVERRIDEMINMEMBERS:
        return overrideMinMembers == null ? "" : overrideMinMembers.toString();
      case CONQUESTENABLED:
        return Boolean.toString(conquestEnabled);
      case CONQUESTITEMLOYALTY:
        return Boolean.toString(conquestItemLoyalty);
      case CONQUESTDEITYBASIS:
        return Boolean.toString(conquestByWorship);
      case MAXVOTEDAYS:
        return Integer.toString(maxVoteDays);
      case VOTEQUORUMPCT:
        return Integer.toString(voteQuorumPct);
      case AUTOPROMOTEBY:
        return autoPromoteBy.toString();
      case VOTEFUNCS:
        {
          final StringBuilder str = new StringBuilder("");
          for (ClanPosition pos : positions) {
            for (int a = 0; a < Function.values().length; a++)
              if (pos.getFunctionChart()[a] == Authority.MUST_VOTE_ON) {
                if (str.length() > 0) str.append(",");
                str.append(Function.values()[a]);
              }
            break;
          }
          return str.toString();
        }
      case NUMRABLE:
        return (clanAbilityNames == null) ? "0" : ("" + clanAbilityNames.length);
      case GETRABLE:
        return (clanAbilityNames == null) ? "" : ("" + clanAbilityNames[num]);
      case GETRABLEPROF:
        return (clanAbilityProficiencies == null) ? "0" : ("" + clanAbilityProficiencies[num]);
      case GETRABLEQUAL:
        return (clanAbilityQuals == null) ? "false" : ("" + clanAbilityQuals[num]);
      case GETRABLELVL:
        return (clanAbilityLevels == null) ? "0" : ("" + clanAbilityLevels[num]);
      case NUMREFF:
        return (clanEffectNames == null) ? "0" : ("" + clanEffectNames.length);
      case GETREFF:
        return (clanEffectNames == null) ? "" : ("" + clanEffectNames[num]);
      case GETREFFPARM:
        return (clanEffectParms == null) ? "0" : ("" + clanEffectParms[num]);
      case GETREFFLVL:
        return (clanEffectLevels == null) ? "0" : ("" + clanEffectLevels[num]);
      default:
        Log.errOut("Clan", "getStat:Unhandled:" + stat.toString());
        break;
    }
    return "";
  }

  public boolean isStat(String code) {
    return getStatIndex(code) != null;
  }

  public void setStat(String code, String val) {
    int num = 0;
    int numDex = code.length();
    while ((numDex > 0) && (Character.isDigit(code.charAt(numDex - 1)))) numDex--;
    if (numDex < code.length()) {
      num = CMath.s_int(code.substring(numDex));
      code = code.substring(0, numDex);
    }
    final GOVT_STAT_CODES stat = getStatIndex(code);
    if (stat == null) {
      return;
    }
    switch (stat) {
      case NAME:
        name = val;
        break;
      case AUTOROLE:
        {
          ClanPosition P = getPosition(val);
          if (P != null) autoRole = P.getRoleID();
          break;
        }
      case ACCEPTPOS:
        {
          ClanPosition P = getPosition(val);
          if (P != null) acceptPos = P.getRoleID();
          break;
        }
      case SHORTDESC:
        shortDesc = val;
        break;
      case LONGDESC:
        longDesc = val;
        break;
      case XPLEVELFORMULA:
        setXpCalculationFormulaStr(val);
        break;
      case REQUIREDMASK:
        requiredMaskStr = val;
        break;
      case ISPUBLIC:
        isPublic = CMath.s_bool(val);
        break;
      case ISFAMILYONLY:
        isFamilyOnly = CMath.s_bool(val);
        break;
      case OVERRIDEMINMEMBERS:
        {
          if (val.length() == 0) overrideMinMembers = null;
          else overrideMinMembers = Integer.valueOf(CMath.s_int(val));
          break;
        }
      case CONQUESTENABLED:
        conquestEnabled = CMath.s_bool(val);
        break;
      case CONQUESTITEMLOYALTY:
        conquestItemLoyalty = CMath.s_bool(val);
        break;
      case CONQUESTDEITYBASIS:
        conquestByWorship = CMath.s_bool(val);
        break;
      case MAXVOTEDAYS:
        maxVoteDays = CMath.s_int(val);
        break;
      case VOTEQUORUMPCT:
        voteQuorumPct = CMath.s_int(val);
        break;
      case AUTOPROMOTEBY:
        {
          Clan.AutoPromoteFlag flag =
              (Clan.AutoPromoteFlag) CMath.s_valueOf(Clan.AutoPromoteFlag.values(), val);
          if (flag != null) autoPromoteBy = flag;
          break;
        }
      case VOTEFUNCS:
        {
          final Vector<String> funcs = CMParms.parseCommas(val.toUpperCase().trim(), true);
          for (ClanPosition pos : positions) {
            for (int a = 0; a < Function.values().length; a++)
              if (pos.getFunctionChart()[a] == Authority.MUST_VOTE_ON)
                pos.getFunctionChart()[a] = Authority.CAN_NOT_DO;
            for (final String funcName : funcs) {
              Authority auth = (Authority) CMath.s_valueOf(Function.values(), funcName);
              if (auth != null) pos.getFunctionChart()[auth.ordinal()] = Authority.MUST_VOTE_ON;
            }
          }
          break;
        }
      case NUMRABLE:
        clanAbilityMap = null;
        if (CMath.s_int(val) == 0) {
          clanAbilityNames = null;
          clanAbilityProficiencies = null;
          clanAbilityQuals = null;
          clanAbilityLevels = null;
        } else {
          clanAbilityNames = new String[CMath.s_int(val)];
          clanAbilityProficiencies = new int[CMath.s_int(val)];
          clanAbilityQuals = new boolean[CMath.s_int(val)];
          clanAbilityLevels = new int[CMath.s_int(val)];
        }
        break;
      case GETRABLE:
        {
          if (clanAbilityNames == null) clanAbilityNames = new String[num + 1];
          clanAbilityNames[num] = val;
          break;
        }
      case GETRABLEPROF:
        {
          if (clanAbilityProficiencies == null) clanAbilityProficiencies = new int[num + 1];
          clanAbilityProficiencies[num] = CMath.s_parseIntExpression(val);
          break;
        }
      case GETRABLEQUAL:
        {
          if (clanAbilityQuals == null) clanAbilityQuals = new boolean[num + 1];
          clanAbilityQuals[num] = CMath.s_bool(val);
          break;
        }
      case GETRABLELVL:
        {
          if (clanAbilityLevels == null) clanAbilityLevels = new int[num + 1];
          clanAbilityLevels[num] = CMath.s_parseIntExpression(val);
          break;
        }
      case NUMREFF:
        clanEffectMap = null;
        if (CMath.s_int(val) == 0) {
          clanEffectNames = null;
          clanEffectParms = null;
          clanEffectLevels = null;
        } else {
          clanEffectNames = new String[CMath.s_int(val)];
          clanEffectParms = new String[CMath.s_int(val)];
          clanEffectLevels = new int[CMath.s_int(val)];
        }
        break;
      case GETREFF:
        {
          if (clanEffectNames == null) clanEffectNames = new String[num + 1];
          clanEffectNames[num] = val;
          break;
        }
      case GETREFFPARM:
        {
          if (clanEffectParms == null) clanEffectParms = new String[num + 1];
          clanEffectParms[num] = val;
          break;
        }
      case GETREFFLVL:
        {
          if (clanEffectLevels == null) clanEffectLevels = new int[num + 1];
          clanEffectLevels[num] = CMath.s_int(val);
          break;
        }
      default:
        Log.errOut("Clan", "setStat:Unhandled:" + stat.toString());
        break;
    }
  }

  public String getHelpStr() {
    if (getLongDesc().length() == 0) return null;
    if (helpStr == null) {
      StringBuilder str = new StringBuilder("\n\rOrganization type: " + getName() + "\n\r\n\r");
      str.append(getLongDesc()).append("\n\r");
      str.append("\n\rAuthority Chart:\n\r\n\r");
      final List<ClanPosition> showablePositions = new Vector<ClanPosition>();
      for (ClanPosition P : getPositions()) {
        boolean showMe = false;
        for (Clan.Authority a : P.getFunctionChart()) if (a == Authority.CAN_DO) showMe = true;
        if (showMe) showablePositions.add(P);
      }
      final List<ClanPosition> sortedPositions = new Vector<ClanPosition>();
      while (sortedPositions.size() < showablePositions.size()) {
        ClanPosition highPos = null;
        for (ClanPosition P : showablePositions)
          if ((!sortedPositions.contains(P))
              && ((highPos == null) || (highPos.getRank() < P.getRank()))) highPos = P;
        sortedPositions.add(highPos);
      }
      final int[] posses = new int[sortedPositions.size()];
      int posTotalLen = 0;
      for (int p = 0; p < sortedPositions.size(); p++) {
        posses[p] = sortedPositions.get(p).getName().length() + 2;
        posTotalLen += posses[p];
      }
      int funcMaxLen = 0;
      int funcTotal = 0;
      String[] functionNames = new String[Clan.Function.values().length];
      for (int f = 0; f < Clan.Function.values().length; f++) {
        Clan.Function func = Clan.Function.values()[f];
        funcTotal += func.name().length() + 1;
        if (func.name().length() > funcMaxLen) funcMaxLen = func.name().length() + 1;
        functionNames[f] = func.name();
      }
      int funcAvg = funcTotal / Clan.Function.values().length;
      int funcMaxAvg = (int) CMath.round((double) funcAvg * 1.3);
      while ((funcMaxLen > funcMaxAvg) && ((funcMaxAvg + posTotalLen) > 78)) funcMaxLen--;
      if (posses.length > 0)
        while ((funcMaxLen + posTotalLen) > 78) {
          int highPos = 0;
          for (int p = 1; p < sortedPositions.size(); p++)
            if (posses[p] > posses[highPos]) highPos = p;
          posTotalLen--;
          posses[highPos]--;
        }

      final int commandColLen = funcMaxLen;
      str.append(CMStrings.padRight("Command", commandColLen - 1)).append("!");
      for (int p = 0; p < posses.length; p++) {
        ClanPosition pos = sortedPositions.get(p);
        String name = CMStrings.capitalizeAndLower(pos.getName().replace('_', ' '));
        str.append(CMStrings.padRight(name, posses[p] - 1));
        if (p < posses.length - 1) str.append("!");
      }
      str.append("\n\r");
      Object lineDraw =
          new Object() {
            private static final String line =
                "----------------------------------------------------------------------------";

            public String toString() {
              StringBuilder s = new StringBuilder("");
              s.append(line.substring(0, commandColLen - 1)).append("+");
              for (int p = 0; p < posses.length; p++) {
                s.append(CMStrings.padRight(line, posses[p] - 1));
                if (p < posses.length - 1) s.append("+");
              }
              return s.toString();
            }
          };
      str.append(lineDraw.toString()).append("\n\r");
      for (Clan.Function func : Clan.Function.values()) {
        String fname = CMStrings.capitalizeAndLower(func.toString().replace('_', ' '));
        str.append(CMStrings.padRight(fname, commandColLen - 1)).append("!");
        for (int p = 0; p < sortedPositions.size(); p++) {
          ClanPosition pos = sortedPositions.get(p);
          Authority auth = pos.getFunctionChart()[func.ordinal()];
          String x = "";
          if (auth == Authority.CAN_DO) x = "X";
          else if (auth == Authority.MUST_VOTE_ON) x = "v";
          str.append(CMStrings.padCenter(x, posses[p] - 1));
          if (p < posses.length - 1) str.append("!");
        }
        str.append("\n\r").append(lineDraw.toString()).append("\n\r");
      }
      /*
      protected String[] 	clanEffectNames			=null;
      protected int[] 	clanEffectLevels		=null;
      protected String[] 	clanEffectParms			=null;
      protected String[] 	clanAbilityNames		=null;
      protected int[] 	clanAbilityLevels		=null;
      protected int[] 	clanAbilityProficiencies=null;
      protected boolean[] clanAbilityQuals		=null;
      */

      if ((clanAbilityLevels != null)
          && (clanEffectLevels != null)
          && (clanAbilityLevels.length > 0)
          && (clanEffectLevels.length > 0)) {
        str.append("\n\rBenefits per Clan Level:\n\r");
        int maxLevel = -1;
        for (int x : clanEffectLevels) if (x > maxLevel) maxLevel = x;
        for (int x : clanAbilityLevels) if (x > maxLevel) maxLevel = x;
        for (int l = 1; l <= maxLevel; l++) {
          final List<String> levelBenefits = new LinkedList<String>();
          for (int x = 0; x < clanEffectLevels.length; x++)
            if (clanEffectLevels[x] == l) {
              final Ability A = CMClass.getAbility(clanEffectNames[x]);
              if (A != null) {
                A.setMiscText(clanEffectParms[x]);
                String desc = A.accountForYourself();
                if ((desc == null) || (desc.length() == 0))
                  desc = "Members gain the following effect: " + A.name();
                levelBenefits.add(desc);
              }
            }
          for (int x = 0; x < clanAbilityLevels.length; x++)
            if (clanAbilityLevels[x] == l) {
              final Ability A = CMClass.getAbility(clanAbilityNames[x]);
              if (A != null) {
                if (clanAbilityQuals[x]) levelBenefits.add("Members qualify for: " + A.name());
                else levelBenefits.add("Members automatically gain: " + A.name());
              }
            }
          for (final String bene : levelBenefits) str.append("Level " + l + ": " + bene + "\n\r");
        }
      }
      helpStr = str.toString();
    }
    return helpStr;
  }

  public List<Ability> getClanLevelAbilities(Integer level) {
    if ((clanAbilityMap == null)
        && (clanAbilityNames != null)
        && (clanAbilityLevels != null)
        && (clanAbilityProficiencies != null)
        && (clanAbilityQuals != null)) {
      CMLib.ableMapper().delCharMappings(ID()); // necessary for a "clean start"
      clanAbilityMap = new Hashtable<Integer, List<Ability>>();
      for (int i = 0; i < clanAbilityNames.length; i++) {
        CMLib.ableMapper()
            .addDynaAbilityMapping(
                ID(),
                clanAbilityLevels[i],
                clanAbilityNames[i],
                clanAbilityProficiencies[i],
                "",
                !clanAbilityQuals[i],
                false);
      }
    }
    if (clanAbilityMap == null) return empty;
    if (clanAbilityMap.containsKey(level)) return clanAbilityMap.get(level);
    List<AbilityMapper.AbilityMapping> V =
        CMLib.ableMapper().getUpToLevelListings(ID(), level.intValue(), true, true);
    CMObjUniqSortSVec<Ability> finalV = new CMObjUniqSortSVec<Ability>();
    for (AbilityMapper.AbilityMapping able : V) {
      Ability A = CMClass.getAbility(able.abilityID);
      if (A != null) {
        A.setProficiency(CMLib.ableMapper().getDefaultProficiency(ID(), false, A.ID()));
        A.setSavable(false);
        A.setMiscText(CMLib.ableMapper().getDefaultParm(ID(), false, A.ID()));
        finalV.add(A);
      }
    }
    finalV.trimToSize();
    clanAbilityMap.put(level, finalV);
    return finalV;
  }

  public List<Ability> getClanLevelEffectsList(final MOB mob, final Integer level) {
    if (clanEffectNames == null) return empty;

    if ((clanEffectMap == null)
        && (clanEffectNames != null)
        && (clanEffectLevels != null)
        && (clanEffectParms != null)) clanEffectMap = new Hashtable<Integer, List<Ability>>();

    if (clanEffectMap == null) return empty;

    if (clanEffectMap.containsKey(level)) return clanEffectMap.get(level);
    final CMObjUniqSortSVec<Ability> finalV = new CMObjUniqSortSVec<Ability>();
    for (int v = 0; v < clanEffectLevels.length; v++) {
      if ((clanEffectLevels[v] <= level.intValue())
          && (clanEffectNames.length > v)
          && (clanEffectParms.length > v)) {
        Ability A = CMClass.getAbility(clanEffectNames[v]);
        if (A != null) {
          // mob was set to null here to make the cache map actually relevant .. see caching below
          A.setProficiency(CMLib.ableMapper().getMaxProficiency((MOB) null, true, A.ID()));
          A.setMiscText(clanEffectParms[v]);
          A.makeNonUninvokable();
          A.setSavable(false); // must go AFTER the ablve
          finalV.add(A);
        }
      }
    }
    finalV.trimToSize();
    clanEffectMap.put(level, finalV);
    return finalV;
  }

  public int getClanLevelEffectsSize(final MOB mob, final Integer level) {
    return getClanLevelEffectsList(mob, level).size();
  }

  public ChameleonList<Ability> getEmptyClanLevelEffects(final MOB mob) {
    return new ChameleonList<Ability>(
        empty,
        new ChameleonList.Signaler<Ability>(empty) {
          public boolean isDeprecated() {
            return (mob != null) && (mob.getMyClan()) != null;
          }

          public void rebuild(final ChameleonList<Ability> me) {
            if (mob == null) return;
            final Clan C = mob.getMyClan();
            if (C != null)
              me.changeMeInto(
                  C.getGovernment().getClanLevelEffects(mob, Integer.valueOf(C.getClanLevel())));
          }
        });
  }

  public ChameleonList<Ability> getClanLevelEffects(final MOB mob, final Integer level) {
    if (level == null) return getEmptyClanLevelEffects(mob);
    final DefaultClanGovernment myGovt = this;
    final List<Ability> myList = getClanLevelEffectsList(mob, level);
    final List<Ability> finalV = new Vector<Ability>(myList.size());
    for (final Ability A : myList) {
      Ability finalA = (Ability) A.copyOf();
      finalA.makeNonUninvokable();
      finalA.setSavable(false); // must come AFTER the above
      finalA.setAffectedOne(mob);
      finalV.add(finalA);
    }
    final ChameleonList<Ability> finalFinalV;
    if (mob == null) {
      finalFinalV =
          new ChameleonList<Ability>(
              finalV,
              new ChameleonList.Signaler<Ability>(myList) {
                public boolean isDeprecated() {
                  return false;
                }

                public void rebuild(final ChameleonList<Ability> me) {}
              });
    } else {
      finalFinalV =
          new ChameleonList<Ability>(
              finalV,
              new ChameleonList.Signaler<Ability>(myList) {
                public boolean isDeprecated() {
                  if ((mob == null) || (mob.amDestroyed())) return true;
                  final Clan C = mob.getMyClan();
                  if (C == null) return true;
                  if ((C.getGovernment() != myGovt)
                      || (getClanLevelEffectsList(mob, Integer.valueOf(C.getClanLevel()))
                          != oldReferenceListRef.get())) return true;
                  return false;
                }

                public void rebuild(final ChameleonList<Ability> me) {

                  final Clan C = (mob != null) ? mob.getMyClan() : null;
                  if ((mob == null) || (mob.amDestroyed()) || (C == null))
                    me.changeMeInto(getEmptyClanLevelEffects(mob));
                  else
                    me.changeMeInto(
                        C.getGovernment()
                            .getClanLevelEffects(mob, Integer.valueOf(C.getClanLevel())));
                }
              });
    }
    return finalFinalV;
  }
}
 public String getStat(String code) {
   int num = 0;
   int numDex = code.length();
   while ((numDex > 0) && (Character.isDigit(code.charAt(numDex - 1)))) numDex--;
   if (numDex < code.length()) {
     num = CMath.s_int(code.substring(numDex));
     code = code.substring(0, numDex);
   }
   final GOVT_STAT_CODES stat = getStatIndex(code);
   if (stat == null) {
     return "";
   }
   switch (stat) {
     case NAME:
       return name;
     case AUTOROLE:
       return (autoRole < 0 || autoRole > positions.length) ? "" : positions[autoRole].getID();
     case ACCEPTPOS:
       return (acceptPos < 0 || acceptPos > positions.length) ? "" : positions[acceptPos].getID();
     case SHORTDESC:
       return shortDesc;
     case LONGDESC:
       return longDesc;
     case XPLEVELFORMULA:
       return xpCalculationFormulaStr == null ? "" : xpCalculationFormulaStr;
     case REQUIREDMASK:
       return requiredMaskStr;
     case ISPUBLIC:
       return Boolean.toString(isPublic);
     case ISFAMILYONLY:
       return Boolean.toString(isFamilyOnly);
     case OVERRIDEMINMEMBERS:
       return overrideMinMembers == null ? "" : overrideMinMembers.toString();
     case CONQUESTENABLED:
       return Boolean.toString(conquestEnabled);
     case CONQUESTITEMLOYALTY:
       return Boolean.toString(conquestItemLoyalty);
     case CONQUESTDEITYBASIS:
       return Boolean.toString(conquestByWorship);
     case MAXVOTEDAYS:
       return Integer.toString(maxVoteDays);
     case VOTEQUORUMPCT:
       return Integer.toString(voteQuorumPct);
     case AUTOPROMOTEBY:
       return autoPromoteBy.toString();
     case VOTEFUNCS:
       {
         final StringBuilder str = new StringBuilder("");
         for (ClanPosition pos : positions) {
           for (int a = 0; a < Function.values().length; a++)
             if (pos.getFunctionChart()[a] == Authority.MUST_VOTE_ON) {
               if (str.length() > 0) str.append(",");
               str.append(Function.values()[a]);
             }
           break;
         }
         return str.toString();
       }
     case NUMRABLE:
       return (clanAbilityNames == null) ? "0" : ("" + clanAbilityNames.length);
     case GETRABLE:
       return (clanAbilityNames == null) ? "" : ("" + clanAbilityNames[num]);
     case GETRABLEPROF:
       return (clanAbilityProficiencies == null) ? "0" : ("" + clanAbilityProficiencies[num]);
     case GETRABLEQUAL:
       return (clanAbilityQuals == null) ? "false" : ("" + clanAbilityQuals[num]);
     case GETRABLELVL:
       return (clanAbilityLevels == null) ? "0" : ("" + clanAbilityLevels[num]);
     case NUMREFF:
       return (clanEffectNames == null) ? "0" : ("" + clanEffectNames.length);
     case GETREFF:
       return (clanEffectNames == null) ? "" : ("" + clanEffectNames[num]);
     case GETREFFPARM:
       return (clanEffectParms == null) ? "0" : ("" + clanEffectParms[num]);
     case GETREFFLVL:
       return (clanEffectLevels == null) ? "0" : ("" + clanEffectLevels[num]);
     default:
       Log.errOut("Clan", "getStat:Unhandled:" + stat.toString());
       break;
   }
   return "";
 }
Exemple #15
0
 public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException {
   commands.removeElementAt(0);
   MOB leader = CMLib.combat().getFollowedLeader(mob);
   List<MOB>[] done = CMLib.combat().getFormation(mob);
   if (commands.size() == 0) {
     StringBuffer str = new StringBuffer("");
     for (int i = 0; i < done.length; i++)
       if (done[i] != null) {
         if (i == 0) str.append("^xfront  - ^.^?");
         else str.append("^xrow +" + i + " - ^.^?");
         for (int i2 = 0; i2 < done[i].size(); i2++)
           str.append(((i2 > 0) ? ", " : "") + ((MOB) done[i].get(i2)).name());
         str.append("\n\r");
       }
     mob.session().colorOnlyPrintln(str.toString());
   } else if (commands.size() == 1) mob.tell("Put whom in what row?");
   else if (mob.numFollowers() == 0) mob.tell("Noone is following you!");
   else {
     String row = (String) commands.lastElement();
     if ("FRONT".startsWith(row.toUpperCase())) row = "0";
     commands.removeElementAt(commands.size() - 1);
     String name = CMParms.combine(commands, 0);
     MOB who = null;
     if (CMLib.english().containsString(mob.name(), name)
         || CMLib.english().containsString(mob.Name(), name)) {
       mob.tell("You can not move your own position.  You are always the leader of your party.");
       return false;
     }
     for (int f = 0; f < mob.numFollowers(); f++) {
       MOB M = mob.fetchFollower(f);
       if (M == null) continue;
       if (CMLib.english().containsString(M.name(), name)
           || CMLib.english().containsString(M.Name(), name)) {
         who = M;
         break;
       }
     }
     if (who == null) {
       mob.tell("There is noone following you called " + name + ".");
       return false;
     }
     if ((!CMath.isNumber(row)) || (CMath.s_int(row) < 0))
       mob.tell(
           "'"
               + row
               + "' is not a valid row in which to put "
               + who.name()
               + ".  Try number greater than 0.");
     else {
       int leaderRow = -1;
       for (int f = 0; f < done.length; f++)
         if ((done[f] != null) && (done[f].contains(leader))) {
           leaderRow = f;
           break;
         }
       if (leaderRow < 0) mob.tell("You do not exist.");
       else if (CMath.s_int(row) < leaderRow)
         mob.tell(
             "You can not place "
                 + who.name()
                 + " behind your own position, which is "
                 + leaderRow
                 + ".");
       else {
         mob.addFollower(who, CMath.s_int(row) - leaderRow);
         mob.tell("You have positioned " + who.name() + " to row " + CMath.s_int(row));
       }
     }
   }
   return false;
 }
Exemple #16
0
  public boolean tick(Tickable ticking, int tickID) {
    int realLastWeather = super.lastWeather;
    if (!super.tick(ticking, tickID)) return false;
    Area A = CMLib.map().areaLocation(ticking);
    if (A == null) return false;
    Climate C = A.getClimateObj();
    if (C == null) return false;
    lastWeather = realLastWeather;

    // handle freeze overs
    if ((coldWeather(lastWeather))
        && (coldWeather(C.weatherType(null)))
        && (lastWeather != C.weatherType(null))
        && (A.getTimeObj().getSeasonCode() == TimeClock.SEASON_WINTER)
        && (CMLib.dice().rollPercentage() < freezeOverChance)) {
      if (ticking instanceof Room) {
        Room R = (Room) ticking;
        if ((R.domainType() == Room.DOMAIN_OUTDOORS_WATERSURFACE)
            && (CMLib.dice().rollPercentage() < freezeOverChance)
            && (R instanceof Drink)
            && (((Drink) R).liquidType() == RawMaterial.RESOURCE_FRESHWATER)) {
          Ability A2 = CMClass.getAbility("Spell_IceSheet");
          if (A2 != null) {
            MOB mob = CMLib.map().getFactoryMOB(R);
            A2.invoke(mob, R, true, 0);
            mob.destroy();
          }
        }
      } else
        for (Enumeration<Room> e = A.getProperMap(); e.hasMoreElements(); ) {
          Room R = (Room) e.nextElement();
          if ((R.domainType() == Room.DOMAIN_OUTDOORS_WATERSURFACE)
              && (CMLib.dice().rollPercentage() < freezeOverChance)) {
            Ability A2 = CMClass.getAbility("Spell_IceSheet");
            if (A2 != null) {
              MOB mob = CMLib.map().getFactoryMOB(R);
              A2.invoke(mob, R, true, 0);
              mob.destroy();
            }
          }
        }
    }
    if ((botherDown--) == 1) {
      resetBotherTicks();
      switch (C.weatherType(null)) {
        case Climate.WEATHER_BLIZZARD:
        case Climate.WEATHER_SLEET:
        case Climate.WEATHER_SNOW:
        case Climate.WEATHER_HAIL:
        case Climate.WEATHER_THUNDERSTORM:
        case Climate.WEATHER_RAIN:
          for (Enumeration<Room> r = A.getProperMap(); r.hasMoreElements(); ) {
            Room R = (Room) r.nextElement();
            if (CMLib.map().hasASky(R))
              for (int i = 0; i < R.numInhabitants(); i++) {
                MOB mob = R.fetchInhabitant(i);
                if ((mob != null)
                    && (!mob.isMonster())
                    && (CMLib.flags().aliveAwakeMobile(mob, true))
                    && (CMath.bset(mob.getBitmap(), MOB.ATT_AUTOWEATHER)))
                  mob.tell(C.getWeatherDescription(A));
              }
          }
          break;
      }
    }
    if ((diseaseDown--) == 1) {
      resetDiseaseTicks();
      int coldChance = 0;
      int fluChance = 0;
      int frostBiteChance = 0;
      int heatExhaustionChance = 0;
      switch (C.weatherType(null)) {
        case Climate.WEATHER_BLIZZARD:
        case Climate.WEATHER_SLEET:
        case Climate.WEATHER_SNOW:
          coldChance = 99;
          fluChance = 25;
          frostBiteChance = 15;
          break;
        case Climate.WEATHER_HAIL:
          coldChance = 50;
          frostBiteChance = 10;
          break;
        case Climate.WEATHER_THUNDERSTORM:
        case Climate.WEATHER_RAIN:
          coldChance = 25;
          break;
        case Climate.WEATHER_WINTER_COLD:
          coldChance = 75;
          fluChance = 10;
          frostBiteChance = 5;
          break;
        case Climate.WEATHER_HEAT_WAVE:
          heatExhaustionChance = 15;
          break;
        case Climate.WEATHER_DROUGHT:
          heatExhaustionChance = 20;
          break;
      }

      for (Session S : CMLib.sessions().localOnlineIterable()) {
        if ((S.mob() == null)
            || (S.mob().location() == null)
            || (S.mob().location().getArea() != A)
            || (S.mob().isMonster())) continue;

        MOB M = S.mob();
        Room R = M.location();

        if ((R.domainConditions() & Room.CONDITION_COLD) > 0) {
          if (coldChance > 0) coldChance += 10;
          if (coldChance > 0) fluChance += 5; // yes, cold is related this way to flu
          if (frostBiteChance > 0)
            frostBiteChance = frostBiteChance + (int) Math.round(CMath.mul(frostBiteChance, 0.5));
        }
        if ((R.domainConditions() & Room.CONDITION_HOT) > 0) {
          if (heatExhaustionChance > 0) heatExhaustionChance += 10;
        }
        if ((R.domainConditions() & Room.CONDITION_WET) > 0) {
          if (coldChance > 0) coldChance += 5;
          if (heatExhaustionChance > 5) heatExhaustionChance -= 5;
          if (frostBiteChance > 0)
            frostBiteChance = frostBiteChance + (int) Math.round(CMath.mul(frostBiteChance, 0.25));
        }
        int save =
            (M.charStats().getSave(CharStats.STAT_SAVE_COLD)
                    + M.charStats().getSave(CharStats.STAT_SAVE_WATER))
                / 2;
        if ((CMLib.dice().rollPercentage() < (coldChance - save))
            && ((C.weatherType(M.location()) != Climate.WEATHER_CLEAR))) {
          long coveredPlaces = 0;
          for (int l = 0; l < ALL_COVERED_SPOTS.length; l++)
            if (M.getWearPositions(ALL_COVERED_SPOTS[l]) == 0)
              coveredPlaces = coveredPlaces | ALL_COVERED_SPOTS[l];
          Item I = null;
          for (int i = 0; i < M.numItems(); i++) {
            I = M.getItem(i);
            if ((I == null) || (I.amWearingAt(Wearable.IN_INVENTORY))) continue;
            if (I.amWearingAt(Wearable.WORN_ABOUT_BODY))
              coveredPlaces = coveredPlaces | Wearable.WORN_TORSO | Wearable.WORN_LEGS;
            for (int l = 0; l < ALL_COVERED_SPOTS.length; l++)
              if (I.amWearingAt(ALL_COVERED_SPOTS[l]))
                coveredPlaces = coveredPlaces | ALL_COVERED_SPOTS[l];
          }
          if ((coveredPlaces != ALL_COVERED_CODE)
              && (!CMSecurity.isDisabled(CMSecurity.DisFlag.AUTODISEASE))) {
            Ability COLD = CMClass.getAbility("Disease_Cold");
            if (CMLib.dice().rollPercentage()
                < (fluChance
                    + (((M.location().domainConditions() & Room.CONDITION_WET) > 0) ? 10 : 0)))
              COLD = CMClass.getAbility("Disease_Flu");
            if ((COLD != null) && (M.fetchEffect(COLD.ID()) == null)) COLD.invoke(M, M, true, 0);
          }
        }
        if ((CMLib.dice().rollPercentage() < (frostBiteChance - save))
            && ((C.weatherType(M.location()) != Climate.WEATHER_CLEAR))) {
          long unfrostedPlaces = 0;
          for (int l = 0; l < ALL_FROST_SPOTS.length; l++)
            if (M.getWearPositions(ALL_FROST_SPOTS[l]) == 0)
              unfrostedPlaces = unfrostedPlaces | ALL_FROST_SPOTS[l];
          Item I = null;
          for (int i = 0; i < M.numItems(); i++) {
            I = M.getItem(i);
            if ((I == null) || (I.amWearingAt(Wearable.IN_INVENTORY))) continue;
            for (int l = 0; l < ALL_FROST_SPOTS.length; l++)
              if (I.amWearingAt(ALL_FROST_SPOTS[l]))
                unfrostedPlaces = unfrostedPlaces | ALL_FROST_SPOTS[l];
          }
          if ((unfrostedPlaces != ALL_FROST_CODE)
              && (!CMSecurity.isDisabled(CMSecurity.DisFlag.AUTODISEASE))) {
            Ability COLD = CMClass.getAbility("Disease_FrostBite");
            if ((COLD != null) && (M.fetchEffect(COLD.ID()) == null)) COLD.invoke(M, M, true, 0);
          }
        }
        if ((heatExhaustionChance > 0)
            && (CMLib.dice().rollPercentage()
                < (heatExhaustionChance - M.charStats().getSave(CharStats.STAT_SAVE_FIRE)))
            && (C.weatherType(M.location()) != Climate.WEATHER_CLEAR)
            && (!CMSecurity.isDisabled(CMSecurity.DisFlag.AUTODISEASE))) {
          Ability COLD = CMClass.getAbility("Disease_HeatExhaustion");
          if ((COLD != null) && (M.fetchEffect(COLD.ID()) == null)) COLD.invoke(M, M, true, 0);
        }
      }
    }
    if ((rumbleDown--) == 1) {
      resetRumbleTicks();
      for (Session S : CMLib.sessions().localOnlineIterable()) {
        if ((S.mob() == null)
            || (S.mob().location() == null)
            || (S.mob().location().getArea() != A)
            || (S.mob().isMonster())
            || (!CMath.bset(S.mob().getBitmap(), MOB.ATT_AUTOWEATHER))) continue;
        Room R = S.mob().location();
        if (R != null) {
          switch (C.weatherType(null)) {
            case Climate.WEATHER_THUNDERSTORM:
              {
                if (C.weatherType(R) != Climate.WEATHER_THUNDERSTORM) {
                  if ((R.domainType() & Room.INDOORS) > 0) {
                    if ((R.getArea() != null)
                        && CMath.div(
                                R.getArea().getAreaIStats()[Area.Stats.INDOOR_ROOMS.ordinal()],
                                R.getArea().properSize())
                            < 0.90)
                      S.mob()
                          .tell(
                              "^JA thunderous rumble and CRACK of lightning can be heard outside.^?"
                                  + CMProps.msp("thunder.wav", 40));
                  } else
                    S.mob()
                        .tell(
                            "^JA thunderous rumble and CRACK of lightning can be heard.^?"
                                + CMProps.msp("thunder.wav", 40));
                } else if (R.getArea().getTimeObj().getTODCode() == TimeClock.TIME_DAY)
                  S.mob()
                      .tell(
                          "^JA thunderous rumble and CRACK of lightning can be heard as the pounding rain soaks you.^?"
                              + CMProps.msp("thunderandrain.wav", 40));
                else
                  S.mob()
                      .tell(
                          "^JA bolt of lightning streaks across the sky as the pounding rain soaks you!^?"
                              + CMProps.msp("thunderandrain.wav", 40));
                break;
              }
            case Climate.WEATHER_BLIZZARD:
              if (C.weatherType(R) == Climate.WEATHER_BLIZZARD)
                S.mob()
                    .tell(
                        "^JSwirling clouds of snow buffet you.^?"
                            + CMProps.msp("blizzard.wav", 40));
              break;
            case Climate.WEATHER_SNOW:
              if (C.weatherType(R) == Climate.WEATHER_SNOW)
                S.mob().tell("^JSnowflakes fall lightly on you.^?");
              break;
            case Climate.WEATHER_DUSTSTORM:
              if (C.weatherType(R) == Climate.WEATHER_DUSTSTORM)
                S.mob()
                    .tell(
                        "^JSwirling clouds of dust assault you.^?" + CMProps.msp("windy.wav", 40));
              break;
            case Climate.WEATHER_HAIL:
              if (C.weatherType(R) == Climate.WEATHER_HAIL)
                S.mob()
                    .tell(
                        "^JYou are being pelleted by hail! Ouch!^?" + CMProps.msp("hail.wav", 40));
              break;
            case Climate.WEATHER_RAIN:
              if (C.weatherType(R) == Climate.WEATHER_RAIN)
                S.mob().tell("^JThe rain is soaking you!^?" + CMProps.msp("rainlong.wav", 40));
              break;
            case Climate.WEATHER_SLEET:
              if (C.weatherType(R) == Climate.WEATHER_SLEET)
                S.mob()
                    .tell(
                        "^JCold and blistering sleet is soaking you numb!^?"
                            + CMProps.msp("rain.wav", 40));
              break;
            case Climate.WEATHER_WINDY:
              if (C.weatherType(R) == Climate.WEATHER_WINDY)
                S.mob().tell("^JThe wind gusts around you.^?" + CMProps.msp("wind.wav", 40));
              break;
          }
        }
      }
    }
    if ((lightningDown--) == 1) {
      resetLightningTicks();
      if (C.weatherType(null) == Climate.WEATHER_THUNDERSTORM) {
        boolean playerAround = false;
        for (Session S : CMLib.sessions().localOnlineIterable()) {
          if ((S.mob() == null)
              || (S.mob().location() == null)
              || (S.mob().location().getArea() != A)
              || (S.mob().isMonster())
              || (C.weatherType(S.mob().location()) != Climate.WEATHER_THUNDERSTORM)) continue;
          playerAround = true;
        }
        if (playerAround) {
          Room R = A.getRandomProperRoom();
          MOB M = R.fetchRandomInhabitant();
          if (M != null) {
            Ability A2 = CMClass.getAbility("Chant_SummonLightning");
            if (A2 != null) {
              A2.setMiscText("RENDER MUNDANE");
              A2.invoke(M, M, true, M.phyStats().level());
            }
          } else R = null;
          Room R2 = null;
          for (Enumeration<Room> e = A.getProperMap(); e.hasMoreElements(); ) {
            R2 = (Room) e.nextElement();
            if ((R2 != R) && (R2.numInhabitants() > 0))
              if ((A.getTimeObj().getTODCode() == TimeClock.TIME_DAY)
                  || (C.weatherType(R2) != Climate.WEATHER_THUNDERSTORM)) {
                if ((R2.domainType() & Room.INDOORS) > 0)
                  R2.showHappens(
                      CMMsg.MSG_OK_ACTION,
                      "^JA thunderous rumble and crack of lightning can be heard outside.^?"
                          + CMProps.msp("thunder2.wav", 40));
                else
                  R2.showHappens(
                      CMMsg.MSG_OK_ACTION,
                      "^JA thunderous rumble and crack of lightning can be heard.^?"
                          + CMProps.msp("thunder2.wav", 40));
              } else
                R2.showHappens(
                    CMMsg.MSG_OK_ACTION,
                    "^JYou hear a thunderous rumble as a bolt of lightning streaks across the sky!^?"
                        + CMProps.msp("thunder3.wav", 40));
          }
        }
      }
    }
    if ((tornadoDown--) == 1) {
      resetTornadoTicks();
      if ((C.weatherType(null) == Climate.WEATHER_THUNDERSTORM)
          || (C.weatherType(null) == Climate.WEATHER_WINDY)) {
        boolean playerAround = false;
        for (Session S : CMLib.sessions().localOnlineIterable()) {
          if ((S.mob() == null)
              || (S.mob().location() == null)
              || (S.mob().location().getArea() != A)
              || (S.mob().isMonster())
              || (C.weatherType(S.mob().location()) != Climate.WEATHER_THUNDERSTORM)) continue;
          playerAround = true;
        }
        if (playerAround) {
          Room R = A.getRandomProperRoom();
          MOB M = R.fetchRandomInhabitant();
          if (M != null) {
            Ability A2 = CMClass.getAbility("Chant_SummonTornado");
            if (A2 != null) {
              A2.setMiscText("RENDER MUNDANE");
              MOB mob = CMLib.map().getFactoryMOB(R);
              A2.invoke(mob, null, true, 0);
              mob.destroy();
            }
          } else R = null;
          Room R2 = null;
          for (Enumeration<Room> e = A.getProperMap(); e.hasMoreElements(); ) {
            R2 = (Room) e.nextElement();
            if ((R2 != R) && (R2.numInhabitants() > 0))
              if ((A.getTimeObj().getTODCode() == TimeClock.TIME_DAY)
                  || (C.weatherType(R2) != Climate.WEATHER_THUNDERSTORM)) {
                if ((R2.domainType() & Room.INDOORS) > 0)
                  R2.showHappens(
                      CMMsg.MSG_OK_ACTION,
                      "^JThe terrible rumble of a tornado can be heard outside.^?"
                          + CMProps.msp("tornado.wav", 40));
                else
                  R2.showHappens(
                      CMMsg.MSG_OK_ACTION,
                      "^JThe terrible rumble of a tornado can be heard.^?"
                          + CMProps.msp("tornado.wav", 40));
              } else
                R2.showHappens(
                    CMMsg.MSG_OK_ACTION,
                    "^JA huge and terrible tornado touches down somewhere near by.^?"
                        + CMProps.msp("tornado.wav", 40));
          }
        }
      }
    }
    if ((dustDown--) == 1) {
      resetDustTicks();
      if (C.weatherType(null) == Climate.WEATHER_DUSTSTORM) {
        Vector choices = new Vector();
        Room R = null;
        for (Session S : CMLib.sessions().localOnlineIterable()) {
          if ((S.mob() == null)
              || (S.mob().location() == null)
              || (S.mob().location().getArea() != A)
              || (S.mob().isMonster())
              || (C.weatherType(S.mob().location()) != Climate.WEATHER_DUSTSTORM)) continue;
          R = S.mob().location();
          if ((R != null) && (!choices.contains(R))) choices.addElement(R);
        }
        if (choices.size() > 0) {
          R = (Room) choices.elementAt(CMLib.dice().roll(1, choices.size(), -1));
          MOB M = R.fetchRandomInhabitant();
          if ((M != null)
              && (C.weatherType(R) == Climate.WEATHER_DUSTSTORM)
              && (!CMLib.flags().isSleeping(M))) {
            Ability A2 = CMClass.getAbility("Skill_Dirt");
            if (A2 != null) A2.invoke(M, M, true, 0);
          }
        }
      }
    }
    if ((hailDown--) == 1) {
      resetHailTicks();
      if (C.weatherType(null) == Climate.WEATHER_HAIL) {
        Vector choices = new Vector();
        Room R = null;
        for (Session S : CMLib.sessions().localOnlineIterable()) {
          if ((S.mob() == null)
              || (S.mob().location() == null)
              || (S.mob().location().getArea() != A)
              || (S.mob().isMonster())
              || (C.weatherType(S.mob().location()) != Climate.WEATHER_HAIL)) continue;
          R = S.mob().location();
          if ((R != null) && (!choices.contains(R))) choices.addElement(R);
        }
        if (choices.size() > 0) {
          R = (Room) choices.elementAt(CMLib.dice().roll(1, choices.size(), -1));
          MOB M = R.fetchRandomInhabitant();
          Ability A2 = CMClass.getAbility("Chant_SummonHail");
          if ((A2 != null) && (C.weatherType(R) == Climate.WEATHER_HAIL)) {
            A2.setMiscText("RENDER MUNDANE");
            A2.invoke(M, M, true, M.phyStats().level());
          }
        }
      }
    }
    if ((C.weatherType(null) == Climate.WEATHER_DROUGHT)
        && (CMLib.dice().rollPercentage() < droughtFireChance)) {
      Room R = CMLib.map().roomLocation((Environmental) ticking);
      if ((R == null) && (ticking instanceof Area)) R = ((Area) ticking).getRandomProperRoom();
      if ((R != null)
          && ((R.domainType() & Room.INDOORS) == 0)
          && (R.domainType() != Room.DOMAIN_OUTDOORS_SWAMP)
          && (R.domainType() != Room.DOMAIN_OUTDOORS_UNDERWATER)
          && (R.domainType() != Room.DOMAIN_OUTDOORS_WATERSURFACE)
          && ((R.domainConditions() & Room.CONDITION_WET) == 0)) {
        Item I = R.getRandomItem();
        if ((I != null) && (CMLib.flags().isGettable(I)))
          switch (I.material() & RawMaterial.MATERIAL_MASK) {
            case RawMaterial.MATERIAL_CLOTH:
            case RawMaterial.MATERIAL_LEATHER:
            case RawMaterial.MATERIAL_PAPER:
            case RawMaterial.MATERIAL_VEGETATION:
            case RawMaterial.MATERIAL_WOODEN:
              {
                Ability A2 = CMClass.getAbility("Burning");
                MOB mob = CMLib.map().getFactoryMOB(R);
                R.showHappens(
                    CMMsg.MSG_OK_VISUAL,
                    I.Name()
                        + " spontaneously combusts in the seering heat!"
                        + CMProps.msp("fire.wav", 40));
                A2.invoke(mob, I, true, 0);
                mob.destroy();
              }
              break;
          }
      }
    }
    if ((gustDown--) == 1) {
      resetGustTicks();
      if ((C.weatherType(null) == Climate.WEATHER_WINDY)
          || (C.weatherType(null) == Climate.WEATHER_BLIZZARD)
          || (C.weatherType(null) == Climate.WEATHER_DUSTSTORM)) {
        Vector choices = new Vector();
        Room R = null;
        for (Session S : CMLib.sessions().localOnlineIterable()) {
          if ((S.mob() == null)
              || (S.mob().location() == null)
              || (S.mob().location().getArea() != A)
              || (S.mob().isMonster())
              || ((C.weatherType(S.mob().location()) != Climate.WEATHER_WINDY)
                  && (C.weatherType(S.mob().location()) != Climate.WEATHER_BLIZZARD)
                  && (C.weatherType(S.mob().location()) != Climate.WEATHER_DUSTSTORM))) continue;
          R = S.mob().location();
          if ((R != null) && (!choices.contains(R))) choices.addElement(R);
        }
        if (choices.size() > 0) {
          R = (Room) choices.elementAt(CMLib.dice().roll(1, choices.size(), -1));
          MOB M = CMLib.map().getFactoryMOB(R);
          Ability A2 = CMClass.getAbility("Chant_WindGust");
          if (A2 != null) {
            A2.setMiscText("RENDER MUNDANE");
            A2.invoke(M, M, true, M.phyStats().level());
          }
          M.destroy();
        }
      }
    }
    if ((rustDown--) == 1) {
      resetRustTicks();
      for (Session S : CMLib.sessions().localOnlineIterable()) {
        if ((S.mob() == null)
            || (S.mob().location() == null)
            || (S.mob().location().getArea() != A)
            || (S.mob().isMonster())) continue;
        int rustChance = 0;
        switch (C.weatherType(S.mob().location())) {
          case Climate.WEATHER_BLIZZARD:
          case Climate.WEATHER_SLEET:
          case Climate.WEATHER_SNOW:
            rustChance = 5;
            break;
          case Climate.WEATHER_HAIL:
            rustChance = 5;
            break;
          case Climate.WEATHER_THUNDERSTORM:
          case Climate.WEATHER_RAIN:
            rustChance = 5;
            break;
        }

        MOB M = S.mob();
        Room R = M.location();

        switch (R.domainType()) {
          case Room.DOMAIN_INDOORS_UNDERWATER:
          case Room.DOMAIN_INDOORS_WATERSURFACE:
          case Room.DOMAIN_OUTDOORS_WATERSURFACE:
          case Room.DOMAIN_OUTDOORS_UNDERWATER:
            rustChance += 5;
            break;
          default:
            break;
        }
        if ((R.domainConditions() & Room.CONDITION_WET) > 0) rustChance += 2;
        if (CMLib.dice().rollPercentage() < rustChance) {
          int weatherType = C.weatherType(R);
          Vector rustThese = new Vector();
          for (int i = 0; i < M.numItems(); i++) {
            Item I = M.getItem(i);
            if (I == null) continue;
            if ((!I.amWearingAt(Wearable.IN_INVENTORY))
                && (((I.material() & RawMaterial.MATERIAL_MASK) == RawMaterial.MATERIAL_METAL))
                && (I.subjectToWearAndTear())
                && ((CMLib.dice().rollPercentage() > I.phyStats().ability() * 25)))
              rustThese.addElement(I);
            else if (I.amWearingAt(Wearable.WORN_ABOUT_BODY)
                && (((I.material() & RawMaterial.MATERIAL_MASK) != RawMaterial.MATERIAL_METAL))) {
              rustThese.clear();
              break;
            }
          }
          if (R != null)
            for (int i = 0; i < rustThese.size(); i++) {
              Item I = (Item) rustThese.elementAt(i);
              CMMsg msg =
                  CMClass.getMsg(
                      M,
                      I,
                      null,
                      CMMsg.MASK_ALWAYS | CMMsg.TYP_WATER,
                      (weatherType != 0) ? "<T-NAME> rusts." : "<T-NAME> rusts in the water.",
                      CMMsg.TYP_WATER,
                      null,
                      CMMsg.NO_EFFECT,
                      null);
              if (R.okMessage(M, msg)) {
                R.send(M, msg);
                if (msg.value() <= 0) {
                  I.setUsesRemaining(I.usesRemaining() - 1);
                  if (I.usesRemaining() <= 0) {
                    msg =
                        CMClass.getMsg(
                            M,
                            null,
                            null,
                            CMMsg.MSG_OK_VISUAL,
                            I.name() + " is destroyed!",
                            null,
                            I.name() + " carried by " + M.name() + " is destroyed!");
                    if (R.okMessage(M, msg)) R.send(M, msg);
                    I.destroy();
                  }
                }
              }
            }
        }
      }
    }
    if (ticking instanceof Room) lastWeather = C.weatherType((Room) ticking);
    else lastWeather = C.weatherType(null);
    return true;
  }
 public double combatCastingTime(final MOB mob, final List<String> cmds) {
   return CMProps.getCombatActionSkillCost(
       ID(), CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCOMABLETIME), 50.0));
 }
Exemple #18
0
  public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException {
    if ((commands.size() == 1) && (((String) commands.firstElement()).startsWith("QUESTW")))
      commands.addElement("WON");
    if ((commands.size() > 1) && (((String) commands.elementAt(1)).equalsIgnoreCase("WON"))) {
      Vector qVec = new Vector();
      for (int q = 0; q < CMLib.quests().numQuests(); q++) {
        Quest Q = CMLib.quests().fetchQuest(q);
        if (Q.wasWinner(mob.Name())) {
          String name = Q.displayName().trim().length() > 0 ? Q.displayName() : Q.name();
          if (!qVec.contains(name)) qVec.addElement(name);
        }
      }
      Collections.sort(qVec);
      StringBuffer msg = new StringBuffer("^HQuests you are listed as having won:^?^N\n\r");
      for (int i = 0; i < qVec.size(); i++) msg.append(((String) qVec.elementAt(i)) + "^N\n\r");
      if (!mob.isMonster()) mob.tell(msg.toString());
    } else if ((commands.size() > 2)
        && (((String) commands.elementAt(1)).equalsIgnoreCase("DROP"))) {
      ScriptingEngine foundS = null;
      for (Enumeration<ScriptingEngine> e = mob.scripts(); e.hasMoreElements(); ) {
        ScriptingEngine SE = e.nextElement();
        if (SE == null) continue;
        if ((SE.defaultQuestName().length() > 0)
            && (CMLib.quests().findQuest(SE.defaultQuestName()) == null)) foundS = SE;
      }
      if (foundS != null) mob.delScript(foundS);
      foundS = null;

      String rest = CMParms.combine(commands, 2);
      Quest Q = CMLib.quests().findQuest(rest);
      if (Q == null) {
        mob.tell("There is no such quest as '" + rest + "'.");
        return false;
      }
      for (Enumeration<ScriptingEngine> e = mob.scripts(); e.hasMoreElements(); ) {
        ScriptingEngine SE = e.nextElement();
        if (SE == null) continue;
        if ((SE.defaultQuestName().length() > 0)
            && (SE.defaultQuestName().equalsIgnoreCase(Q.name()))) foundS = SE;
      }
      if (foundS == null) {
        mob.tell("You have not accepted a quest called '" + rest + "'.  Enter QUESTS for a list.");
        return false;
      }
      if ((!mob.isMonster()
          && (mob.session()
              .confirm("Drop the quest '" + Q.name() + "', are you sure (y/N)?", "N")))) {
        CMLib.coffeeTables().bump(Q, CoffeeTableRow.STAT_QUESTDROPPED);
        mob.delScript(foundS);
        mob.tell("Quest dropped.");
        return false;
      }
    } else if (commands.size() == 1) {
      List<Quest> qQVec = CMLib.quests().getPlayerPersistantQuests(mob);
      Vector<String> qVec = new Vector<String>();
      for (Quest Q : qQVec) {
        String name = Q.displayName().trim().length() > 0 ? Q.displayName() : Q.name();
        if (!qVec.contains(name)) qVec.addElement(name);
      }
      Collections.sort(qVec);
      StringBuffer msg = new StringBuffer("^HQuests you are listed as having accepted:^?^N\n\r");
      for (int i = 0; i < qVec.size(); i++) msg.append(((String) qVec.elementAt(i)) + "^N\n\r");
      if (!mob.isMonster())
        mob.tell(msg.toString() + "\n\r^HEnter QUEST [QUEST NAME] for more information.^N^.");

    } else {
      String rest = CMParms.combine(commands, 1);
      Quest Q = CMLib.quests().findQuest(rest);
      if (Q == null) {
        mob.tell("There is no such quest as '" + rest + "'.");
        return false;
      }
      ScriptingEngine foundS = null;
      for (Enumeration<ScriptingEngine> e = mob.scripts(); e.hasMoreElements(); ) {
        ScriptingEngine SE = e.nextElement();
        if (SE == null) continue;
        if ((SE.defaultQuestName().length() > 0)
            && (SE.defaultQuestName().equalsIgnoreCase(Q.name()))) foundS = SE;
      }
      if (foundS == null) {
        mob.tell("You have not accepted a quest called '" + rest + "'.  Enter QUESTS for a list.");
        return false;
      }
      String name = Q.displayName().trim().length() > 0 ? Q.displayName() : Q.name();
      if (!Q.name().equals(name)) name += " (" + Q.name() + ")";
      mob.tell("^HQuest Information: ^w" + name + "^N");
      String instructions = null;
      if ((instructions == null) || (instructions.length() == 0))
        instructions = foundS.getVar("*", "INSTRUCTIONS");
      if ((instructions == null) || (instructions.length() == 0))
        instructions = Q.isStat("INSTRUCTIONS") ? Q.getStat("INSTRUCTIONS") : null;
      if ((instructions == null) || (instructions.length() == 0))
        instructions = "No further information available.";
      String timeRemaining = foundS.getVar("*", "TIME_REMAINING");
      if ((timeRemaining != null) && (timeRemaining.length() > 0)) {
        String timeRemainingType = foundS.getVar("*", "TIME_REMAINING_TYPE");
        if (((timeRemainingType.equalsIgnoreCase("TICKS") || (timeRemainingType.length() == 0))
            && (CMath.isInteger(timeRemaining)))) {
          long ticks = CMath.s_int(timeRemaining);
          ticks *= CMProps.getTickMillis();
          if (ticks > 60000) timeRemaining = (ticks / 60000) + " minutes";
          else timeRemaining = (ticks / 1000) + " seconds";
        } else if (timeRemainingType.length() > 0) timeRemaining += " " + timeRemainingType;
      }
      String progress = foundS.getVar("*", "PROGRESS");
      mob.tell("^w" + instructions + "^N");
      if ((timeRemaining != null) && (timeRemaining.length() > 0))
        mob.tell("\n\r^yTime Remaining: ^w" + timeRemaining + "^N");
      if ((progress != null) && (progress.length() > 0))
        mob.tell("\n\r^yProgress: ^w" + progress + "^N");
    }
    return false;
  }
Exemple #19
0
  public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) {
    int autoGenerate = 0;
    if ((auto) && (commands.size() > 0) && (commands.firstElement() instanceof Integer)) {
      autoGenerate = ((Integer) commands.firstElement()).intValue();
      commands.removeElementAt(0);
      givenTarget = null;
    }
    DVector enhancedTypes = enhancedTypes(mob, commands);
    randomRecipeFix(mob, addRecipes(mob, loadRecipes()), commands, autoGenerate);
    if (commands.size() == 0) {
      commonTell(
          mob,
          "Weave what? Enter \"weave list\" for a list, \"weave refit <item>\" to resize, \"weave learn <item>\", \"weave scan\", or \"weave mend <item>\".");
      return false;
    }
    if ((!auto)
        && (commands.size() > 0)
        && (((String) commands.firstElement()).equalsIgnoreCase("bundle"))) {
      bundling = true;
      if (super.invoke(mob, commands, givenTarget, auto, asLevel))
        return super.bundle(mob, commands);
      return false;
    }
    List<List<String>> recipes = addRecipes(mob, loadRecipes());
    String str = (String) commands.elementAt(0);
    bundling = false;
    String startStr = null;
    int duration = 4;
    if (str.equalsIgnoreCase("list")) {
      String mask = CMParms.combine(commands, 1);
      StringBuffer buf = new StringBuffer("");
      int toggler = 1;
      int toggleTop = 2;
      for (int r = 0; r < toggleTop; r++)
        buf.append(
            CMStrings.padRight("Item", 22)
                + " "
                + CMStrings.padRight("Lvl", 3)
                + " "
                + CMStrings.padRight("Material", 10)
                + " ");
      buf.append("\n\r");
      for (int r = 0; r < recipes.size(); r++) {
        List<String> V = recipes.get(r);
        if (V.size() > 0) {
          String item = replacePercent((String) V.get(RCP_FINALNAME), "");
          int level = CMath.s_int((String) V.get(RCP_LEVEL));
          String wood = getComponentDescription(mob, V, RCP_WOOD);
          if (wood.length() > 5) {
            if (toggler > 1) buf.append("\n\r");
            toggler = toggleTop;
          }
          if ((level <= xlevel(mob))
              && ((mask == null)
                  || (mask.length() == 0)
                  || mask.equalsIgnoreCase("all")
                  || CMLib.english().containsString(item, mask))) {
            buf.append(
                CMStrings.padRight(item, 22)
                    + " "
                    + CMStrings.padRight("" + level, 3)
                    + " "
                    + CMStrings.padRightPreserve("" + wood, 10)
                    + ((toggler != toggleTop) ? " " : "\n\r"));
            if (++toggler > toggleTop) toggler = 1;
          }
        }
      }
      if (toggler != 1) buf.append("\n\r");
      commonTell(mob, buf.toString());
      enhanceList(mob);
      return true;
    } else if ((commands.firstElement() instanceof String)
        && (((String) commands.firstElement())).equalsIgnoreCase("learn")) {
      return doLearnRecipe(mob, commands, givenTarget, auto, asLevel);
    } else if (str.equalsIgnoreCase("scan")) return publicScan(mob, commands);
    else if (str.equalsIgnoreCase("mend")) {
      building = null;
      activity = CraftingActivity.CRAFTING;
      messedUp = false;
      key = null;
      Vector newCommands = CMParms.parse(CMParms.combine(commands, 1));
      building =
          getTarget(mob, mob.location(), givenTarget, newCommands, Wearable.FILTER_UNWORNONLY);
      if (!canMend(mob, building, false)) return false;
      activity = CraftingActivity.MENDING;
      if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false;
      startStr = "<S-NAME> start(s) mending " + building.name() + ".";
      displayText = "You are mending " + building.name();
      verb = "mending " + building.name();
    } else if (str.equalsIgnoreCase("refit")) {
      building = null;
      activity = CraftingActivity.CRAFTING;
      key = null;
      messedUp = false;
      Vector newCommands = CMParms.parse(CMParms.combine(commands, 1));
      building =
          getTarget(mob, mob.location(), givenTarget, newCommands, Wearable.FILTER_UNWORNONLY);
      if (building == null) return false;
      if ((building.material() != RawMaterial.RESOURCE_COTTON)
          && (building.material() != RawMaterial.RESOURCE_SILK)
          && (building.material() != RawMaterial.RESOURCE_HEMP)
          && (building.material() != RawMaterial.RESOURCE_VINE)
          && (building.material() != RawMaterial.RESOURCE_WHEAT)
          && (building.material() != RawMaterial.RESOURCE_SEAWEED)) {
        commonTell(mob, "That's not made of any sort of weavable material.  It can't be refitted.");
        return false;
      }
      if (!(building instanceof Armor)) {
        commonTell(mob, "You don't know how to refit that sort of thing.");
        return false;
      }
      if (building.phyStats().height() == 0) {
        commonTell(mob, building.name() + " is already the right size.");
        return false;
      }
      activity = CraftingActivity.REFITTING;
      if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false;
      startStr = "<S-NAME> start(s) refitting " + building.name() + ".";
      displayText = "You are refitting " + building.name();
      verb = "refitting " + building.name();
    } else {
      building = null;
      activity = CraftingActivity.CRAFTING;
      messedUp = false;
      aborted = false;
      key = null;
      int amount = -1;
      if ((commands.size() > 1) && (CMath.isNumber((String) commands.lastElement()))) {
        amount = CMath.s_int((String) commands.lastElement());
        commands.removeElementAt(commands.size() - 1);
      }
      String recipeName = CMParms.combine(commands, 0);
      List<String> foundRecipe = null;
      List<List<String>> matches = matchingRecipeNames(recipes, recipeName, true);
      for (int r = 0; r < matches.size(); r++) {
        List<String> V = matches.get(r);
        if (V.size() > 0) {
          int level = CMath.s_int((String) V.get(RCP_LEVEL));
          if (level <= xlevel(mob)) {
            foundRecipe = V;
            break;
          }
        }
      }
      if (foundRecipe == null) {
        commonTell(
            mob,
            "You don't know how to weave a '" + recipeName + "'.  Try \"weave list\" for a list.");
        return false;
      }

      final String woodRequiredStr = (String) foundRecipe.get(RCP_WOOD);
      final List<Object> componentsFoundList =
          getAbilityComponents(
              mob,
              woodRequiredStr,
              "make " + CMLib.english().startWithAorAn(recipeName),
              autoGenerate);
      if (componentsFoundList == null) return false;
      int woodRequired = CMath.s_int(woodRequiredStr);
      woodRequired = adjustWoodRequired(woodRequired, mob);

      if (amount > woodRequired) woodRequired = amount;
      int[] pm = {
        RawMaterial.RESOURCE_COTTON,
        RawMaterial.RESOURCE_SILK,
        RawMaterial.RESOURCE_HEMP,
        RawMaterial.RESOURCE_VINE,
        RawMaterial.RESOURCE_WHEAT,
        RawMaterial.RESOURCE_SEAWEED
      };
      String misctype = (String) foundRecipe.get(RCP_MISCTYPE);
      String spell =
          (foundRecipe.size() > RCP_SPELL) ? ((String) foundRecipe.get(RCP_SPELL)).trim() : "";
      bundling = spell.equalsIgnoreCase("BUNDLE") || misctype.equalsIgnoreCase("BUNDLE");
      int[][] data =
          fetchFoundResourceData(
              mob,
              woodRequired,
              "weavable material",
              pm,
              0,
              null,
              null,
              false,
              autoGenerate,
              enhancedTypes);
      if (data == null) return false;
      fixDataForComponents(data, componentsFoundList);
      woodRequired = data[0][FOUND_AMT];
      if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false;
      int lostValue =
          autoGenerate > 0
              ? 0
              : CMLib.materials()
                      .destroyResources(mob.location(), woodRequired, data[0][FOUND_CODE], 0, null)
                  + CMLib.ableMapper().destroyAbilityComponents(componentsFoundList);
      building = CMClass.getItem((String) foundRecipe.get(RCP_CLASSTYPE));
      if (building == null) {
        commonTell(mob, "There's no such thing as a " + foundRecipe.get(RCP_CLASSTYPE) + "!!!");
        return false;
      }
      duration =
          getDuration(
              CMath.s_int((String) foundRecipe.get(RCP_TICKS)),
              mob,
              CMath.s_int((String) foundRecipe.get(RCP_LEVEL)),
              4);
      String itemName =
          replacePercent(
                  (String) foundRecipe.get(RCP_FINALNAME),
                  RawMaterial.CODES.NAME(data[0][FOUND_CODE]))
              .toLowerCase();
      if (bundling) itemName = "a " + woodRequired + "# " + itemName;
      else if (itemName.endsWith("s")) itemName = "some " + itemName;
      else itemName = CMLib.english().startWithAorAn(itemName);
      building.setName(itemName);
      startStr = "<S-NAME> start(s) weaving " + building.name() + ".";
      displayText = "You are weaving " + building.name();
      verb = "weaving " + building.name();
      building.setDisplayText(itemName + " lies here");
      building.setDescription(itemName + ". ");
      building
          .basePhyStats()
          .setWeight(
              (int) Math.round((double) woodRequired * this.getItemWeightMultiplier(bundling)));
      building.setBaseValue(CMath.s_int((String) foundRecipe.get(RCP_VALUE)));
      building.setMaterial(data[0][FOUND_CODE]);
      building.basePhyStats().setLevel(CMath.s_int((String) foundRecipe.get(RCP_LEVEL)));
      building.setSecretIdentity(getBrand(mob));
      int capacity = CMath.s_int((String) foundRecipe.get(RCP_CAPACITY));
      long canContain = getContainerType((String) foundRecipe.get(RCP_CONTAINMASK));
      int armordmg = CMath.s_int((String) foundRecipe.get(RCP_ARMORDMG));
      if (bundling) {
        building.setBaseValue(lostValue);
        building.basePhyStats().setWeight(woodRequired);
      }
      addSpells(building, spell);
      if (building instanceof Weapon) {
        ((Weapon) building).setWeaponClassification(Weapon.CLASS_FLAILED);
        for (int cl = 0; cl < Weapon.CLASS_DESCS.length; cl++) {
          if (misctype.equalsIgnoreCase(Weapon.CLASS_DESCS[cl]))
            ((Weapon) building).setWeaponClassification(cl);
        }
        building.basePhyStats().setDamage(armordmg);
        ((Weapon) building).setRawProperLocationBitmap(Wearable.WORN_WIELD | Wearable.WORN_HELD);
        ((Weapon) building).setRawLogicalAnd((capacity > 1));
      }
      key = null;
      if (building instanceof Armor) {
        if (capacity > 0) {
          ((Armor) building).setCapacity(capacity + woodRequired);
          ((Armor) building).setContainTypes(canContain);
        }
        ((Armor) building).basePhyStats().setArmor(0);
        if (armordmg != 0)
          ((Armor) building).basePhyStats().setArmor(armordmg + (abilityCode() - 1));
        setWearLocation(building, misctype, 0);
      } else if (building instanceof Container) {
        if (capacity > 0) {
          ((Container) building).setCapacity(capacity + woodRequired);
          ((Container) building).setContainTypes(canContain);
        }
        if (misctype.equalsIgnoreCase("LID"))
          ((Container) building).setLidsNLocks(true, false, false, false);
        else if (misctype.equalsIgnoreCase("LOCK")) {
          ((Container) building).setLidsNLocks(true, false, true, false);
          ((Container) building).setKeyName(Double.toString(Math.random()));
          key = CMClass.getItem("GenKey");
          ((DoorKey) key).setKey(((Container) building).keyName());
          key.setName("a key");
          key.setDisplayText("a small key sits here");
          key.setDescription("looks like a key to " + building.name());
          key.recoverPhyStats();
          key.text();
        }
      }
      if (building instanceof Rideable) {
        setRideBasis((Rideable) building, misctype);
      }
      building.recoverPhyStats();
      building.text();
      building.recoverPhyStats();
    }

    messedUp = !proficiencyCheck(mob, 0, auto);

    if (bundling) {
      messedUp = false;
      duration = 1;
      verb = "bundling " + RawMaterial.CODES.NAME(building.material()).toLowerCase();
      startStr = "<S-NAME> start(s) " + verb + ".";
      displayText = "You are " + verb;
    }

    if (autoGenerate > 0) {
      if (key != null) commands.addElement(key);
      commands.addElement(building);
      return true;
    }

    CMMsg msg = CMClass.getMsg(mob, building, this, CMMsg.MSG_NOISYMOVEMENT, startStr);
    if (mob.location().okMessage(mob, msg)) {
      mob.location().send(mob, msg);
      building = (Item) msg.target();
      beneficialAffect(mob, mob, asLevel, duration);
      enhanceItem(mob, building, enhancedTypes);
    } else if (bundling) {
      messedUp = false;
      aborted = false;
      unInvoke();
    }
    return true;
  }
 private GOVT_STAT_CODES getStatIndex(String code) {
   return (GOVT_STAT_CODES) CMath.s_valueOf(GOVT_STAT_CODES.values(), code);
 }
  public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) {
    int autoGenerate = 0;
    if ((auto) && (commands.size() > 0) && (commands.firstElement() instanceof Integer)) {
      autoGenerate = ((Integer) commands.firstElement()).intValue();
      commands.removeElementAt(0);
      givenTarget = null;
    }
    DVector enhancedTypes = enhancedTypes(mob, commands);
    randomRecipeFix(mob, addRecipes(mob, loadRecipes()), commands, autoGenerate);
    if (commands.size() == 0) {
      commonTell(
          mob,
          "Make what? Enter \"mleatherwork list\" for a list, \"mleatherwork refit <item>\" to resize, \"mleatherwork learn <item>\", \"mleatherwork scan\", or \"mleatherwork mend <item>\".");
      return false;
    }
    if ((!auto)
        && (commands.size() > 0)
        && (((String) commands.firstElement()).equalsIgnoreCase("bundle"))) {
      bundling = true;
      if (super.invoke(mob, commands, givenTarget, auto, asLevel))
        return super.bundle(mob, commands);
      return false;
    }
    List<List<String>> recipes = addRecipes(mob, loadRecipes());
    String str = (String) commands.elementAt(0);
    playSound = "scissor.wav";
    String startStr = null;
    bundling = false;
    int multiplier = 4;
    int duration = 4;
    if (str.equalsIgnoreCase("list")) {
      String mask = CMParms.combine(commands, 1);
      StringBuffer buf = new StringBuffer("");
      int toggler = 1;
      int toggleTop = 2;
      for (int r = 0; r < toggleTop; r++)
        buf.append(
            CMStrings.padRight("Item", 30)
                + " "
                + CMStrings.padRight("Lvl", 3)
                + " "
                + CMStrings.padRight("Amt", 3)
                + " ");
      buf.append("\n\r");
      for (int r = 0; r < recipes.size(); r++) {
        List<String> V = recipes.get(r);
        if (V.size() > 0) {
          String item = replacePercent((String) V.get(RCP_FINALNAME), "");
          int level = CMath.s_int((String) V.get(RCP_LEVEL));
          String wood = getComponentDescription(mob, V, RCP_WOOD);
          if (wood.length() > 5) {
            if (toggler > 1) buf.append("\n\r");
            toggler = toggleTop;
          }
          if ((level <= xlevel(mob))
              && ((mask == null)
                  || (mask.length() == 0)
                  || mask.equalsIgnoreCase("all")
                  || CMLib.english().containsString(item, mask))) {
            buf.append(
                CMStrings.padRight(item, 30)
                    + " "
                    + CMStrings.padRight("" + (level), 3)
                    + " "
                    + CMStrings.padRightPreserve("" + wood, 3)
                    + ((toggler != toggleTop) ? " " : "\n\r"));
            if (++toggler > toggleTop) toggler = 1;
          }
        }
      }
      if (toggler != 1) buf.append("\n\r");
      commonTell(mob, buf.toString());
      enhanceList(mob);
      return true;
    } else if ((commands.firstElement() instanceof String)
        && (((String) commands.firstElement())).equalsIgnoreCase("learn")) {
      return doLearnRecipe(mob, commands, givenTarget, auto, asLevel);
    } else if (str.equalsIgnoreCase("scan")) return publicScan(mob, commands);
    else if (str.equalsIgnoreCase("mend")) {
      building = null;
      activity = CraftingActivity.CRAFTING;
      messedUp = false;
      Vector newCommands = CMParms.parse(CMParms.combine(commands, 1));
      building =
          getTarget(mob, mob.location(), givenTarget, newCommands, Wearable.FILTER_UNWORNONLY);
      if (!canMend(mob, building, false)) return false;
      activity = CraftingActivity.MENDING;
      if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false;
      startStr = "<S-NAME> start(s) mending " + building.name() + ".";
      displayText = "You are mending " + building.name();
      verb = "mending " + building.name();
    } else if (str.equalsIgnoreCase("refit")) {
      building = null;
      activity = CraftingActivity.CRAFTING;
      messedUp = false;
      Vector newCommands = CMParms.parse(CMParms.combine(commands, 1));
      building =
          getTarget(mob, mob.location(), givenTarget, newCommands, Wearable.FILTER_UNWORNONLY);
      if (building == null) return false;
      if ((building.material() & RawMaterial.MATERIAL_MASK) != RawMaterial.MATERIAL_LEATHER) {
        commonTell(mob, "That's not made of leather.  That can't be refitted.");
        return false;
      }
      if (!(building instanceof Armor)) {
        commonTell(mob, "You don't know how to refit that sort of thing.");
        return false;
      }
      if (building.phyStats().height() == 0) {
        commonTell(mob, building.name() + " is already the right size.");
        return false;
      }
      activity = CraftingActivity.REFITTING;
      if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false;
      startStr = "<S-NAME> start(s) refitting " + building.name() + ".";
      displayText = "You are refitting " + building.name();
      verb = "refitting " + building.name();
    } else {
      building = null;
      activity = CraftingActivity.CRAFTING;
      messedUp = false;
      aborted = false;
      int amount = -1;
      if ((commands.size() > 1) && (CMath.isNumber((String) commands.lastElement()))) {
        amount = CMath.s_int((String) commands.lastElement());
        commands.removeElementAt(commands.size() - 1);
      }
      String recipeName = CMParms.combine(commands, 0);
      List<String> foundRecipe = null;
      List<List<String>> matches = matchingRecipeNames(recipes, recipeName, true);
      for (int r = 0; r < matches.size(); r++) {
        List<String> V = matches.get(r);
        if (V.size() > 0) {
          String name = (String) V.get(RCP_FINALNAME);
          int level = CMath.s_int((String) V.get(RCP_LEVEL));
          if ((level <= xlevel(mob)) && (name.toUpperCase().indexOf("BATTLEMOULDED") >= 0)) {
            multiplier = 9;
            foundRecipe = V;
            break;
          } else if ((level <= xlevel(mob)) && (name.toUpperCase().indexOf("LAMINAR") >= 0)) {
            multiplier = 8;
            foundRecipe = V;
            break;
          } else if ((level <= (xlevel(mob))) && (name.toUpperCase().indexOf("MASTERWORK") >= 0)) {
            multiplier = 7;
            foundRecipe = V;
            break;
          } else if ((level <= xlevel(mob)) && (name.toUpperCase().indexOf("REINFORCED") >= 0)) {
            multiplier = 6;
            foundRecipe = V;
            break;
          } else if ((level <= (xlevel(mob))) && (name.toUpperCase().indexOf("CUIRBOULI") >= 0)) {
            multiplier = 5;
            foundRecipe = V;
            break;
          } else if (level <= (xlevel(mob))) {
            multiplier = 4;
            foundRecipe = V;
            break;
          }
        }
      }
      if (foundRecipe == null) {
        commonTell(
            mob,
            "You don't know how to make a '"
                + recipeName
                + "'.  Try \"mleatherwork list\" for a list.");
        return false;
      }

      final String woodRequiredStr = (String) foundRecipe.get(RCP_WOOD);
      final List<Object> componentsFoundList =
          getAbilityComponents(
              mob,
              woodRequiredStr,
              "make " + CMLib.english().startWithAorAn(recipeName),
              autoGenerate);
      if (componentsFoundList == null) return false;
      int woodRequired = CMath.s_int(woodRequiredStr);
      woodRequired = adjustWoodRequired(woodRequired, mob);

      if (amount > woodRequired) woodRequired = amount;
      int[] pm = {RawMaterial.MATERIAL_LEATHER};
      int[] pm1 = {RawMaterial.MATERIAL_METAL, RawMaterial.MATERIAL_MITHRIL};
      String misctype = (String) foundRecipe.get(RCP_MISCTYPE);
      bundling = misctype.equalsIgnoreCase("BUNDLE");
      int[][] data =
          fetchFoundResourceData(
              mob,
              woodRequired,
              "leather",
              pm,
              (multiplier == 6) ? 1 : 0,
              (multiplier == 6) ? "metal" : null,
              (multiplier == 6) ? pm1 : null,
              bundling,
              autoGenerate,
              enhancedTypes);
      if (data == null) return false;
      fixDataForComponents(data, componentsFoundList);
      woodRequired = data[0][FOUND_AMT];
      if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false;
      int lostValue =
          autoGenerate > 0
              ? 0
              : CMLib.materials()
                      .destroyResources(
                          mob.location(),
                          woodRequired,
                          data[0][FOUND_CODE],
                          data[1][FOUND_CODE],
                          null)
                  + CMLib.ableMapper().destroyAbilityComponents(componentsFoundList);
      building = CMClass.getItem((String) foundRecipe.get(RCP_CLASSTYPE));
      if (building == null) {
        commonTell(mob, "There's no such thing as a " + foundRecipe.get(RCP_CLASSTYPE) + "!!!");
        return false;
      }
      duration =
          getDuration(multiplier * CMath.s_int((String) foundRecipe.get(RCP_TICKS)), mob, 30, 4);
      String itemName =
          (replacePercent(
                  (String) foundRecipe.get(RCP_FINALNAME),
                  RawMaterial.CODES.NAME(data[0][FOUND_CODE])))
              .toLowerCase();
      if (bundling) itemName = "a " + woodRequired + "# " + itemName;
      else if (itemName.endsWith("s")) itemName = "some " + itemName;
      else itemName = CMLib.english().startWithAorAn(itemName);
      building.setName(itemName);
      startStr = "<S-NAME> start(s) making " + building.name() + ".";
      displayText = "You are making " + building.name();
      verb = "making " + building.name();
      building.setDisplayText(itemName + " lies here");
      building.setDescription(itemName + ". ");
      building
          .basePhyStats()
          .setWeight(
              (int) Math.round((double) woodRequired * this.getItemWeightMultiplier(bundling)));
      building.setBaseValue(CMath.s_int((String) foundRecipe.get(RCP_VALUE)) * multiplier);
      building.setMaterial(data[0][FOUND_CODE]);
      building.setSecretIdentity(getBrand(mob));
      int hardness = RawMaterial.CODES.HARDNESS(data[0][FOUND_CODE]) - 2;
      building
          .basePhyStats()
          .setLevel(CMath.s_int((String) foundRecipe.get(RCP_LEVEL)) + (2 * hardness));
      int capacity = CMath.s_int((String) foundRecipe.get(RCP_CAPACITY));
      long canContain = getContainerType((String) foundRecipe.get(RCP_CONTAINMASK));
      int armordmg = CMath.s_int((String) foundRecipe.get(RCP_ARMORDMG));
      if (armordmg != 0) armordmg = armordmg + (multiplier - 1);
      if (bundling) building.setBaseValue(lostValue);
      String spell =
          (foundRecipe.size() > RCP_SPELL) ? ((String) foundRecipe.get(RCP_SPELL)).trim() : "";
      addSpells(building, spell);
      if (building instanceof Weapon) {
        ((Weapon) building)
            .basePhyStats()
            .setAttackAdjustment(abilityCode() + (hardness * 5) + (abilityCode() - 1) - 1);
        ((Weapon) building).setWeaponClassification(Weapon.CLASS_FLAILED);
        setWeaponTypeClass((Weapon) building, misctype, Weapon.TYPE_SLASHING);
        building.basePhyStats().setDamage(armordmg + hardness);
        ((Weapon) building).setRawProperLocationBitmap(Wearable.WORN_WIELD | Wearable.WORN_HELD);
        ((Weapon) building).setRawLogicalAnd((capacity > 1));
      }
      if (building instanceof Armor) {
        if (capacity > 0) {
          ((Armor) building).setCapacity(capacity + woodRequired);
          ((Armor) building).setContainTypes(canContain);
        }
        ((Armor) building).basePhyStats().setArmor(0);
        if (armordmg != 0)
          ((Armor) building).basePhyStats().setArmor(armordmg + (abilityCode() - 1) + hardness);
        setWearLocation(building, misctype, 0);
      }
      if (building instanceof Drink) {
        if (CMLib.flags().isGettable(building)) {
          ((Drink) building).setLiquidRemaining(0);
          ((Drink) building).setLiquidHeld(capacity * 50);
          ((Drink) building).setThirstQuenched(250);
          if ((capacity * 50) < 250) ((Drink) building).setThirstQuenched(capacity * 50);
        }
      }
      building.recoverPhyStats();
      building.text();
      building.recoverPhyStats();
    }

    messedUp = !proficiencyCheck(mob, 0, auto);

    if (bundling) {
      messedUp = false;
      duration = 1;
      verb = "bundling " + RawMaterial.CODES.NAME(building.material()).toLowerCase();
      startStr = "<S-NAME> start(s) " + verb + ".";
      displayText = "You are " + verb;
    }

    if (autoGenerate > 0) {
      commands.addElement(building);
      return true;
    }

    CMMsg msg = CMClass.getMsg(mob, building, this, CMMsg.MSG_NOISYMOVEMENT, startStr);
    if (mob.location().okMessage(mob, msg)) {
      mob.location().send(mob, msg);
      building = (Item) msg.target();
      beneficialAffect(mob, mob, asLevel, duration);
      enhanceItem(mob, building, enhancedTypes);
    } else if (bundling) {
      messedUp = false;
      aborted = false;
      unInvoke();
    }
    return true;
  }
Exemple #22
0
  public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException {
    if ((!mob.isMonster()) && CMath.bset(mob.getBitmap(), MOB.ATT_QUIET)) {
      mob.tell("You have QUIET mode on.  You must turn it off first.");
      return false;
    }

    if (commands.size() < 3) {
      mob.tell("Tell whom what?");
      return false;
    }
    commands.removeElementAt(0);

    if (((String) commands.firstElement()).equalsIgnoreCase("last")
        && (CMath.isNumber(CMParms.combine(commands, 1)))
        && (mob.playerStats() != null)) {
      java.util.List<String> V = mob.playerStats().getTellStack();
      if ((V.size() == 0)
          || (CMath.bset(metaFlags, Command.METAFLAG_AS))
          || (CMath.bset(metaFlags, Command.METAFLAG_POSSESSED))) mob.tell("No telling.");
      else {
        int num = CMath.s_int(CMParms.combine(commands, 1));
        if (num > V.size()) num = V.size();
        Session S = mob.session();
        try {
          if (S != null) S.snoopSuspension(1);
          for (int i = V.size() - num; i < V.size(); i++) mob.tell((String) V.get(i));
        } finally {
          if (S != null) S.snoopSuspension(-1);
        }
      }
      return false;
    }

    MOB targetM = null;
    String targetName = ((String) commands.elementAt(0)).toUpperCase();
    targetM = CMLib.sessions().findPlayerOnline(targetName, true);
    if (targetM == null) targetM = CMLib.sessions().findPlayerOnline(targetName, false);
    for (int i = 1; i < commands.size(); i++) {
      String s = (String) commands.elementAt(i);
      if (s.indexOf(' ') >= 0) commands.setElementAt("\"" + s + "\"", i);
    }
    String combinedCommands = CMParms.combine(commands, 1);
    if (combinedCommands.equals("")) {
      mob.tell("Tell them what?");
      return false;
    }
    combinedCommands = CMProps.applyINIFilter(combinedCommands, CMProps.SYSTEM_SAYFILTER);
    if (targetM == null) {
      if (targetName.indexOf('@') >= 0) {
        String mudName = targetName.substring(targetName.indexOf('@') + 1);
        targetName = targetName.substring(0, targetName.indexOf('@'));
        if (CMLib.intermud().i3online() || CMLib.intermud().imc2online())
          CMLib.intermud().i3tell(mob, targetName, mudName, combinedCommands);
        else mob.tell("Intermud is unavailable.");
        return false;
      }
      mob.tell("That person doesn't appear to be online.");
      return false;
    }

    if (CMath.bset(targetM.getBitmap(), MOB.ATT_QUIET)) {
      mob.tell("That person can not hear you.");
      return false;
    }

    Session ts = targetM.session();
    try {
      if (ts != null) ts.snoopSuspension(1);
      CMLib.commands().postSay(mob, targetM, combinedCommands, true, true);
    } finally {
      if (ts != null) ts.snoopSuspension(-1);
    }

    if ((targetM.session() != null) && (targetM.session().afkFlag()))
      mob.tell(targetM.session().afkMessage());
    return false;
  }