Example #1
0
  @Override
  public GRCandidateProgram[] crossover(final CandidateProgram p1, final CandidateProgram p2) {

    final GRCandidateProgram child1 = (GRCandidateProgram) p1;
    final GRCandidateProgram child2 = (GRCandidateProgram) p2;

    final NonTerminalSymbol parseTree1 = child1.getParseTree();
    final NonTerminalSymbol parseTree2 = child2.getParseTree();

    final List<NonTerminalSymbol> nonTerminals1 = parseTree1.getNonTerminalSymbols();
    final List<NonTerminalSymbol> nonTerminals2 = parseTree2.getNonTerminalSymbols();

    final int point1 = rng.nextInt(nonTerminals1.size());

    final NonTerminalSymbol subtree1 = nonTerminals1.get(point1);

    // Generate a list of matching non-terminals from the second program.
    final List<NonTerminalSymbol> matchingNonTerminals = new ArrayList<NonTerminalSymbol>();
    for (final NonTerminalSymbol nt : nonTerminals2) {
      if (nt.getGrammarRule().equals(subtree1.getGrammarRule())) {
        matchingNonTerminals.add(nt);
      }
    }

    if (matchingNonTerminals.isEmpty()) {
      // No valid points in second program, cancel crossover.
      return null;
    } else {
      // Randomly choose a second point out of the matching non-terminals.
      final int point2 = rng.nextInt(matchingNonTerminals.size());
      final NonTerminalSymbol subtree2 = matchingNonTerminals.get(point2);

      // Add crossover points to the stats manager.
      Stats.get().addData(XO_POINT1, point1);
      Stats.get().addData(XO_POINT2, point2);

      // Swap the non-terminals' children.
      final List<Symbol> temp = subtree1.getChildren();
      subtree1.setChildren(subtree2.getChildren());
      subtree2.setChildren(temp);

      // Add subtrees into the stats manager.
      Stats.get().addData(XO_SUBTREE1, subtree1);
      Stats.get().addData(XO_SUBTREE2, subtree2);
    }

    return new GRCandidateProgram[] {child1, child2};
  }
Example #2
0
    @NotNull
    public String getAnalysisSummary() {
        StringBuilder sb = new StringBuilder();
        sb.append("\n" + _.banner("analysis summary"));

        String duration = _.formatTime(System.currentTimeMillis() - stats.getInt("startTime"));
        sb.append("\n- total time: " + duration);
        sb.append("\n- modules loaded: " + loadedFiles.size());
        sb.append("\n- semantic problems: " + semanticErrors.size());
        sb.append("\n- failed to parse: " + failedToParse.size());

        // calculate number of defs, refs, xrefs
        int nDef = 0, nXRef = 0;
        for (Binding b : getAllBindings()) {
            nDef += 1;
            nXRef += b.refs.size();
        }

        sb.append("\n- number of definitions: " + nDef);
        sb.append("\n- number of cross references: " + nXRef);
        sb.append("\n- number of references: " + getReferences().size());

        long nResolved = this.resolved.size();
        long nUnresolved = this.unresolved.size();
        sb.append("\n- resolved names: " + nResolved);
        sb.append("\n- unresolved names: " + nUnresolved);
        sb.append("\n- name resolve rate: " + _.percent(nResolved, nResolved + nUnresolved));
        sb.append("\n" + _.getGCStats());

        return sb.toString();
    }
Example #3
0
  /**
   * Writes the node to the specified output stream.
   *
   * @param out output stream
   * @throws IOException I/O exception
   */
  void write(final DataOutput out) throws IOException {
    out.writeNum(name);
    out.write1(kind);
    out.writeNum(0);
    out.writeNum(children.length);
    out.writeDouble(1);

    // update leaf flag
    boolean leaf = stats.isLeaf();
    for (final PathNode child : children) {
      leaf &= child.kind == Data.TEXT || child.kind == Data.ATTR;
    }
    stats.setLeaf(leaf);
    stats.write(out);
    for (final PathNode child : children) child.write(out);
  }
  /**
   * get xp and gold from killing characters
   *
   * @param Charac collision characters
   */
  public void KillXP(GameCharacter[] Charac) {
    // When the character dies
    for (int i = 0; i < Charac.length; i++) {
      if (Charac[i].ISDEAD && Charac[i].COLL_LISTENER) {

        Charac[i].COLL_LISTENER = false;
        audDEATH.playAudio("death.wav");

        // Remove collision listener
        for (int j = 0; j < FIREBALL.length; j++) {
          FIREBALL[j].removeCollChar(Charac[i]);
        }
        for (int j = 0; j < SHOCK.length; j++) {
          SHOCK[j].removeCollChar(Charac[i]);
        }
        for (int j = 0; j < DARKNESS.length; j++) {
          DARKNESS[j].removeCollChar(Charac[i]);
        }
        for (int j = 0; j < LIFE_DRAIN.length; j++) {
          LIFE_DRAIN[j].removeCollChar(Charac[i]);
        }

        // Add Xp
        STATS.IncreaseXP(10 * Charac[i].STATS.LEVEL);
        // Add Gold
        this.GOLD += Charac[i].GOLD;
      }
    }
  }
Example #5
0
 /**
  * Default constructor.
  *
  * @param name node name
  * @param kind node kind
  * @param parent parent node
  * @param count counter
  */
 private PathNode(final int name, final byte kind, final PathNode parent, final int count) {
   this.children = new PathNode[0];
   this.name = (short) name;
   this.kind = kind;
   this.parent = parent;
   stats = new Stats();
   stats.count = count;
 }
 public void CompleteQuest(int Index) {
   Quest qstComp = QUEST_LIST.elementAt(Index);
   qstComp.STATUS = 3;
   qstComp.QUEST_GIVER.QUEST_LIST.elementAt(0).STATUS = 3;
   qstComp.QUEST_GIVER.QUEST_LIST.removeElementAt(0);
   STATS.IncreaseXP(qstComp.XP);
   GOLD += qstComp.GOLD;
 }
Example #7
0
  public boolean pass(int[] bowl, int bowlId, int round, boolean canPick, boolean mustTake) {
    float[] currentBowl = Vectors.castToFloatArray(bowl);
    numFruits = Vectors.sum(currentBowl);
    if (!canPick) {
      log("CANT PICK RETURNING EARLY");
      return false;
    }

    log("|||||||||||||||||||||||||||||||||||||||||");
    log("Number of bowls that will pass: "******"Number of bowls remaining: " + bowlsRemaining);

    // Initialize the histogram now that we know how many fruit come in a bowl
    if (mle == null) {
      mle = new MLE((int) numFruits, numPlayers, prefs);
    }
    mle.addObservation(currentBowl);

    // calculate score for the bowl the we get
    float score = score(currentBowl);
    scoreStats.addData(score);

    // get MLE and score it
    float[] uniformBowl = new float[currentBowl.length];
    for (int i = 0; i < bowl.length; i++) {
      uniformBowl[i] = numFruits / bowl.length;
    }
    float uniformScore = score(uniformBowl);

    log("Uniform Score: " + uniformScore);
    log("MLE Score: " + score(mle.bowl(round == 0)));
    log("Score: " + score);
    float[] mleBowl = mle.bowl(round == 0);
    Stats bowlGenerationStats = mle.getBowlGenerationStats();
    float[] mlePlatter = mle.platter();
    float maxScore = maxScore(mlePlatter);
    boolean take =
        shouldTakeBasedOnScore(
            score, score(mleBowl), maxScore, bowlGenerationStats.standardDeviation());
    bowlsRemaining--;
    return take;
  }
Example #8
0
 public Analyzer(Map<String, Object> options) {
     self = this;
     if (options != null) {
         this.options = options;
     } else {
         this.options = new HashMap<>();
     }
     stats.putInt("startTime", System.currentTimeMillis());
     this.suffix = ".rb";
     addEnvPath();
     copyModels();
     createCacheDir();
     getAstCache();
 }
Example #9
0
 /**
  * Constructor, specifying an input stream.
  *
  * @param in input stream
  * @param node parent node
  * @throws IOException I/O exception
  */
 PathNode(final DataInput in, final PathNode node) throws IOException {
   name = (short) in.readNum();
   kind = (byte) in.read();
   final int count = in.readNum();
   children = new PathNode[in.readNum()];
   if (in.readDouble() == 1) {
     // "1" indicates the format introduced with Version 7.1
     stats = new Stats(in);
   } else {
     // create old format
     stats = new Stats();
     stats.count = count;
   }
   parent = node;
   for (int c = 0; c < children.length; ++c) children[c] = new PathNode(in, this);
 }
Example #10
0
  private static int buildRings(
      final IScope scope,
      final IAgentFilter filter,
      final Double distance,
      final List<Double> rings,
      final Map<Double, Integer> ringsPn,
      final IAddressableContainer<Integer, IAgent, Integer, IAgent> agents) {

    IList<ILocation> locs = GamaListFactory.create(Types.POINT);
    for (IAgent ag : agents.iterable(scope)) {
      locs.add(ag.getLocation());
    }
    ILocation centralLoc = (ILocation) Stats.getMean(scope, locs);
    IAgent centralAg = scope.getTopology().getAgentClosestTo(scope, centralLoc, filter);
    List<IAgent> neighbors =
        distance == 0 || filter == null
            ? new ArrayList<IAgent>()
            : new ArrayList<IAgent>(
                scope.getTopology().getNeighborsOf(scope, centralAg, distance, filter));

    for (IAgent ag : neighbors) {
      double dist = centralLoc.euclidianDistanceTo(ag.getLocation());
      if (dist == 0) {
        continue;
      }
      if (!rings.contains(dist)) {
        rings.add(dist);
        ringsPn.put(dist, 1);
      } else {
        ringsPn.put(dist, 1 + ringsPn.get(dist));
      }
    }
    Collections.sort(rings);

    for (int i = 1; i < rings.size(); i++) {
      double dist = rings.get(i);
      double dist1 = rings.get(i - 1);
      ringsPn.put(dist, ringsPn.get(dist) + ringsPn.get(dist1));
    }

    return rings.size();
  }
Example #11
0
 void finish() {
   long elapsed = System.nanoTime() - startTime;
   Object st = accum.get(name);
   if (st == null) accum.put(name, new Stats(elapsed, numOps));
   else ((Stats) st).addTime(elapsed, numOps);
 }
  /**
   * Run the pass <code>pass</code> on the job. Before running the pass on the job, if the job is a
   * <code>SourceJob</code>, then this method will ensure that the scheduling invariants are
   * enforced by calling <code>enforceInvariants</code>.
   */
  protected void runPass(Job job, Pass pass) throws CyclicDependencyException {
    // make sure that all scheduling invariants are satisfied before running
    // the next pass. We may thus execute some other passes on other
    // jobs running the given pass.
    try {
      enforceInvariants(job, pass);
    } catch (CyclicDependencyException e) {
      // A job that depends on this job is still running
      // an earlier pass.  We cannot continue this pass,
      // but we can just silently fail since the job we're
      // that depends on this one will eventually try
      // to run this pass again when it reaches a barrier.
      return;
    }

    if (getOptions().disable_passes.contains(pass.name())) {
      if (Report.should_report(Report.frontend, 1)) Report.report(1, "Skipping pass " + pass);
      job.finishPass(pass, true);
      return;
    }

    if (Report.should_report(Report.frontend, 1))
      Report.report(1, "Trying to run pass " + pass + " in " + job);

    if (job.isRunning()) {
      // We're currently running.  We can't reach the goal.
      throw new CyclicDependencyException(job + " cannot reach pass " + pass);
    }

    pass.resetTimers();

    boolean result = false;
    if (job.status()) {
      Job oldCurrentJob = this.currentJob;
      this.currentJob = job;
      Report.should_report.push(pass.name());

      // Stop the timer on the old pass. */
      Pass oldPass = oldCurrentJob != null ? oldCurrentJob.runningPass() : null;

      if (oldPass != null) {
        oldPass.toggleTimers(true);
      }

      job.setRunningPass(pass);
      pass.toggleTimers(false);

      result = pass.run();

      pass.toggleTimers(false);
      job.setRunningPass(null);

      Report.should_report.pop();
      this.currentJob = oldCurrentJob;

      // Restart the timer on the old pass. */
      if (oldPass != null) {
        oldPass.toggleTimers(true);
      }

      // pretty-print this pass if we need to.
      if (getOptions().print_ast.contains(pass.name())) {
        System.err.println("--------------------------------" + "--------------------------------");
        System.err.println("Pretty-printing AST for " + job + " after " + pass.name());

        PrettyPrinter pp = new PrettyPrinter();
        pp.printAst(job.ast(), new CodeWriter(System.err, 78));
      }

      // dump this pass if we need to.
      if (getOptions().dump_ast.contains(pass.name())) {
        System.err.println("--------------------------------" + "--------------------------------");
        System.err.println("Dumping AST for " + job + " after " + pass.name());

        NodeVisitor dumper = new DumpAst(new CodeWriter(System.err, 78));
        dumper = dumper.begin();
        job.ast().visit(dumper);
        dumper.finish();
      }

      // This seems to work around a VM bug on linux with JDK
      // 1.4.0.  The mark-sweep collector will sometimes crash.
      // Running the GC explicitly here makes the bug go away.
      // If this fails, maybe run with bigger heap.

      // System.gc();
    }

    Stats stats = getStats();
    stats.accumPassTimes(pass.id(), pass.inclusiveTime(), pass.exclusiveTime());

    if (Report.should_report(Report.time, 2)) {
      Report.report(
          2,
          "Finished "
              + pass
              + " status="
              + str(result)
              + " inclusive_time="
              + pass.inclusiveTime()
              + " exclusive_time="
              + pass.exclusiveTime());
    } else if (Report.should_report(Report.frontend, 1)) {
      Report.report(1, "Finished " + pass + " status=" + str(result));
    }

    job.finishPass(pass, result);
  }
Example #13
0
  private static void computeXaXsTransitions(
      final IScope scope,
      final IAgentFilter filter,
      final GamaMatrix<Double> fuzzytransitions,
      final Double distance,
      final IContainer<Integer, IAgent> agents,
      final int nbCat,
      final Map<List<Integer>, Map<Double, Double>> XaPerTransition,
      final Map<List<Integer>, Map<Double, Double>> XsPerTransition,
      final Set<Double> Xvals) {

    IList<ILocation> locs = GamaListFactory.create(Types.POINT);
    for (IAgent ag : agents.iterable(scope)) {
      locs.add(ag.getLocation());
    }
    ILocation centralLoc = (ILocation) Stats.getMean(scope, locs);
    if (filter != null) {
      IAgent centralAg = scope.getTopology().getAgentClosestTo(scope, centralLoc, filter);
      List<IAgent> neighbors =
          distance == 0
              ? new ArrayList<IAgent>()
              : new ArrayList<IAgent>(
                  scope.getTopology().getNeighborsOf(scope, centralAg, distance, filter));
      double sizeNorm = FastMath.sqrt(centralAg.getEnvelope().getArea());

      Map<IAgent, Double> distancesCoeff = new TOrderedHashMap<IAgent, Double>();
      distancesCoeff.put(centralAg, 1.0);
      for (IAgent ag : neighbors) {
        double euclidDist = centralAg.getLocation().euclidianDistanceTo(ag.getLocation());
        double dist = 1 / (1.0 + euclidDist / sizeNorm);
        distancesCoeff.put(ag, dist);
      }

      for (int i = 0; i < nbCat; i++) {
        for (int j = 0; j < nbCat; j++) {
          for (int k = 0; k < nbCat; k++) {
            List<Integer> ca = new ArrayList();
            ca.add(i);
            ca.add(j);
            ca.add(k);
            double xa = 0;
            double xs = 0;
            for (IAgent ag : distancesCoeff.keySet()) {
              double dist = distancesCoeff.get(ag);
              double xatmp = fuzzyTransition(scope, fuzzytransitions, nbCat, i, k, i, j) * dist;
              double xstmp = fuzzyTransition(scope, fuzzytransitions, nbCat, i, j, i, k) * dist;
              if (xatmp > xa) {
                xa = xatmp;
              }
              if (xstmp > xs) {
                xs = xstmp;
              }
            }
            if (xa > 0) {

              Map<Double, Double> mapxa = XaPerTransition.get(ca);
              if (mapxa == null) {
                mapxa = new TOrderedHashMap<Double, Double>();
                mapxa.put(xa, 1.0);
                XaPerTransition.put(ca, mapxa);
              } else {
                if (mapxa.containsKey(xa)) {
                  mapxa.put(xa, mapxa.get(xa) + 1.0);
                } else {
                  mapxa.put(xa, 1.0);
                }
              }
              Xvals.add(xa);
            }
            if (xs > 0) {
              Map<Double, Double> mapxs = XsPerTransition.get(ca);
              if (mapxs == null) {
                mapxs = new TOrderedHashMap<Double, Double>();
                mapxs.put(xs, 1.0);
                XsPerTransition.put(ca, mapxs);
              } else {
                if (mapxs.containsKey(xa)) {
                  mapxs.put(xs, mapxs.get(xs) + 1.0);
                } else {
                  mapxs.put(xs, 1.0);
                }
              }
              Xvals.add(xs);
            }
          }
        }
      }
    }
  }
Example #14
0
  public void integrateObservation(int[] succState, float currFitScore) {
    // If this is the first observation of the round
    if (state == null) {
      state = succState;
      action = new boolean[Environment.numberOfKeys];
      prevFitScore = 0;
      bestScore = 0;
      possibleActions = getPossibleActions(environment);

      // Unpack Values
      if (learnedParams.containsKey("weights")) {
        iter = (Iteration) learnedParams.get("iter");
        rm = (ReplayMemory) learnedParams.get("rm");
        weights = (HashMap<String, double[][]>) learnedParams.get("weights");
        System.out.println("Starting Simulation at iteration : " + Integer.toString(iter.value));
      } else {
        // If this is the first observation of the simulation/trials
        rm = new ReplayMemory(GlobalOptions.replaySize);
        weights = new HashMap<String, double[][]>();
        iter = new Iteration(1);
        learnedParams.put("weights", weights);
        learnedParams.put("rm", rm);
        learnedParams.put("iter", iter);
      }

      if (net == null) {
        numFeatures = state.length + possibleActions.size() + 1;
        int numActions = possibleActions.size();

        // Network Architecture
        List<LayerSpec> layerSpecs = new ArrayList<LayerSpec>();
        // Layer 1:
        layerSpecs.add(
            new LayerSpec(LayerFactory.TYPE_FULLY_CONNECTED, numFeatures, GlobalOptions.h1Size));
        layerSpecs.add(
            new LayerSpec(LayerFactory.TYPE_RELU, GlobalOptions.batchSize, GlobalOptions.h1Size));
        // Layer 2:
        layerSpecs.add(
            new LayerSpec(
                LayerFactory.TYPE_FULLY_CONNECTED, GlobalOptions.h1Size, GlobalOptions.h2Size));
        layerSpecs.add(
            new LayerSpec(LayerFactory.TYPE_RELU, GlobalOptions.batchSize, GlobalOptions.h2Size));
        // Layer 3:
        layerSpecs.add(new LayerSpec(LayerFactory.TYPE_FULLY_CONNECTED, GlobalOptions.h2Size, 1));

        net = new NeuralNet(layerSpecs, weights);
      }
    }

    // state and action denote (s,a) while succState and succAction denote (s'a')
    // Reward denotes r
    StateActionPair SAP = new StateActionPair(state, action);
    boolean[] succAction = findBestAction(environment, succState);
    StateActionPair succSAP = new StateActionPair(succState, succAction);
    double succBestScore = evalScore(succSAP);

    float reward = currFitScore - prevFitScore;
    if (GlobalOptions.useIndicatorRewards) {
      if (reward != 0) reward = reward > 0 ? 1.0f : -1.0f;
    }

    double trueScore = reward + GlobalOptions.dicount * succBestScore;
    rm.addMemory(extractFeatures(SAP)[0], trueScore);

    // Annealed learning rate and epsilon greedy
    if (iter.value % GlobalOptions.DECAY_STEP == 0
        && !GlobalOptions.testTime
        && GlobalOptions.LR > GlobalOptions.MIN_LR) {
      GlobalOptions.LR = GlobalOptions.LR * GlobalOptions.decayFactor;
      // RANDOM_ACTION_EPSILON = RANDOM_ACTION_EPSILON * DECAY_FACTOR;
      System.out.println(
          "Decay Step - LR : "
              + Double.toString(GlobalOptions.LR)
              + " Epsilon : "
              + Double.toString(randomJump));
    }

    // only do this update on every n-th iteration
    if (iter.value % GlobalOptions.UPDATE_INTERVAL == 0 && !GlobalOptions.testTime) {
      List<double[][]> batch = rm.sample(GlobalOptions.batchSize);
      double[][] trainX = batch.get(0);
      double[][] trainy = batch.get(1);
      double[][] pred = net.forward(trainX);
      double[][] trainError = Matrix.subtract(pred, trainy);
      double regError = 0.5 * GlobalOptions.regularizationLamda * net.getWeightSq();
      trainError = Matrix.scalarAdd(trainError, regError);
      net.backprop(trainError, GlobalOptions.LR, GlobalOptions.regularizationLamda);
    }

    if (iter.value % GlobalOptions.STAT_INTERVAL == 0 && !GlobalOptions.testTime) {
      // Print learning statistics - on every nth iteration
      double error = (evalScore(SAP) - trueScore);
      stats.addError(error);
      stats.addWeights(net);
      stats.addLearningRate(GlobalOptions.LR);
      stats.addEpsilonGreedy(randomJump);
      stats.flush();
    }

    // Update Persistent Parameters
    iter.value++;
    state = succState;
    action = succAction;
    prevFitScore = currFitScore;
  }
  /**
   * Constructor to create a character
   *
   * @param x X Position
   * @param y Y Position
   * @param w Width of Image
   * @param h Height of Image
   * @param FileN Name of image file
   * @param S Max number of frames
   */
  public GameCharacter(
      double x, double y, double w, double h, String FileN, int S, int Ty, String c) {
    // Set position and size
    X = x;
    Y = y;
    W = w;
    H = h;

    BASIC_PROCESS = new ProgressBar(new Font("Arial", 36, 36), this);
    BASIC_EFFECTS = new ProgressBar(new Font("Arial", 36, 36), this);
    // Add magic attacks
    // Fireball
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i] = new MagicAttack(-500, -500, 39, 41, "Fireball.png", 3, 1, 2, "Fireball");
      FIREBALL[i].STATS.setStats(new String[] {"Damage=10", "Points=10"});
      FIREBALL[i].CASTER = this;
    }
    // Shock
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i] = new MagicAttack(-500, -500, 39, 41, "Shock.png", 2, 1, 0, "Shock");
      SHOCK[i].STATS.setStats(new String[] {"Damage=20", "Points=15"});
      SHOCK[i].CASTER = this;
    }
    // Darkness
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i] = new MagicAttack(-500, -500, 165, 164, "Darkness.png", 3, 1, 2, "Darkness");
      DARKNESS[i].STATS.setStats(new String[] {"Damage=100", "Points=50"});
      DARKNESS[i].CASTER = this;
    }
    // Life Drain
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i] = new MagicAttack(-500, -500, 32, 32, "Life Drain.png", 7, 1, 0, "Life Drain");
      LIFE_DRAIN[i].STATS.setStats(new String[] {"Damage=50", "Points=25"});
      LIFE_DRAIN[i].CASTER = this;
    }
    // Get Image
    try {

      if (isJar()) {
        // Character
        imgCHARAC = getImage("/Graphics/Character/", FileN);

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = getImage("/Graphics/Effects/", "Dead" + BloodType + ".png");

        // Quest
        imgQStart = getImage("/Graphics/Effects/", "Quest_Start.png");
        imgQEnd = getImage("/Graphics/Effects/", "Quest_Complete.png");

      } else {
        // Character
        imgCHARAC = ImageIO.read(Paths.get(DIRECT + FileN).toFile());

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = ImageIO.read(Paths.get(DIRECT2 + "Dead" + BloodType + ".png").toFile());

        // Quest
        imgQStart = ImageIO.read(Paths.get(DIRECT2 + "Quest_Start.png").toFile());
        imgQEnd = ImageIO.read(Paths.get(DIRECT2 + "Quest_Complete.png").toFile());
      }

    } catch (Exception e) {
    }

    // Max number of frames
    SIZE = S;

    // Sprite type
    TYPE = Ty;

    // Assign class
    CLASS = c;
    Cl = c;

    // Add items and attacks according to class
    if (CLASS.equals("Player")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Wooden Staff",
          20,
          1,
          "Staff_1.png",
          "Meele",
          new String[] {"Damage=5", "Attack Speed=1"});

      // Equip items
      INVENTORY.ItemEffect(1, this);
      // MEELE_WEAPON=null;
      // Assign Magic
      SPELL_LIST.add(FIREBALL);

      // Inventory type
      INVENTORY.Type = "Player";
    } else if (CLASS.equals("Citizen")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 5);

      INVENTORY.Type = "Friendly";
    } else if (CLASS.equals("Blacksmith")) {

      // Add items
      INVENTORY.addItem(
          "Silver Dagger",
          250,
          1,
          "Dagger_3.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Steel Dagger",
          450,
          1,
          "Dagger_5.png",
          "Meele",
          new String[] {"Damage=35", "Attack Speed=1"});
      // INVENTORY.addItem("Assassin blade", 750,1, "Dagger_6.png","Meele",new
      // String[]{"Damage=45","Attack Speed=1"});
      // INVENTORY.addItem("Serpent Dagger", 5000,1, "Dagger_2.png","Meele",new
      // String[]{"Damage=50","Attack Speed=1"});
      // INVENTORY.addItem("Dagger of Time", 5050,1, "Dagger_1.png","Meele",new
      // String[]{"Damage=75","Attack Speed=1"});

      INVENTORY.addItem(
          "Steel Sword",
          450,
          1,
          "Sword_1.png",
          "Meele",
          new String[] {"Damage=30", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Silver Sword",
          100,
          1,
          "Sword_5.png",
          "Meele",
          new String[] {"Damage=20", "Attack Speed=0.5"});
      // INVENTORY.addItem("Iron Scimitar", 150,1, "Sword_7.png","Meele",new
      // String[]{"Damage=15","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Scimitar", 500,1, "Sword_4.png","Meele",new
      // String[]{"Damage=50","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Katana", 450,1, "Sword_6.png","Meele",new
      // String[]{"Damage=40","Attack Speed=0.95"});
      // INVENTORY.addItem("Butcher's Sword", 5000,1, "Sword_3.png","Meele",new
      // String[]{"Damage=100","Attack Speed=0.55"});
      // INVENTORY.addItem("Blood Thirster", 6000,1, "Sword_8.png","Meele",new
      // String[]{"Damage=200","Attack Speed=0.75"});

      INVENTORY.addItem(
          "Iron Hammer",
          150,
          1,
          "Hammer_1.png",
          "Meele",
          new String[] {"Damage=40", "Attack Speed=0.15"});
      // INVENTORY.addItem("Steel Hammer", 450,1, "Hammer_0.png","Meele",new
      // String[]{"Damage=60","Attack Speed=0.15"});
      // INVENTORY.addItem("Iron Mace", 50,1, "Mace_1.png","Meele",new String[]{"Damage=15","Attack
      // Speed=0.5"});

      INVENTORY.addItem("Steel Helmet", 250, 1, "Head_1.png", "H_armor", new String[] {"Armor=20"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});
      // INVENTORY.addItem("Iron Horn Helmet", 350,1, "Head_6.png","H_armor",new
      // String[]{"Armor=50","Magic Resist=0"});
      // INVENTORY.addItem("Steel Horn Helmet", 500,1, "Head_7.png","H_armor",new
      // String[]{"Armor=80","Magic Resist=0"});
      // INVENTORY.addItem("Skysteel Helmet", 4000,1, "Head_4.png","H_armor",new
      // String[]{"Armor=60","Magic Resist=25"});

      INVENTORY.addItem(
          "Iron Cuirass", 250, 1, "Chest_4.png", "C_armor", new String[] {"Armor=20"});
      INVENTORY.addItem(
          "Steel Cuirass", 350, 1, "Chest_1.png", "C_armor", new String[] {"Armor=30"});
      // INVENTORY.addItem("Scale Cuirass", 550,1, "Chest_3.png","C_armor",new
      // String[]{"Armor=50"});
      // INVENTORY.addItem("Dark metal Cuirass", 750,1, "Chest_6.png","C_armor",new
      // String[]{"Armor=70"});
      // INVENTORY.addItem("Master Cuirass", 3050,1, "Chest_5.png","C_armor",new
      // String[]{"Armor=80","Magic Resist=25"});
      // INVENTORY.addItem("Legendary Cuirass", 3050,1, "Chest_2.png","C_armor",new
      // String[]{"Armor=100","Magic Resist=100"});

      INVENTORY.addItem(
          "Wooden Shield",
          50,
          1,
          "Shield_1.png",
          "Shield",
          new String[] {"Armor=5", "Magic Resist=0"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

      // Set Stats
      STATS.setStats(new String[] {"Level = 5 "});
      MAX_HEALTH = 200;
      HEALTH = (int) MAX_HEALTH;
    } else if (CLASS.equals("Alchemist")) {
      // Add Items
      INVENTORY.addItem(
          "Health Potion", 25, 50, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Mana Potion", 20, 50, "Mana Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Speed Potion", 10, 50, "Speed Pot.png", "Potion", new String[] {"Points=5"});
      // INVENTORY.addItem("Invisib Potion", 50, 10, "Invisibility Pot.png","Potion",new
      // String[]{"Points=5"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Inn Keeper")) {
      // Add Items
      INVENTORY.addItem("Roasted Fish", 15, 10, "Fish.png", "Food", new String[] {"Points=5"});
      INVENTORY.addItem("Apple", 15, 10, "Apple.png", "Food", new String[] {"Points=2"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Mage")) {

      INVENTORY.addItem(
          "Leather Cap",
          250,
          1,
          "Head_8.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=25"});
      INVENTORY.addItem(
          "Dark Leather Cap",
          300,
          1,
          "Head_9.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=50"});
      // INVENTORY.addItem("Jesters Cap", 500,1, "Head_5.png","H_armor",new
      // String[]{"Armor=10","Magic Resist=90"});
      // INVENTORY.addItem("Skull Helmet", 5000,1, "Head_3.png","H_armor",new
      // String[]{"Armor=100","Magic Resist=100"});
      INVENTORY.addItem(
          "Shock Spell Stone",
          250,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + SHOCK[0].STATS.DAMAGE});
      // INVENTORY.addItem("Darkness Spell Stone", 500,1, "Stone_1.png","SpellStoner",new
      // String[]{"Damage="+DARKNESS[0].STATS.DAMAGE});
      INVENTORY.addItem(
          "Life Drain Spell Stone",
          300,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + LIFE_DRAIN[0].STATS.DAMAGE});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

    } else if (CLASS.equals("Skeleton")) {

      // Add items
      INVENTORY.addItem(
          "Bone Club", 5, 1, "Mace_2.png", "Meele", new String[] {"Damage=5", "Attack Speed=1"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 10 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Skeleton Chieftan")) {

      // Add Item
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 50 + 25);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Assign Stats
      STATS.LEVEL = 3;
      HEALTH = 250;
      MAX_HEALTH = 250;

      // Opify
      Opify(1 / 1.25);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Shaman")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

    } else if (CLASS.equals("Dark Elf")) {

      // Add items
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});

      // Assign Stats
      STATS.LEVEL = 2;
      HEALTH = 150;
      MAX_HEALTH = 150;

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);
      INVENTORY.ItemEffect(1, this);

      // Add Ai
      EAI = new EnemyAI(this);

    } else if (CLASS.equals("Prisoner")) {
      INVENTORY.addItem("Key", 0, 1, "Key.png", "Key", new String[] {});
      // NAI= new NPCAI(this);
    }
  }
Example #16
0
  /** Retrieves statistics data based on app usage */
  public Stats getStats() {
    Stats mStats = new Stats();

    // Categories
    mStats.setCategories(getCategories().size());

    // Everything about notes and their text stats
    int notesActive = 0,
        notesArchived = 0,
        notesTrashed = 0,
        reminders = 0,
        remindersFuture = 0,
        checklists = 0,
        notesMasked = 0,
        tags = 0,
        locations = 0;
    int totalWords = 0, totalChars = 0, maxWords = 0, maxChars = 0, avgWords = 0, avgChars = 0;
    int words, chars;
    List<Note> notes = getAllNotes(false);
    for (Note note : notes) {
      if (note.isTrashed()) {
        notesTrashed++;
      } else if (note.isArchived()) {
        notesArchived++;
      } else {
        notesActive++;
      }
      if (note.getAlarm() != null && Long.parseLong(note.getAlarm()) > 0) {
        if (Long.parseLong(note.getAlarm()) > Calendar.getInstance().getTimeInMillis()) {
          remindersFuture++;
        } else {
          reminders++;
        }
      }
      if (note.isChecklist()) {
        checklists++;
      }
      if (note.isLocked()) {
        notesMasked++;
      }
      tags += TagsHelper.retrieveTags(note).size();
      if (note.getLongitude() != null && note.getLongitude() != 0) {
        locations++;
      }
      words = getWords(note);
      chars = getChars(note);
      if (words > maxWords) {
        maxWords = words;
      }
      if (chars > maxChars) {
        maxChars = chars;
      }
      totalWords += words;
      totalChars += chars;
    }
    mStats.setNotesActive(notesActive);
    mStats.setNotesArchived(notesArchived);
    mStats.setNotesTrashed(notesTrashed);
    mStats.setReminders(reminders);
    mStats.setRemindersFutures(remindersFuture);
    mStats.setNotesChecklist(checklists);
    mStats.setNotesMasked(notesMasked);
    mStats.setTags(tags);
    mStats.setLocation(locations);
    avgWords = totalWords / (notes.size() != 0 ? notes.size() : 1);
    avgChars = totalChars / (notes.size() != 0 ? notes.size() : 1);

    mStats.setWords(totalWords);
    mStats.setWordsMax(maxWords);
    mStats.setWordsAvg(avgWords);
    mStats.setChars(totalChars);
    mStats.setCharsMax(maxChars);
    mStats.setCharsAvg(avgChars);

    // Everything about attachments
    int attachmentsAll = 0, images = 0, videos = 0, audioRecordings = 0, sketches = 0, files = 0;
    List<Attachment> attachments = getAllAttachments();
    for (Attachment attachment : attachments) {
      if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())) {
        images++;
      } else if (Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
        videos++;
      } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
        audioRecordings++;
      } else if (Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())) {
        sketches++;
      } else if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {
        files++;
      }
    }
    mStats.setAttachments(attachmentsAll);
    mStats.setImages(images);
    mStats.setVideos(videos);
    mStats.setAudioRecordings(audioRecordings);
    mStats.setSketches(sketches);
    mStats.setFiles(files);

    return mStats;
  }