public void loadTree() {
   System.out.println("Loading tree");
   StreamTokenizer stream = null;
   try {
     FileInputStream f = new FileInputStream(tree);
     Reader input = new BufferedReader(new InputStreamReader(f));
     stream = new StreamTokenizer(input);
     stream.resetSyntax();
     stream.wordChars(32, 127);
   } catch (Exception e) {
     System.out.println("Error opening " + tree);
     System.exit(1);
   }
   list = new ArrayList();
   try {
     // read the file to the end
     while (stream.nextToken() != StreamTokenizer.TT_EOF) {
       // is a word being read
       if (stream.ttype == StreamTokenizer.TT_WORD) {
         list.add(new String(stream.sval));
       }
       // is a number being read
       if (stream.ttype == StreamTokenizer.TT_NUMBER) {
         list.add(new Double(stream.nval));
       }
     }
   } catch (Exception e) {
     System.out.println("\nError reading " + tree + ". Exiting...");
     System.exit(1);
   }
 }
  public void createBuildings() {
    bList = new ArrayList<Building>();

    // resource
    bList.add(new Building("Gold Mine", 3, 3, 960, 7));
    bList.add(new Building("Elixir Collector", 3, 3, 960, 7));
    // bList.add(new Building("Dark Elixir Drill", 3, 3, 1160, 3));
    bList.add(new Building("Gold Storage", 3, 3, 2100, 4));
    bList.add(new Building("Elixir Storage", 3, 3, 2100, 4));
    // bList.add(new Building("Dark Elixir Storage", 3, 3, 3200, 1));
    // bList.add(new Building("Builder Hut", 2, 2, 250, 5));

    // army
    bList.add(new Building("Army Camp", 5, 5, 500, 4));
    bList.add(new Building("Barracks", 3, 3, 860, 4));
    // bList.add(new Building("Dark Barracks", 3, 3, 900, 2));
    // bList.add(new Building("Laboratory", 4, 4, 950, 1));
    // bList.add(new Building("Spell Factory", 3, 3, 615, 1));
    // bList.add(new Building("Barbarian King Altar", 3, 3, 250, 1));
    // bList.add(new Building("Dark Spell Factory", 3, 3, 750, 1));
    // bList.add(new Building("Archer Queen Altar", 3, 3, 250, 1));

    // other
    bList.add(new Building("Town Hall", 4, 4, 5500, 1));
    bList.add(new Building("Clan Castle", 3, 3, 3400, 1));

    // defense
    bList.add(new Building("Archer Tower", 3, 3, 1050, 7));
    bList.add(new Building("Cannon", 3, 3, 1260, 6));
    bList.add(new Building("Wall", 1, 1, 7000, 275));
    // bList.add(new Building("Air Sweeper", 2, 2, 1000, 2));
    // bList.add(new Building("Cannon", 3, 3, 1260, 6));
    // bList.add(new Building("Cannon", 3, 3, 1260, 6));
  }
  public void updatePickups() {
    for (int i = 0; i < pickupList.size(); i++) {
      if (pickupList.get(i).pickedUp) pickupList.remove(i);
    } // end for

    while (pickupList.size() < startNumPickups) pickupList.add(new Pickup(frameWidth, frameHeight));
  } // end updatePickups
  public void draw(node leaf, Graphics2D g, int px, int py) {
    int lvl = leaf.getLevel();
    double l = lvl;
    counts[lvl]++;

    double xfraq = counts[lvl] / (spacing[lvl] + 1);
    double yfraq = l / depth;
    int x = new Double(1600 * xfraq).intValue();
    int y = new Double(1200 * yfraq).intValue() + 10;

    if (leaf.getAttr() != null) {
      g.drawString(leaf.getAttr(), x - 20, y);
    }
    if (leaf.getCrit() != null) {
      g.drawString(leaf.getCrit(), x - 20, y + 10);
    }
    if (leaf.getResult() != null) {
      g.drawString(leaf.getResult(), x - 20, y + 10);
    }
    g.drawLine(x, y, px, py);
    // g.fillRect(x,y,20,20);
    ArrayList children = leaf.getChildren();
    while (!children.isEmpty()) {
      draw((node) children.remove(0), g, x, y);
    }
  }
Exemple #5
0
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
  public void setup() {
    size(600, 400);
    smooth();
    f = createFont("Georgia", 12, true);

    obstacles = new ArrayList();
    boids = new ArrayList();

    // A little algorithm to pick a bunch of random obstacles that don't overlap
    for (int i = 0; i < 100; i++) {
      float x = random(width);
      float y = random(height);
      float r = random(50 - i / 2, 50);
      boolean ok = true;
      for (int j = 0; j < obstacles.size(); j++) {
        Obstacle o = (Obstacle) obstacles.get(j);
        if (dist(x, y, o.loc.x, o.loc.y) < o.radius + r + 20) {
          ok = false;
        }
      }
      if (ok) obstacles.add(new Obstacle(x, y, r));
    }

    // Starting with three boids
    boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.2f));
    boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.1f));
    boids.add(new Boid(new PVector(random(width), random(height)), 2f, 0.05f));
  }
  public Iterator handlePixels(Image img, Rectangle rect) {
    int x = rect.x;
    int y = rect.y;
    int w = rect.width;
    int h = rect.height;

    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
    try {
      pg.grabPixels();
    } catch (InterruptedException e) {
      System.err.println("interrupted waiting for pixels!");
      return null;
    }
    if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
      System.err.println("image fetch aborted or errored");
      return null;
    }
    ArrayList tmpList = new ArrayList();
    for (int j = 0; j < h; j++) {
      for (int i = 0; i < w; i++) {
        tmpList.add(handleSinglePixel(x + i, y + j, pixels[j * w + i]));
      }
    }
    return tmpList.iterator();
  }
 public void draw(Graphics g, ImagesLoader imLoad) {
   for (int i = 0; i < pickupList.size(); i++) {
     Pickup p = pickupList.get(i);
     BufferedImage img = imLoad.getImage(p.type);
     g.drawImage(img, (int) p.x, (int) p.y, null);
   } // end for
 } // end draw
  public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    if (dst == null) dst = createCompatibleDestImage(src, null);

    int width = src.getWidth();
    int height = src.getHeight();
    int numScratches = (int) (density * width * height / 100);
    ArrayList<Line2D> lines = new ArrayList<Line2D>();
    {
      float l = length * width;
      Random random = new Random(seed);
      Graphics2D g = dst.createGraphics();
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g.setColor(new Color(color));
      g.setStroke(new BasicStroke(this.width));
      for (int i = 0; i < numScratches; i++) {
        float x = width * random.nextFloat();
        float y = height * random.nextFloat();
        float a = angle + ImageMath.TWO_PI * (angleVariation * (random.nextFloat() - 0.5f));
        float s = (float) Math.sin(a) * l;
        float c = (float) Math.cos(a) * l;
        float x1 = x - c;
        float y1 = y - s;
        float x2 = x + c;
        float y2 = y + s;
        g.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
        lines.add(new Line2D.Float(x1, y1, x2, y2));
      }
      g.dispose();
    }

    if (false) {
      //		int[] inPixels = getRGB( src, 0, 0, width, height, null );
      int[] inPixels = new int[width * height];
      int index = 0;
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          float sx = x, sy = y;
          for (int i = 0; i < numScratches; i++) {
            Line2D.Float l = (Line2D.Float) lines.get(i);
            float dot = (l.x2 - l.x1) * (sx - l.x1) + (l.y2 - l.y1) * (sy - l.y1);
            if (dot > 0) inPixels[index] |= (1 << i);
          }
          index++;
        }
      }

      Colormap colormap = new LinearColormap();
      index = 0;
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          float f = (float) (inPixels[index] & 0x7fffffff) / 0x7fffffff;
          inPixels[index] = colormap.getColor(f);
          index++;
        }
      }
      setRGB(dst, 0, 0, width, height, inPixels);
    }
    return dst;
  }
    public void avoid(ArrayList obstacles) {

      // Make a vector that will be the position of the object
      // relative to the Boid rotated in the direction of boid's velocity
      PVector closestRotated = new PVector(sight + 1, sight + 1);
      float closestDistance = 99999;
      Obstacle avoid = null;

      // Let's look at each obstacle
      for (int i = 0; i < obstacles.size(); i++) {
        Obstacle o = (Obstacle) obstacles.get(i);

        float d = PVector.dist(loc, o.loc);
        PVector dir = vel.get();
        dir.normalize();
        PVector diff = PVector.sub(o.loc, loc);

        // Now we use the dot product to rotate the vector that points from boid to obstacle
        // Velocity is the new x-axis
        PVector rotated = new PVector(diff.dot(dir), diff.dot(getNormal(dir)));

        // Is the obstacle in our path?
        if (PApplet.abs(rotated.y) < (o.radius + r)) {
          // Is it the closest obstacle?
          if ((rotated.x > 0) && (rotated.x < closestRotated.x)) {
            closestRotated = rotated;
            avoid = o;
          }
        }
      }

      // Can we actually see the closest one?
      if (PApplet.abs(closestRotated.x) < sight) {

        // The desired vector should point away from the obstacle
        // The closer to the obstacle, the more it should steer
        PVector desired =
            new PVector(closestRotated.x, -closestRotated.y * sight / closestRotated.x);
        desired.normalize();
        desired.mult(closestDistance);
        desired.limit(maxspeed);
        // Rotate back to the regular coordinate system
        rotateVector(desired, vel.heading2D());

        // Draw some debugging stuff
        if (debug) {
          stroke(0);
          line(loc.x, loc.y, loc.x + desired.x * 10, loc.y + desired.y * 10);
          avoid.highlight(true);
        }

        // Apply Reynolds steering rules
        desired.sub(vel);
        desired.limit(maxforce);
        acc.add(desired);
      }
    }
  public void draw() {

    background(255);

    for (int i = 0; i < balls.size(); i++) {
      Ball ball = (Ball) balls.get(i);
      ball.calc();
      ball.display();
    }
  }
Exemple #12
0
  /** Update all of the Ball's and draw them */
  public void update() {

    if (balls.size() != 0) {

      for (int i = 0; i < balls.size(); i++) {
        Ball b = (Ball) balls.get(i);
        b.update();
        b.attract = kelly;
        b.drawBall();
      }
    }
  }
 public void plotProjection(ArrayList<double[]> pballs) {
   for (int i = 0; i < pballs.size(); i++) {
     double xyzt[] = pballs.get(i);
     // switch y and z;
     double temp = xyzt[2];
     xyzt[2] = xyzt[1];
     xyzt[1] = temp;
     Point3D realWorld = new Point3D(xyzt[0], xyzt[1], xyzt[2]);
     // Point pixCoords = depthgetPixFromWorld(realWorld);
     // depthImg.setRGB(pixCoords.x,pixCoords.y,0xFFFFFFFF);
   }
 }
 public void trav(ArrayList nodes, node cur) {
   node temp;
   while (!nodes.isEmpty()) {
     temp = (node) nodes.get(0);
     if (temp.getLevel() - 1 == cur.getLevel()) {
       nodes.remove(0);
       cur.addChild(temp);
       trav(nodes, temp);
     } else {
       return;
     }
   }
 }
Exemple #15
0
  private ArrayList GetFolderTree(String s_Dir, String s_Flag, int n_Indent, int n_TreeIndex) {
    String s_List = "";
    ArrayList aSubFolders = new ArrayList();

    File file = new File(s_Dir);
    File[] filelist = file.listFiles();

    if (filelist != null && filelist.length > 0) {
      for (int i = 0; i < filelist.length; i++) {
        if (filelist[i].isDirectory()) {
          aSubFolders.add(filelist[i].getName());
        }
      }

      int n_Count = aSubFolders.size();
      String s_LastFlag = "";
      String s_Folder = "";
      for (int i = 1; i <= n_Count; i++) {
        if (i < n_Count) {
          s_LastFlag = "0";
        } else {
          s_LastFlag = "1";
        }

        s_Folder = aSubFolders.get(i - 1).toString();
        s_List =
            s_List
                + "arr"
                + s_Flag
                + "["
                + String.valueOf(n_TreeIndex)
                + "]=new Array(\""
                + s_Folder
                + "\","
                + String.valueOf(n_Indent)
                + ", "
                + s_LastFlag
                + ");\n";
        n_TreeIndex = n_TreeIndex + 1;
        ArrayList a_Temp =
            GetFolderTree(s_Dir + s_Folder + sFileSeparator, s_Flag, n_Indent + 1, n_TreeIndex);
        s_List = s_List + a_Temp.get(0).toString();
        n_TreeIndex = Integer.valueOf(a_Temp.get(1).toString()).intValue();
      }
    }

    ArrayList a_Return = new ArrayList();
    a_Return.add(s_List);
    a_Return.add(String.valueOf(n_TreeIndex));
    return a_Return;
  }
Exemple #16
0
 /**
  * Gets the image contents of frame n.
  *
  * @return BufferedImage representation of frame, or null if n is invalid.
  */
 public BufferedImage getFrame(int n) {
   BufferedImage im = null;
   if ((n >= 0) && (n < frameCount)) {
     im = ((GifFrame) frames.get(n)).image;
   }
   return im;
 }
Exemple #17
0
  /** Print it! */
  public String printClusters(Cluster clustering, float threshold, HTMLFile f) {
    int maxSize = 0;

    ArrayList<Cluster> clusters = getClusters(clustering, threshold);

    for (Iterator<Cluster> i = clusters.iterator(); i.hasNext(); ) {
      Cluster cluster = i.next();
      if (cluster.size() > maxSize) maxSize = cluster.size();
    }

    TreeSet<Cluster> sorted = new TreeSet<Cluster>(clusters);
    clusters = null;

    // Now print them:
    return outputClustering(f, sorted, maxSize);
  }
Exemple #18
0
 public void drawCluster(Cluster cluster) {
   int index = clusters.indexOf(cluster);
   if (index != -1) {
     cluster.y = maxY;
     cluster.x = minX + index * factor;
     if (cluster.size() > 1) g.setColor(Color.RED);
     else g.setColor(Color.BLACK);
     g.drawRect(cluster.x - 1, cluster.y - cluster.size(), 2, 1 + cluster.size());
   } else {
     Cluster left = cluster.getLeft();
     Cluster right = cluster.getRight();
     drawCluster(left);
     drawCluster(right);
     int yBar = minY + (int) ((maxY - minY) * (cluster.getSimilarity() / threshold));
     g.setColor(Color.DARK_GRAY);
     if (left.y > yBar) {
       g.drawLine(left.x, left.y - 1, left.x, yBar);
       writeMap(left, yBar);
     }
     if (right.y > yBar) {
       g.drawLine(right.x, right.y - 1, right.x, yBar);
       writeMap(right, yBar);
     }
     g.setColor(Color.BLACK);
     g.drawLine(left.x, yBar, right.x, yBar);
     cluster.x = (right.x + left.x) / 2;
     cluster.y = yBar;
   }
 }
Exemple #19
0
  /** If a key is pressed perform the respective actions */
  public void keyPressed() {

    // Add 'stems' to the balls
    if (keyCode == SHIFT) {
      stems = !stems;
      for (int i = 0; i < balls.size(); i++) {
        Ball b = (Ball) balls.get(i);
        b.STEM = stems;
      }
    }
    // toggle repaint background
    else if (key == 'b') REPAINT = !REPAINT;
    // Empty the ArrayList of Balls
    else if (key == 'x') balls.clear();
    // Add a ball
    else if (key == 'f') addBall();
  }
Exemple #20
0
 /**
  * Gets display duration for specified frame.
  *
  * @param n int index of frame
  * @return delay in milliseconds
  */
 public int getDelay(int n) {
   //
   delay = -1;
   if ((n >= 0) && (n < frameCount)) {
     delay = ((GifFrame) frames.get(n)).delay;
   }
   return delay;
 }
Exemple #21
0
  /**
   * Loads into a double[][] a plain text file of numbers, with newlines dividing the numbers into
   * rows and tabs or spaces delimiting columns. The Y dimension is not flipped.
   */
  public static double[][] loadTextFile(InputStream stream) throws IOException {
    Scanner scan = new Scanner(stream);

    ArrayList rows = new ArrayList();
    int width = -1;

    while (scan.hasNextLine()) {
      String srow = scan.nextLine().trim();
      if (srow.length() > 0) {
        int w = 0;
        if (width == -1) // first time compute width
        {
          ArrayList firstRow = new ArrayList();
          Scanner rowScan = new Scanner(new StringReader(srow));
          while (rowScan.hasNextDouble()) {
            firstRow.add(new Double(rowScan.nextDouble())); // ugh, boxed
            w++;
          }
          width = w;
          double[] row = new double[width];
          for (int i = 0; i < width; i++) row[i] = ((Double) (firstRow.get(i))).doubleValue();
          rows.add(row);
        } else {
          double[] row = new double[width];
          Scanner rowScan = new Scanner(new StringReader(srow));
          while (rowScan.hasNextDouble()) {
            if (w == width) // uh oh
            throw new IOException("Row lengths do not match in text file");
            row[w] = rowScan.nextDouble();
            w++;
          }
          if (w < width) // uh oh
          throw new IOException("Row lengths do not match in text file");
          rows.add(row);
        }
      }
    }

    if (width == -1) // got nothing
    return new double[0][0];

    double[][] fieldTransposed = new double[rows.size()][];
    for (int i = 0; i < rows.size(); i++) fieldTransposed[i] = ((double[]) (rows.get(i)));

    // now transpose because we have width first
    double[][] field = new double[width][fieldTransposed.length];
    for (int i = 0; i < field.length; i++)
      for (int j = 0; j < field[i].length; j++) field[i][j] = fieldTransposed[j][i];

    return field;
  }
  public void recreateTree() {
    System.out.println("Recreating tree");
    ArrayList nodes = new ArrayList();
    String attr, crit, result;
    int level;
    node leaf;
    while (!list.isEmpty()) {
      if (((String) list.remove(0)).compareTo("Node") == 0) {
        leaf = new node();
        attr = (String) list.remove(0);
        // System.out.println("ATTR:"+attr);
        crit = (String) list.remove(0);
        try {
          level = (new Double(crit)).intValue();
          crit = null;
        } catch (Exception e) {
          // System.out.println("crit:"+crit);
          level = (new Double((String) list.remove(0))).intValue();
        }
        // System.out.println("lvl:"+level);
        if (level > depth) {
          depth = level;
        }
        if (((String) list.get(0)).compareTo("Node") != 0) {
          result = (String) list.remove(0);
          leaf.setResult(result);
        }
        leaf.setSplitCriteria(crit, 0);
        leaf.setLevel(level);
        leaf.setAttr(attr);

        if (attr.compareTo("_root") == 0) {
          root = leaf;
        } else {

          nodes.add(leaf);
        }
      }
    }
    depth++;
    levelCount(nodes);

    System.out.println("Linking " + nodes.size() + " tree nodes");
    trav(nodes, root);
  }
 public void levelCount(ArrayList nodes) {
   System.out.println("Doing level counts");
   spacing = new double[depth];
   for (int i = 0; i < depth; i++) {
     spacing[i] = 0;
   }
   spacing[0]++;
   node leaf;
   for (int i = 0; i < nodes.size(); i++) {
     leaf = (node) nodes.get(i);
     spacing[leaf.getLevel()]++;
   }
   max = 0;
   for (int i = 0; i < depth; i++) {
     if (spacing[i] > max) {
       max = spacing[i];
     }
     // System.out.println("Level "+i+" has "+spacing[i]+" nodes");
   }
 }
  public void setup() {
    size(320, 240);
    smooth();

    // Start with 10 balls
    balls = new ArrayList();
    for (int i = 0; i < 10; i++) {
      Ball ball = new Ball(random(width), random(height));
      balls.add(ball);
    }
  }
  public void draw() {
    background(255);

    // Turn off highlighting for all obstalces
    for (int i = 0; i < obstacles.size(); i++) {
      Obstacle o = (Obstacle) obstacles.get(i);
      o.highlight(false);
    }

    // Act on all boids
    for (int i = 0; i < boids.size(); i++) {
      Boid b = (Boid) boids.get(i);
      b.avoid(obstacles);
      b.run();
    }

    // Display the obstacles
    for (int i = 0; i < obstacles.size(); i++) {
      Obstacle o = (Obstacle) obstacles.get(i);
      o.display();
    }

    // Instructions
    textFont(f);
    fill(0);
    text(
        "Hit space bar to toggle debugging lines.\nClick the mouse to generate a new boids.",
        10,
        height - 30);
  }
  private void writeGeographicImageGeoKeys(ArrayList<TiffIFDEntry> ifds, AVList params)
      throws IOException {
    long offset = this.theChannel.position();

    if (isImage(params) && isGeographic(params)) {
      int epsg = GeoTiff.GCS.WGS_84;

      if (params.hasKey(AVKey.PROJECTION_EPSG_CODE))
        epsg = (Integer) params.getValue(AVKey.PROJECTION_EPSG_CODE);

      short[] values =
          new short[] {
            // GeoKeyDirectory header
            GeoTiff.GeoKeyHeader.KeyDirectoryVersion,
            GeoTiff.GeoKeyHeader.KeyRevision,
            GeoTiff.GeoKeyHeader.MinorRevision,
            0, // IMPORTANT!! we will update count below, after the array initialization
            // end of header -

            // geo keys array

            /* key 1 */
            GeoTiff.GeoKey.ModelType,
            0,
            1,
            GeoTiff.ModelType.Geographic,
            /* key 2 */
            GeoTiff.GeoKey.RasterType,
            0,
            1,
            (short) (0xFFFF & GeoTiff.RasterType.RasterPixelIsArea),
            /* key 3 */
            GeoTiff.GeoKey.GeographicType,
            0,
            1,
            (short) (0xFFFF & epsg),
            /* key 4 */
            GeoTiff.GeoKey.GeogAngularUnits,
            0,
            1,
            GeoTiff.Unit.Angular.Angular_Degree
          };

      // IMPORTANT!! update count - number of geokeys
      values[3] = (short) (values.length / 4);

      byte[] bytes = this.getBytes(values);
      this.theChannel.write(ByteBuffer.wrap(bytes));
      ifds.add(
          new TiffIFDEntry(GeoTiff.Tag.GEO_KEY_DIRECTORY, Tiff.Type.SHORT, values.length, offset));
    }
  }
Exemple #27
0
  /** Reads next frame image */
  protected void readImage() {
    ix = readShort(); // (sub)image position & size
    iy = readShort();
    iw = readShort();
    ih = readShort();

    int packed = read();
    lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
    interlace = (packed & 0x40) != 0; // 2 - interlace flag
    // 3 - sort flag
    // 4-5 - reserved
    lctSize = 2 << (packed & 7); // 6-8 - local color table size

    if (lctFlag) {
      lct = readColorTable(lctSize); // read table
      act = lct; // make local table active
    } else {
      act = gct; // make global table active
      if (bgIndex == transIndex) bgColor = 0;
    }
    int save = 0;
    if (transparency) {
      save = act[transIndex];
      act[transIndex] = 0; // set transparent color if specified
    }

    if (act == null) {
      status = STATUS_FORMAT_ERROR; // no color table defined
    }

    if (err()) return;

    decodeImageData(); // decode pixel data
    skip();

    if (err()) return;

    frameCount++;

    // create new image to receive frame data
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);

    setPixels(); // transfer pixel data to image

    frames.add(new GifFrame(image, delay)); // add image to frame list

    if (transparency) {
      act[transIndex] = save;
    }
    resetFrame();
  }
  public int getRandomImageNum() {
    if (images.size() <= images_used.size()) return -1;
    else {
      // Calculate, based on random, if we try to get from the new images
      boolean getFromNewImages;
      if (Math.random() * 100 < percentage_of_new_images) {
        getFromNewImages = true;
      } else {
        getFromNewImages = false;
      }

      int i;
      int j = 0;
      int tries = 0;
      while (true && tries < randomImageNum_maxTries) {
        // Always try the last added pictures
        if (images_nevershown.size() > 0
            && tries < (int) (randomImageNum_maxTries / 4) // Only use 1/4 of the tries here
        ) {
          i = images_nevershown.get(0);
          tries++;
        } else if (getFromNewImages
            && images_lastadded.size() > 0
            && tries < (int) (randomImageNum_maxTries / 2) // Only use 1/2 of the tries here
        ) {
          j = (int) (images_lastadded.size() * Math.random());
          i = images_lastadded.get(j);
          tries++;
        } else {
          // Random from the rest of the pictures
          i = (int) (Math.random() * images.size());
          tries++;
        }
        if (!images_used.contains((Integer) i)) return i;
      }

      System.out.println("Max tries in randomImageNum");
      return -1;
    }

    // Original:
    // return (int)(Math.random() * images.size());
  }
Exemple #29
0
  private ArrayList<Cluster> getClusters(Cluster clustering, float threshold) {
    ArrayList<Cluster> clusters = new ArrayList<Cluster>();

    // First determine the clusters
    Stack<Cluster> stack = new Stack<Cluster>();
    stack.push(clustering);
    while (!stack.empty()) {
      Cluster current = stack.pop();

      if (current.size() == 1) {
        clusters.add(current); // singleton clusters
      } else {
        if (current.getSimilarity() >= threshold) {
          clusters.add(current);
        } else {
          // current.size() != 1   !!!
          stack.push(current.getLeft());
          stack.push(current.getRight());
        }
      }
    }
    return clusters;
  }
Exemple #30
0
  void turnOnFadeLog() throws IOException {
    Global.log("Connecting to fade log...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.fadeLogPort() + "...");
      try {
        fadeLog = new ClientByteStream(ip, Global.fadeLogPort(), 12);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                String s = null;
                byte[] data = null;
                try {
                  data = fadeLog.read();
                  if (data == null) return;
                  s = fadeLog.readLine();
                } catch (IOException ex) {
                  System.err.println("Error reading from fade log: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (s == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                float x = bb.getFloat();
                float y = bb.getFloat();
                Color color = Global.IntToColor(bb.getInt());

                // if fade color is same as ship color, play power-up sound

                if (color.equals(getPlayerShip().fill)) Sounds.powerUp.play();

                fadeLog(s, x, y, color);
              }
            }));
  }