Exemplo n.º 1
0
 /**
  * With segmented selections, ignore first mouse up and finalize when user double-clicks,
  * control-clicks or clicks in start box.
  */
 protected void handleMouseUp(int sx, int sy) {
   if (state == MOVING) {
     state = NORMAL;
     return;
   }
   if (state == MOVING_HANDLE) {
     cachedMask = null; // mask is no longer valid
     state = NORMAL;
     updateClipRect();
     oldX = x;
     oldY = y;
     oldWidth = width;
     oldHeight = height;
     return;
   }
   if (state != CONSTRUCTING) return;
   if (IJ.spaceBarDown()) // is user scrolling image?
   return;
   boolean samePoint = false;
   if (xpf != null)
     samePoint = (xpf[nPoints - 2] == xpf[nPoints - 1] && ypf[nPoints - 2] == ypf[nPoints - 1]);
   else samePoint = (xp[nPoints - 2] == xp[nPoints - 1] && yp[nPoints - 2] == yp[nPoints - 1]);
   Rectangle biggerStartBox =
       new Rectangle(ic.screenXD(startXD) - 5, ic.screenYD(startYD) - 5, 10, 10);
   if (nPoints > 2
       && (biggerStartBox.contains(sx, sy)
           || (ic.offScreenXD(sx) == startXD && ic.offScreenYD(sy) == startYD)
           || (samePoint && (System.currentTimeMillis() - mouseUpTime) <= 500))) {
     nPoints--;
     addOffset();
     finishPolygon();
     return;
   } else if (!samePoint) {
     mouseUpTime = System.currentTimeMillis();
     if (type == ANGLE && nPoints == 3) {
       addOffset();
       finishPolygon();
       return;
     }
     // add point to polygon
     if (xpf != null) {
       xpf[nPoints] = xpf[nPoints - 1];
       ypf[nPoints] = ypf[nPoints - 1];
       nPoints++;
       if (nPoints == xpf.length) enlargeArrays();
     } else {
       xp[nPoints] = xp[nPoints - 1];
       yp[nPoints] = yp[nPoints - 1];
       nPoints++;
       if (nPoints == xp.length) enlargeArrays();
     }
     // if (lineWidth>1) fitSpline();
   }
 }
Exemplo n.º 2
0
  public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();

    solve();
    out.flush();

    long end = System.currentTimeMillis();
    // trace(end-start + "ms");
    br.close();
    out.close();
  }
Exemplo n.º 3
0
  public static void main(String[] args) {
    long start = System.currentTimeMillis();

    while (in.hasNext()) solve();
    out.flush();

    long end = System.currentTimeMillis();
    // trace(end-start + "ms");
    in.close();
    out.close();
  }
Exemplo n.º 4
0
Arquivo: B.java Projeto: t8m8/AtCoder
  public static void main(String[] args) {
    debug = args.length > 0;
    long start = System.currentTimeMillis();

    solve();
    out.flush();

    long end = System.currentTimeMillis();
    dump((end - start) + "ms");
    in.close();
    out.close();
  }
Exemplo n.º 5
0
 void showFrameRate(Graphics g) {
   frames++;
   if (System.currentTimeMillis() > firstFrame + 1000) {
     firstFrame = System.currentTimeMillis();
     fps = frames;
     frames = 0;
   }
   g.setColor(Color.white);
   g.fillRect(10, 12, 50, 15);
   g.setColor(Color.black);
   g.drawString((int) (fps + 0.5) + " fps", 10, 25);
 }
Exemplo n.º 6
0
  private void drawAWP(Graphics g, int x, int y) {
    if (System.currentTimeMillis() < shotTime + TAWP.SHOOT_TIME) {
      // System.out.println(true);
      double multi = 1.0 * (System.currentTimeMillis() - shotTime) / TAWP.SHOOT_TIME;
      g.setColor(new Color(255, 255, 255, 255 - (int) (multi * 256)));
      g.fillRect(0, 0, Wuigi.screenWidth, Wuigi.screenHeight);
    }
    if (numBullets <= 0) return;

    BufferedImage img = TAWP.IMAGE.getBuffer();
    AffineTransform xform = new AffineTransform();
    // g2d.setPaint(new TexturePaint(figureOutDrawImage(),
    //		new Rectangle2D.Float(0, 0, 32, 32)));
    // g2d.drawImage(figureOutDrawImage(),0,0,null);
    xform.setToIdentity();
    xform.translate(x - 5, y);

    double diffY = y + height / 2 - ScreenManager.mouse.y;
    double diffX = ScreenManager.mouse.x - x - width / 2;

    double angle;

    if (diffY > 0 && diffX > 0) {
      angle = Math.PI / 2 - Math.atan(diffY / diffX);
    } else if (diffY == 0 && diffX > 0) {
      angle = Math.PI / 2;
    } else if (diffY < 0 && diffX > 0) {
      angle = Math.PI / 2 + Math.atan(-diffY / diffX);
    } else if (diffY < 0 && diffX == 0) {
      angle = Math.PI;
    } else if (diffY < 0 && diffX < 0) {
      angle = 3 * Math.PI / 2 - Math.atan(diffY / diffX);
    } else if (diffY == 0 && diffX < 0) {
      angle = 3 * Math.PI / 2;
    } else if (diffY > 0 && diffX < 0) {
      angle = 3 * Math.PI / 2 + Math.atan(-diffY / diffX);
    } else {
      angle = 0;
    }
    angle -= Math.PI / 2;

    if (angle > Math.PI / 2 && angle < 3 * Math.PI / 2) {
      xform.scale(1, -1);
      xform.translate(0, -TAWP.IMAGE.getHeight());
      angle = -angle;
    }
    // xform.scale(/*width/img.getWidth(),height/img.getHeight()*/);
    xform.rotate(angle, 27, 13);

    ((Graphics2D) g).drawImage(img, xform, null);
    ammo.setPos(x + 10, y - 20);
    ammo.draw(g);
  }
Exemplo n.º 7
0
  public void handleImage() {
    while (true) {
      Image src = null;
      try {
        src = new Image(visionImage.take(), width, height);
      } catch (InterruptedException e) {
        e.printStackTrace();
        continue;
      }

      // Apply Blob Track to Image
      Image dest = new Image(src);
      blobTrack.apply(src, dest);

      OdometryMsg msg = new OdometryMsg();

      if (LOCALIZE && System.currentTimeMillis() - last_localization > LOCALIZATION_INTERVAL) {
        ResetMsg stop_msg = new ResetMsg();
        stop_msg.reset = false;
        stopPub.publish(stop_msg);

        Point2D.Double curr_point;
        synchronized (localization) {
          curr_point = localization.localize(odo_x, odo_y, blobTrack.fiducials);
        }
        msg.x = curr_point.x;
        msg.y = curr_point.y;

        last_localization = System.currentTimeMillis();
      } else {
        msg.x = odo_x;
        msg.y = odo_y;
      }
      msg.theta = odo_theta;
      localPub.publish(msg);

      // Update newly formed vision message
      gui.setVisionImage(dest.toArray(), width, height);

      try {
        Thread.sleep(1000);
      } catch (Exception exc) {
        exc.printStackTrace();
      }

      ResetMsg stop_msg = new ResetMsg();
      stop_msg.reset = true;
      stopPub.publish(stop_msg);
    }
  }
Exemplo n.º 8
0
 private void chkFPS() {
   if (fpsCount == 0) {
     fpsTime = System.currentTimeMillis() / 1000;
     fpsCount++;
     return;
   }
   fpsCount++;
   long time = System.currentTimeMillis() / 1000;
   if (time != fpsTime) {
     lastFPS = fpsCount;
     fpsCount = 1;
     fpsTime = time;
   }
 }
Exemplo n.º 9
0
 void resetMaxBounds() {
   ImageWindow win = imp.getWindow();
   if (win != null && (System.currentTimeMillis() - win.setMaxBoundsTime) > 500L) {
     win.setMaximizedBounds(win.maxWindowBounds);
     maxBoundsReset = true;
   }
 }
 ////////////////////////////////////////////////////////////////////////////
 // Paint
 //
 public synchronized void paint(Graphics g) {
   Graphics2D g2 = (Graphics2D) g;
   // Graphics2D buffGraphics2 = (Graphics2D) buffGraphics;
   //    g2.drawImage(bImage, 3, 3, getWidth() - 3, getHeight() - 3,
   //        0, 0, iWidth, iHeight, null);
   g2.drawImage(bImage, 0, 0, iWidth, iHeight, null);
   g2.drawString(String.valueOf(System.currentTimeMillis()), 10, 10);
 }
Exemplo n.º 11
0
  private BufferedImage figureOutDrawImage(Sprite[] imgs) {

    Sprite img;
    if (dead) {
      return imgs[5].getBuffer();
    }

    if (Math.abs((int) (vel.y * 100)) > 0 && !piped) {
      img = imgs[1];
    } else if (!(movingRight || movingLeft) && vel.x == 0) img = imgs[0];
    else {
      if (movingRight && vel.x < 0 || movingLeft && vel.x > 0) img = imgs[4];
      else {
        if (rightFoot) img = imgs[3];
        else img = imgs[2];
      }
    }

    if (star && (starTime < 8000 / 15 || System.currentTimeMillis() % 60 > 30)) {
      int width = img.getBuffer().getWidth(), height = img.getBuffer().getHeight();
      Sprite limg = new Sprite(img.getBuffer());
      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          Color pixel = limg.getPixel(x, y);
          if (pixel.getAlpha() != 0) {
            limg.setPixel(
                x,
                y,
                new Color(
                    255 - pixel.getRed(),
                    255 - pixel.getGreen(),
                    255 - pixel.getBlue(),
                    pixel.getAlpha()));
          }
        }
      }
      img = limg;
    } else if (metal) {
      int width = img.getBuffer().getWidth(), height = img.getBuffer().getHeight();
      Sprite limg = new Sprite(img.getBuffer());
      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          Color pixel = limg.getPixel(x, y);
          if (pixel.getAlpha() != 0) {
            int gray = (pixel.getRed() + pixel.getBlue() + pixel.getGreen()) / 3;
            limg.setPixel(x, y, new Color(gray, gray, gray, pixel.getAlpha()));
          }
        }
      }
      img = limg;
    }

    if (facingRight) {
      return img.flipX();
    } else {
      return img.getBuffer();
    }
  }
Exemplo n.º 12
0
 void setMaxBounds() {
   if (maxBoundsReset) {
     maxBoundsReset = false;
     ImageWindow win = imp.getWindow();
     if (win != null && !IJ.isLinux() && win.maxBounds != null) {
       win.setMaximizedBounds(win.maxBounds);
       win.setMaxBoundsTime = System.currentTimeMillis();
     }
   }
 }
Exemplo n.º 13
0
  private void graphGrid(ArrayList<ArrayList<Position>> grid) throws InterruptedException {
    System.out.println(
        "Size of file by rows = " + grid.size() + ", columns = " + grid.get(0).size());
    final long current = System.currentTimeMillis();
    // System.out.println("Time for parsing file: " + ((current - startParseTime) / 1000) + " sec");
    // long afterEdge = 0;
    // long timeFindEdge = 0;

    ArrayList<Integer> ranges = findRanges();
    final Cell<Integer> threadsActive = new Cell<Integer>(threads);
    class EdgeThread extends Thread {

      int startRow = 0;
      int endRow = 0;

      public EdgeThread(int startRow, int endRow) {
        this.startRow = startRow;
        this.endRow = endRow;
      }

      public void run() {
        System.out.println("Thread: " + this.getId());
        findEdges(startRow, endRow);
        boolean lastThread;
        synchronized (threadsActive) {
          lastThread = --threadsActive.object == 0;
        }
        if (lastThread) {
          System.out.println("Last Thread: " + this.getId());
          long afterEdge = System.currentTimeMillis();
          long timeFindEdge = (afterEdge - current) / 1000;
          System.out.println("Time for findEdges: " + timeFindEdge + " sec");

          colorSCC();
          long afterColor = System.currentTimeMillis();
          long timeForColor = (afterColor - afterEdge) / 1000;
          System.out.println("Time for coloring and find CC: " + timeForColor + " sec");
          // findConnectedComponents();
          create();
          long timeForCreate = (System.currentTimeMillis() - afterColor) / 1000;
          System.out.println("Time for creating map: " + timeForCreate + " sec");
        }
      }
    }
    for (int i = 0; i < threads; i++) {
      EdgeThread thread = new EdgeThread(ranges.get(2 * i), ranges.get(2 * i + 1));
      thread.start();
    }

    Thread.currentThread().join();
  }
Exemplo n.º 14
0
  void renderer(Graphics2D g2d) {
    height = window.getHeight() - 20;
    width = window.getWidth();

    lastTime = curTime;
    curTime = System.currentTimeMillis();
    totalTime += curTime - lastTime;
    if (totalTime > 1000) {
      totalTime -= 1000;
      fps = frames;
      frames = 0;
    }
    ++frames;

    delta = 16.0 / (curTime - lastTime);
    if (delta < 0) delta = 0;

    g2d.setColor(Color.white);
    if (removeMode) g2d.fill(new Rectangle(0, 0, width, height));

    if (eventHandeler(g2d)) {
      renderBackground(g2d);
      return;
    }

    Graphics2D map = (Graphics2D) g2d.create();
    playerHandeler();
    xOffset = -player.body.getCenterX() + width / 2;
    yOffset = -player.body.getCenterY() + height / 2;

    if (-xOffset < bounds.getBounds2D().getX()) xOffset = -bounds.getBounds2D().getX();
    else if (-xOffset > bounds.getBounds2D().getMaxX() - width)
      xOffset = -bounds.getBounds2D().getMaxX() + width;

    if (-yOffset < bounds.getBounds2D().getY()) yOffset = -bounds.getBounds2D().getY();
    else if (-yOffset > bounds.getBounds2D().getMaxY() - height + 3)
      yOffset = -bounds.getBounds2D().getMaxY() + height - 3;

    map.translate(xOffset, yOffset);

    renderBackground(map);
    itemHandeler(map);
    enemieHandeler();
    characterHandeler(map);

    map.setColor(Color.black);
    map.draw(bounds);

    renderUI(g2d);
  }
Exemplo n.º 15
0
  public void saveGlyphFile(OutputStream a_output) {
    try {
      Transformer transformer = getTransformer();
      Document document = m_glyph.makeDocument();
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(a_output);
      transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException e) {
      e.printStackTrace();
    }

    m_savedTime = System.currentTimeMillis();
    m_modifiedTime = m_savedTime;
  }
Exemplo n.º 16
0
      public void run() {
        System.out.println("Thread: " + this.getId());
        findEdges(startRow, endRow);
        boolean lastThread;
        synchronized (threadsActive) {
          lastThread = --threadsActive.object == 0;
        }
        if (lastThread) {
          System.out.println("Last Thread: " + this.getId());
          long afterEdge = System.currentTimeMillis();
          long timeFindEdge = (afterEdge - current) / 1000;
          System.out.println("Time for findEdges: " + timeFindEdge + " sec");

          colorSCC();
          long afterColor = System.currentTimeMillis();
          long timeForColor = (afterColor - afterEdge) / 1000;
          System.out.println("Time for coloring and find CC: " + timeForColor + " sec");
          // findConnectedComponents();
          create();
          long timeForCreate = (System.currentTimeMillis() - afterColor) / 1000;
          System.out.println("Time for creating map: " + timeForCreate + " sec");
        }
      }
Exemplo n.º 17
0
  /** shoots the AWP */
  public void shootAWP(int x, int y) {
    if (numBullets > 0) {
      numBullets--;
      AWP.start();
      shotTime = System.currentTimeMillis();
      ammo.setText("" + numBullets);

      double awpx = pos.x + width / 2;
      double awpy = pos.y + height / 2;

      double mousex = x + this.pos.x - (Wuigi.screenWidth / 2.0 + xOffset());
      double mousey = Wuigi.screenHeight + pos.y + 32 - (ScreenManager.mouse.y + yOffset());

      addSpawn(new AWPBullet(awpx, awpy, mousex, mousey));
    }
  }
Exemplo n.º 18
0
  /**
   * Display on screen, pause for t milliseconds, and turn on <em>animation mode</em>: subsequent
   * calls to drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and <tt>square()</tt> will
   * not be displayed on screen until the next call to <tt>show()</tt>. This is useful for producing
   * animations (clear the screen, draw a bunch of shapes, display on screen for a fixed amount of
   * time, and repeat). It also speeds up drawing a huge number of shapes (call <tt>show(0)</tt> to
   * defer drawing on screen, draw the shapes, and call <tt>show(0)</tt> to display them all on
   * screen at once).
   *
   * @param t number of milliseconds
   */
  public static void show(int t) {
    // sleep until the next time we're allowed to draw
    long millis = System.currentTimeMillis();
    if (millis < nextDraw) {
      try {
        Thread.sleep(nextDraw - millis);
      } catch (InterruptedException e) {
        System.out.println("Error sleeping");
      }
      millis = nextDraw;
    }

    defer = false;
    draw();
    // try { Thread.sleep(t); }
    // catch (InterruptedException e) { System.out.println("Error sleeping"); }
    defer = true;

    // when are we allowed to draw again
    nextDraw = millis + t;
  }
Exemplo n.º 19
0
        public void keyPressed(KeyEvent e) {
          int dx = 0;
          int dy = 0;
          if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            dx = -1;
          } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            dx = 1;
          } else if (e.getKeyCode() == KeyEvent.VK_UP) {
            dy = -1;
          } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            dy = 1;
          }
          int multiplier = 1;
          if (e.isShiftDown() && e.isAltDown()) {
            multiplier = 10;
          } else if (e.isShiftDown() || e.isAltDown()) {
            multiplier = 5;
          }
          if (dx != 0 || dy != 0) {
            int size =
                Math.min(
                    MAX_SIZE,
                    Math.min(
                        getWidth() - imagePadding.left - imagePadding.right,
                        getHeight() - imagePadding.top - imagePadding.bottom));

            int offsetX = getWidth() / 2 - size / 2;
            int offsetY = getHeight() / 2 - size / 2;
            mouseListener.mousePressed(
                new MouseEvent(
                    ColorPickerPanel.this,
                    MouseEvent.MOUSE_PRESSED,
                    System.currentTimeMillis(),
                    0,
                    point.x + multiplier * dx + offsetX,
                    point.y + multiplier * dy + offsetY,
                    1,
                    false));
          }
        }
Exemplo n.º 20
0
  // CONSTANT METHODS
  public void draw(Graphics g, ImageObserver o) {

    boolean transparent =
        invulerable && (invulerableTime < 3000 / 15 || System.currentTimeMillis() % 60 > 30);
    if (transparent)
      ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    int x = Wuigi.scaleW(Wuigi.screenWidth / 2.0 + xOffset - 4);
    int y = Wuigi.scaleH(Wuigi.screenHeight - yOffset);
    if (cape) {
      if (facingRight)
        g.drawImage(
            TCape.IMAGE.getBuffer(),
            x - 5,
            y,
            Wuigi.scaleW(WIDTH + 8),
            Wuigi.scaleH(HEIGHT + 2),
            o);
      else
        g.drawImage(
            TCape.IMAGE.flipX(), x + 5, y, Wuigi.scaleW(WIDTH + 8), Wuigi.scaleH(HEIGHT + 2), o);
    }

    drawAWP(g, x, y);

    g.drawImage(
        figureOutDrawImage(IMAGE),
        x,
        // (int)(Global.H-H-pos.y-Global.GROUND_LEVEL),
        y,
        Wuigi.scaleW(WIDTH + 8),
        Wuigi.scaleH(HEIGHT + 2),
        o);
    if (transparent)
      ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));

    // g.setColor(Color.WHITE);
    // g.drawRect((int)(Wuigi.W/2 - X_OFFSET), (int)(Wuigi.H - Y_OFFSET), (int)X_OFFSET*2 + width,
    // (int)(Y_OFFSET*2) - Wuigi.H);
  }
/**
 * A simple adapter that allows displaying of timestamped values from an inspection of the <code>
 * ObjectRecorder</code> on a Chart2D.
 */
public class ObjRecorder2Trace2DAdapter implements ChangeListener {
  ITrace2D view;
  ObjectRecorder inspector;
  String fieldname;
  long start = System.currentTimeMillis();

  public ObjRecorder2Trace2DAdapter(
      ITrace2D view, Object toinspect, String fieldname, long interval) {
    this.view = view;
    this.fieldname = fieldname;
    this.view.setLabel(
        new StringBuffer(toinspect.getClass().getName()).append(toinspect.hashCode()).toString());
    this.inspector = new ObjectRecorder(toinspect, interval);
    this.inspector.addChangeListener(this);
  }

  public void stateChanged(ChangeEvent e) {
    TimeStampedValue last;
    try {
      last = inspector.getLastValue(fieldname);
    } catch (Exception f) {
      f.printStackTrace();
      return;
    }
    if (last != null) {
      double tmpx, tmpy;
      tmpx = last.getTime() - start;
      tmpy = Double.parseDouble(last.getValue().toString());
      this.view.addPoint(tmpx, tmpy);
    }
  }

  public void setInterval(long interval) {
    this.inspector.setInterval(interval);
  }
}
Exemplo n.º 22
0
public class Runtime {

  class CExplode {
    Object[][] particles = new Object[30][3];
    double created;
    int timeAlive = 1000;

    CExplode(double x, double y) {
      for (int i = 0; i < particles.length; i++) {
        // particles[i][0] = new Ellipse2D.Double(x, y, 10, 10);
        particles[i][0] =
            new Arc2D.Double(
                x - 25, y - 25, 50, 50, 360 / particles.length * i, 360 / particles.length * 2, 0);
        particles[i][1] = rand.nextDouble() + rand.nextInt(3) - 1;
        particles[i][2] = rand.nextDouble() + rand.nextInt(3) - 1;

        created = System.nanoTime();
      }
    }

    boolean render(Graphics2D map) {
      double diff = (System.nanoTime() - created) / 1000 / 1000;
      if (diff > timeAlive) return true;
      map.setColor(new Color(100, 100, 100, (int) (255 - (diff / timeAlive * 250))));
      for (int i = 0; i < particles.length; i++) {
        RectangularShape tmp = (RectangularShape) particles[i][0];
        double xD = (Double) particles[i][1];
        double yD = (Double) particles[i][2];
        tmp.setFrame(
            (double) tmp.getX() + xD / delta,
            (double) tmp.getY() + yD / delta,
            tmp.getWidth(),
            tmp.getHeight());
        map.draw(tmp);
      }
      return false;
    }
  }

  JFrame window;
  Canvas canvas;
  Random rand = new Random();
  KeyboardInput keyboard;
  MouseInput mouse;

  int fps = 0;
  int frames = 0;
  long totalTime = 0;
  long curTime = System.currentTimeMillis();
  long lastTime = curTime;
  double delta;
  boolean newHighscore = false;
  int oldHighScore = 0;
  boolean cheated = false;
  boolean showDebug = false;

  int height;
  int width;
  double xOffset;
  double yOffset;
  boolean removeMode = true;

  int difficulty;
  boolean paused = false;
  boolean firstStartup = true;
  int startupPage = 1;
  Character player;
  double[][] background = new double[50][9];
  int backgroundWidth;
  RectangularShape bounds;
  CExplode[] characterExplosions = new CExplode[10];
  Item[] items = new Item[10];
  Character[] characters = new Character[50];

  @SuppressWarnings("deprecation")
  Runtime(JFrame app, KeyboardInput keyboard, MouseInput mouse) {
    window = app;
    window.setCursor(Cursor.CROSSHAIR_CURSOR);
    this.mouse = mouse;
    this.keyboard = keyboard;

    height = window.getHeight() - 20;
    width = window.getWidth();
  }

  void newCExplosion(double x, double y) {
    for (int i = 0; i < characterExplosions.length; i++) {
      if (characterExplosions[i] == null) {
        characterExplosions[i] = new CExplode(x, y);
        break;
      }
    }
  }

  void spawnEnemie(double x, double y, int size, int weapon) {
    for (int i = 0; i < characters.length; i++) {
      if (characters[i] == null) {
        characters[i] = new Character(new Ellipse2D.Double(x, y, 1, 1), "enemie", weapon);
        characters[i].setSpawnHealth(size);
        break;
      }
    }
  }

  void spawnBounds(int size) {
    bounds = new Rectangle2D.Double(-size, -size, size * 2, size * 2);
    generateBackground(size);
  }

  void spawnItem(double x, double y, int type) {
    for (int i = 0; i < items.length; i++) {
      if (items[i] == null) {
        items[i] = new Item(x, y, type);
        double[] pos = checkIfInsideBounds(items[i]);
        items[i].body.setFrame(pos[0], pos[1], items[i].body.getWidth(), items[i].body.getHeight());
        // items[i].x = pos[0] + rand.nextInt(100) + items[i].body.getWidth() / 2;
        // items[i].y = pos[1] + rand.nextInt(100) + items[i].body.getHeight() / 2;
        return;
      }
    }
  }

  void restart() {
    for (int i = 0; i < characters.length; i++) {
      characters[i] = null;
    }
    for (int i = 0; i < items.length; i++) {
      items[i] = null;
    }
    startup();
  }

  void startup() {
    cheated = false;
    spawnBounds(1000);
    characters[0] =
        new Character(new Ellipse2D.Double(width / 2 - 25, height / 2 - 25, 50, 50), "player", 1);
    characters[0].health = 10000;
    difficulty = 1;
    player = characters[0];
    newHighscore = false;
  }

  void inputListener() {
    if (keyboard.keyDown(KeyEvent.VK_W)) player.moveDir[1] = -1;
    else if (keyboard.keyDown(KeyEvent.VK_S)) player.moveDir[1] = 1;
    else player.moveDir[1] = 0;

    if (keyboard.keyDown(KeyEvent.VK_A)) player.moveDir[0] = -1;
    else if (keyboard.keyDown(KeyEvent.VK_D)) player.moveDir[0] = 1;
    else player.moveDir[0] = 0;

    if (keyboard.keyDown(KeyEvent.VK_1)) player.SetWeapon(1);
    if (keyboard.keyDown(KeyEvent.VK_2)) player.SetWeapon(2);
    if (keyboard.keyDown(KeyEvent.VK_3)) player.SetWeapon(3);
    if (keyboard.keyDown(KeyEvent.VK_4)) player.SetWeapon(4);
    if (keyboard.keyDown(KeyEvent.VK_5)) player.SetWeapon(5);
    if (keyboard.keyDown(KeyEvent.VK_6)) player.SetWeapon(6);
    if (keyboard.keyDown(KeyEvent.VK_7)) player.SetWeapon(7);
    if (keyboard.keyDown(KeyEvent.VK_8)) player.SetWeapon(8);
    if (keyboard.keyDown(KeyEvent.VK_9)) player.SetWeapon(9);

    if (keyboard.keyDownOnce(KeyEvent.VK_Z)) {
      if (showDebug) showDebug = false;
      else showDebug = true;
    }
    if (keyboard.keyDownOnce(KeyEvent.VK_F9)) {
      cheated = true;
      player.health = 1000000;
    }
    if (keyboard.keyDownOnce(KeyEvent.VK_F10)) {
      cheated = true;
      player.unlockWeapon(2, true);
      player.unlockWeapon(3, true);
      player.unlockWeapon(4, true);
    }
    if (keyboard.keyDownOnce(KeyEvent.VK_F11)) {
      cheated = true;
      player.upgradeWeapon(1, 1);
      player.upgradeWeapon(2, 1);
      player.upgradeWeapon(3, 1);
      player.upgradeWeapon(4, 1);
    }
    if (keyboard.keyDown(KeyEvent.VK_F12)) {
      cheated = true;
      player.score = (int) (player.score + 1 / delta);
    }

    if (keyboard.keyDownOnce(KeyEvent.VK_MINUS)) if (difficulty < 19) difficulty = difficulty + 1;
    if (keyboard.keyDownOnce(KeyEvent.VK_BACK_SLASH))
      if (difficulty > 1) difficulty = difficulty - 1;
    if (keyboard.keyDownOnce(KeyEvent.VK_ESCAPE)) paused = true;
    if (keyboard.keyDownOnce(KeyEvent.VK_M))
      if (removeMode) removeMode = false;
      else removeMode = true;

    if (mouse.buttonDown(1))
      player.Shoot(mouse.getPosition().getX() - xOffset, mouse.getPosition().getY() - yOffset);
  }

  void itemHandeler(Graphics2D map) {
    boolean tmp = false;
    if (rand.nextInt((int) (300 * delta + difficulty * 40)) <= 1 && tmp) {
      int x = rand.nextInt(4) - 2;
      int y = rand.nextInt(4) - 2;
      int type = 1;
      if (x == 0 && y == 0) {
        x = 0;
        y = 1;
      }
      if (rand.nextInt(10) == 1) {
        type = 2;
      }
      if (rand.nextInt(5) == 1)
        for (int i = 0; i < player.weapon.length; i++)
          if (player.weapon[i][11] != null && (Boolean) player.weapon[i][11] == true)
            if ((Integer) player.weapon[i][10] < 5) type = 3;

      spawnItem(player.body.getCenterX() + 200 * x, player.body.getCenterY() + 200 * y, type);
    }

    for (int i = 1; i < items.length; i++) {
      if (items[i] != null) {
        if (items[i].body == null) {
          items[i] = null;
        } else {
          items[i].Runtime(map, player, delta);
        }
      }
    }
  }

  void enemieHandeler() {
    int ran = (int) ((70 - difficulty) * delta);
    if (ran <= 0) return;
    if (rand.nextInt(ran) == 1) {
      int x = rand.nextInt(2);
      int y = rand.nextInt(2);
      int size = rand.nextInt(1000) + 50;
      if (x == 0 && y == 0)
        if (rand.nextBoolean()) x = rand.nextInt(4) + 1;
        else y = rand.nextInt(4) + 1;

      if (rand.nextBoolean()) x = -x;
      if (rand.nextBoolean()) y = -y;
      size = size * (rand.nextInt(difficulty) + 1);

      x = (int) (x * 400 + player.body.getCenterX());
      y = (int) (y * 400 + player.body.getCenterY());

      int type = 0;

      if (rand.nextInt(60 / difficulty) <= 1) type = rand.nextInt(3) + 1;

      spawnEnemie(x, y, size, type);
    }
  }

  double[] checkIfInsideBounds(Character target) {
    double[] targetFixInsideBounds = new double[2];
    targetFixInsideBounds[0] = target.body.getX();
    targetFixInsideBounds[1] = target.body.getY();
    if (target.body.getX() < bounds.getBounds2D().getX())
      targetFixInsideBounds[0] = bounds.getBounds2D().getX();
    else if (target.body.getX() > bounds.getBounds2D().getMaxX() - target.body.getWidth())
      targetFixInsideBounds[0] = bounds.getBounds2D().getMaxX() - target.body.getWidth();

    if (target.body.getY() < bounds.getBounds2D().getY())
      targetFixInsideBounds[1] = bounds.getBounds2D().getY();
    else if (target.body.getY() > bounds.getBounds2D().getMaxY() - target.body.getHeight())
      targetFixInsideBounds[1] = bounds.getBounds2D().getMaxY() - target.body.getHeight();
    return targetFixInsideBounds;
  }

  double[] checkIfInsideBounds(Item target) {
    double[] targetFixInsideBounds = new double[2];
    targetFixInsideBounds[0] = target.body.getX();
    targetFixInsideBounds[1] = target.body.getY();
    if (target.body.getX() < bounds.getBounds2D().getX())
      targetFixInsideBounds[0] = bounds.getBounds2D().getX();
    else if (target.body.getX() > bounds.getBounds2D().getMaxX() - target.body.getWidth())
      targetFixInsideBounds[0] = bounds.getBounds2D().getMaxX() - target.body.getWidth();

    if (target.body.getY() < bounds.getBounds2D().getY())
      targetFixInsideBounds[1] = bounds.getBounds2D().getY();
    else if (target.body.getY() > bounds.getBounds2D().getMaxY() - target.body.getHeight())
      targetFixInsideBounds[1] = bounds.getBounds2D().getMaxY() - target.body.getHeight();
    return targetFixInsideBounds;
  }

  void characterHandeler(Graphics2D map) {
    for (int i = 0; i < characterExplosions.length; i++) {
      if (characterExplosions[i] != null) {
        if (characterExplosions[i].render(map)) characterExplosions[i] = null;
      }
    }
    for (int i = 0; i < characters.length; i++) {
      if (characters[i] != null) {
        if (characters[i].isDead == true) {
          newCExplosion(characters[i].body.getCenterX(), characters[i].body.getCenterY());
          if (rand.nextInt(5) == 1) {
            int type = 1;
            if (rand.nextInt(10) == 1) {
              type = 2;
            }
            if (rand.nextInt(4) == 1)
              for (int j = 0; j < player.weapon.length; j++)
                if (player.weapon[j][11] != null && (Boolean) player.weapon[j][11] == true)
                  if ((Integer) player.weapon[j][10] < 5) type = 3;
            spawnItem(characters[i].body.getCenterX(), characters[i].body.getCenterY(), type);
          }
          characters[i] = null;
        } else {
          if (characters[i].id != "player") {
            characters[i].Folow(player);
            double[] pos = checkIfInsideBounds(characters[i]);
            characters[i].body.setFrame(
                pos[0], pos[1], characters[i].body.getWidth(), characters[i].body.getHeight());
            characters[i].Update(xOffset, yOffset, delta);
          }
          characters[i].Render(map, characters);
          if (Math.pow(characters[i].body.getCenterX() - characters[i].body.getCenterX(), 2)
                  + Math.pow(player.body.getCenterY() - player.body.getCenterY(), 2)
              < Math.pow(width * 1.5, 2)) {
            map.setColor(Color.darkGray);
            map.draw(characters[i].body);
          }
        }
      }
    }
  }

  boolean setHighscore() {
    int high = 0;
    boolean newh = false;

    String path = "";
    if (System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0)
      path =
          new JFileChooser().getFileSystemView().getDefaultDirectory().toString()
              + "/Library/Application Support/ByRikard/IJAG";
    else path = System.getenv("APPDATA") + "/ByRikard/IJAG";
    String highscorePath = path + "/highscore";

    try {
      FileInputStream fstream = new FileInputStream(highscorePath);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      high = Integer.parseInt(br.readLine());
      in.close();
    } catch (Exception e) {
    }
    oldHighScore = high;
    if (high < player.score) {
      high = player.score;
      newh = true;
    }

    try {
      String content = "" + high;
      File file = new File(highscorePath);

      if (!file.exists()) {
        file.createNewFile();
      }
      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(content);
      bw.close();

    } catch (IOException e) {
    }
    return newh;
  }

  void playerHandeler() {

    inputListener();

    if (player.health <= 0) {
      player.isDead = true;
      if (cheated == false) newHighscore = setHighscore();
    }

    player.Update(xOffset, yOffset, delta);
    double[] pos = checkIfInsideBounds(player);
    player.body.setFrame(pos[0], pos[1], player.body.getWidth(), player.body.getHeight());

    int levelupDif = 10;
    double val = levelupDif;
    for (int i = 0; i < difficulty; i++) {
      val = val + val / levelupDif + levelupDif;
    }
    if (player.score > val) {
      if (difficulty < 19) {
        difficulty = difficulty + 1;

        int toUpgrade = 0;
        int curLev = 100;
        for (int i = 0; i < player.weapon.length; i++) {
          if (player.weapon[i][11] != null
              && (Boolean) player.weapon[i][11] == true
              && player.unlockedWeapons[i] == true) {
            if ((Integer) player.weapon[i][10] < curLev) {
              curLev = (Integer) player.weapon[i][10];
              toUpgrade = i;
            }
          }
        }
        if (curLev < 5 && curLev < difficulty / 2) {
          player.upgradeWeapon(toUpgrade, 1);
          player.newMessage(
              "Level up! The "
                  + player.weapon[toUpgrade][13]
                  + " was uppgraded to level "
                  + (curLev + 1),
              2000);
        }
      }
    }
  }

  boolean eventHandeler(Graphics2D g2d) {

    if (keyboard.keyDownOnce(KeyEvent.VK_Q)) {
      window.setState(Frame.ICONIFIED);
      paused = true;
    }

    if (firstStartup) {
      g2d.setColor(Color.white);
      g2d.fill(new Rectangle(0, 0, width, height));

      g2d.setFont(new Font("Courier New", Font.PLAIN, 20));
      g2d.setColor(Color.black);
      switch (startupPage) {
        case 1:
          if (keyboard.keyDownOnce(KeyEvent.VK_SPACE)) startupPage = 2;

          g2d.drawString("The goal of this game is to kill as", 100, 170);
          g2d.drawString("many *zombies* as possible. You are", 100, 200);
          g2d.drawString("given weapons and power-ups to help", 100, 230);
          g2d.drawString("you succeed. Good luck.", 100, 260);

          g2d.setColor(Color.gray);
          g2d.drawString("Press SPACE to continue", 150, 330);
          g2d.drawString("Ø O O", 280, 290);

          g2d.setColor(Color.black);
          g2d.setFont(new Font("Courier New", Font.PLAIN, 34));
          g2d.drawString("Story", 265, 110);
          break;
        case 2:
          if (keyboard.keyDownOnce(KeyEvent.VK_SPACE)) startupPage = 3;

          g2d.drawString("Use A,S,D,W to stear", 100, 170);
          g2d.drawString("Use 1,2,3,4 to change weapon", 100, 200);
          g2d.drawString("Use the MOUSE to aim", 100, 230);
          g2d.drawString("Use the LEFT MOUSE BUTTON to fire", 100, 260);

          g2d.setColor(Color.gray);
          g2d.drawString("Press SPACE to continue", 150, 330);
          g2d.drawString("O Ø O", 280, 290);

          g2d.setColor(Color.black);
          g2d.setFont(new Font("Courier New", Font.PLAIN, 34));
          g2d.drawString("Controlls", 230, 110);
          break;
        case 3:
          if (keyboard.keyDownOnce(KeyEvent.VK_SPACE)) firstStartup = false;

          g2d.setColor(Color.black);
          g2d.draw(new Ellipse2D.Double(100, 170 - 15, 20, 20));
          g2d.setColor(Color.red);
          g2d.draw(new Ellipse2D.Double(100, 200 - 15, 20, 20));
          g2d.setColor(Color.blue);
          g2d.draw(new Ellipse2D.Double(100, 230 - 15, 20, 20));
          g2d.setColor(Color.green);
          g2d.draw(new Ellipse2D.Double(100, 260 - 15, 20, 20));

          g2d.setColor(Color.black);
          g2d.drawString("Is you", 130, 170);
          g2d.drawString("Heals you", 130, 200);
          g2d.drawString("Unlocks / upgrades a weapon", 130, 230);
          g2d.drawString("Causes an explosion around you", 130, 260);

          g2d.setColor(Color.gray);
          g2d.drawString("Press SPACE to start", 150, 330);
          g2d.drawString("O O Ø", 280, 290);

          g2d.setColor(Color.black);
          g2d.setFont(new Font("Courier New", Font.PLAIN, 34));
          g2d.drawString("Power-ups", 230, 110);
          break;
      }
      return true;
    }

    if (player.isDead) {
      g2d.setColor(Color.white);
      g2d.fill(new Rectangle(0, 0, width, height));
      if (keyboard.keyDownOnce(KeyEvent.VK_R)) restart();

      if (newHighscore) {
        int x = 20;
        int y = 130;
        g2d.rotate(-.4, x, y);
        g2d.setFont(new Font("Comic Sans MS", Font.PLAIN, 40));
        g2d.setColor(Color.black);
        Stroke oldStroke = g2d.getStroke();
        float dash[] = {40.0f};
        g2d.setStroke(
            new BasicStroke(
                4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0.0f, dash, 40.0f));
        g2d.drawRoundRect(x, y, 320, 75, 20, 20);
        g2d.setColor(Color.red);
        g2d.drawString(String.format("New Highscore"), x + 20, y + 50);
        g2d.rotate(.4, x, y);
        g2d.setStroke(oldStroke);

        g2d.setColor(Color.lightGray);
        g2d.setFont(new Font("Courier", Font.PLAIN, 20));
        g2d.drawString("Your record was " + oldHighScore + " kills", 210, 260);
      } else if (cheated) {
        int x = 20;
        int y = 130;
        g2d.rotate(-.4, x, y);
        g2d.setFont(new Font("Comic Sans MS", Font.PLAIN, 40));
        g2d.setColor(Color.black);
        Stroke oldStroke = g2d.getStroke();
        float dash[] = {40.0f};
        g2d.setStroke(
            new BasicStroke(
                4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0.0f, dash, 40.0f));
        g2d.drawRoundRect(x, y, 270, 75, 20, 20);
        g2d.setColor(Color.red);
        g2d.drawString(String.format("You cheated"), x + 20, y + 50);
        g2d.rotate(.4, x, y);
        g2d.setStroke(oldStroke);

        g2d.setColor(Color.lightGray);
        g2d.setFont(new Font("Courier", Font.PLAIN, 20));
        g2d.drawString("Highscore not saved", 210, 260);
      } else {
        g2d.setColor(Color.lightGray);
        g2d.setFont(new Font("Courier", Font.PLAIN, 20));
        g2d.drawString("Your record is " + oldHighScore + " kills", 210, 260);
      }

      g2d.setColor(Color.black);
      g2d.setFont(new Font("Courier", Font.PLAIN, 50));

      if (player.score == 1) g2d.drawString(String.format(player.score + " kill"), 200, 230);
      else g2d.drawString(String.format(player.score + " kills"), 200, 230);
      g2d.setFont(new Font("Courier New", Font.PLAIN, 30));
      g2d.setColor(Color.gray);
      g2d.drawString(String.format("Press R to restart"), 150, 330);
      return true;
    }

    if (window.isFocused() == false) paused = true;

    if (paused) {
      g2d.setColor(Color.white);
      g2d.fill(new Rectangle(0, 0, width, height));
      if (keyboard.keyDownOnce(KeyEvent.VK_ESCAPE)) paused = false;
      g2d.setColor(Color.black);
      g2d.setFont(new Font("Courier", Font.PLAIN, 50));
      g2d.drawString("Paused", 200, 230);
      g2d.setFont(new Font("Courier New", Font.PLAIN, 30));
      g2d.setColor(Color.gray);
      g2d.drawString(String.format("Press ESC to resume"), 150, 330);
      return true;
    }

    return false;
  }

  void generateBackground(int size) {
    backgroundWidth = 100;
    int spacing = backgroundWidth;
    int id = 0;
    for (int i = 0; i < bounds.getWidth() / spacing; i++) {
      background[id][0] = spacing * (i + 1) - bounds.getWidth() / 2;
      background[id][1] = -bounds.getHeight() / 2;
      background[id][2] = spacing * (i + 1) - bounds.getWidth() / 2;
      background[id][3] = 0;
      background[id][4] = spacing * (i + 1) - bounds.getWidth() / 2;
      background[id][5] = bounds.getHeight();

      background[id][6] = rand.nextInt(3) - 1;
      background[id][7] = rand.nextInt(3) - 1;
      background[id][8] = 1;
      id++;
    }
    for (int i = 0; i < bounds.getHeight() / spacing; i++) {
      background[id][0] = -bounds.getHeight() / 2;
      background[id][1] = spacing * (i + 1) - bounds.getHeight() / 2;
      background[id][2] = 0;
      background[id][3] = spacing * (i + 1) - bounds.getWidth() / 2;
      background[id][4] = bounds.getWidth();
      background[id][5] = spacing * (i + 1) - bounds.getHeight() / 2;

      background[id][6] = rand.nextInt(3) - 1;
      background[id][7] = rand.nextInt(3) - 1;
      background[id][8] = 1;
      id++;
    }
  }

  void renderBackground(Graphics2D g2d) {
    g2d.setColor(new Color(0, 0, 0, 30));
    for (int i = 0; i < background.length; i++) {
      if (background[i][8] == 1) {
        if (Math.round(rand.nextInt(200) * delta) == 1) background[i][6] = (rand.nextInt(3) - 1);
        if (Math.round(rand.nextInt(200) * delta) == 1) background[i][7] = (rand.nextInt(3) - 1);

        if (background[i][6] < 0) background[i][6] = background[i][6] - 0.01;
        else if (background[i][6] > 0) background[i][6] = background[i][6] + 0.01;

        if (background[i][7] < 0) background[i][7] = background[i][7] - 0.01;
        else if (background[i][7] > 0) background[i][7] = background[i][7] + 0.01;

        if (background[i][2] < background[i][0] - backgroundWidth * 3)
          background[i][6] = rand.nextInt(2);
        if (background[i][2] > background[i][0] + backgroundWidth * 3)
          background[i][6] = -rand.nextInt(2);

        if (background[i][3] < background[i][1] - backgroundWidth * 3)
          background[i][7] = rand.nextInt(2);
        if (background[i][3] > background[i][1] + backgroundWidth * 3)
          background[i][7] = -rand.nextInt(2);

        background[i][2] = background[i][2] + background[i][6] / delta / 10;
        background[i][3] = background[i][3] + background[i][7] / delta / 10;

        Path2D tmp = new Path2D.Double();
        tmp.moveTo(background[i][0], background[i][1]);
        tmp.curveTo(
            background[i][0],
            background[i][1],
            background[i][2],
            background[i][3],
            background[i][4],
            background[i][5]);
        g2d.draw(tmp);
      }
    }
  }

  void renderUI(Graphics2D g2d) {
    g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
    g2d.setColor(Color.white);
    if (removeMode) g2d.setColor(Color.black);
    if (player.health < 0) player.health = 0;
    g2d.drawString(String.format("Helath: %s", player.health), 10, 20);
    g2d.drawString(String.format("Kills: %s", player.score), 10, 40);
    int WLevel = (Integer) player.weapon[player.currentWeapon][10];
    if (WLevel == 5)
      g2d.drawString(String.format("Current Weapon: %s:Max", player.currentWeapon), 10, 60);
    else
      g2d.drawString(String.format("Current Weapon: %s:%s", player.currentWeapon, WLevel), 10, 60);
    g2d.setColor(Color.gray);
    g2d.drawString(String.format("Level: %s", difficulty), 10, 80);
    g2d.setColor(Color.black);
    if (showDebug) g2d.drawString(String.format("FPS: %s", fps), 10, 100);
    if (cheated) g2d.drawString("You cheated, no highscore will be saved", 200, height - 15);
  }

  void renderer(Graphics2D g2d) {
    height = window.getHeight() - 20;
    width = window.getWidth();

    lastTime = curTime;
    curTime = System.currentTimeMillis();
    totalTime += curTime - lastTime;
    if (totalTime > 1000) {
      totalTime -= 1000;
      fps = frames;
      frames = 0;
    }
    ++frames;

    delta = 16.0 / (curTime - lastTime);
    if (delta < 0) delta = 0;

    g2d.setColor(Color.white);
    if (removeMode) g2d.fill(new Rectangle(0, 0, width, height));

    if (eventHandeler(g2d)) {
      renderBackground(g2d);
      return;
    }

    Graphics2D map = (Graphics2D) g2d.create();
    playerHandeler();
    xOffset = -player.body.getCenterX() + width / 2;
    yOffset = -player.body.getCenterY() + height / 2;

    if (-xOffset < bounds.getBounds2D().getX()) xOffset = -bounds.getBounds2D().getX();
    else if (-xOffset > bounds.getBounds2D().getMaxX() - width)
      xOffset = -bounds.getBounds2D().getMaxX() + width;

    if (-yOffset < bounds.getBounds2D().getY()) yOffset = -bounds.getBounds2D().getY();
    else if (-yOffset > bounds.getBounds2D().getMaxY() - height + 3)
      yOffset = -bounds.getBounds2D().getMaxY() + height - 3;

    map.translate(xOffset, yOffset);

    renderBackground(map);
    itemHandeler(map);
    enemieHandeler();
    characterHandeler(map);

    map.setColor(Color.black);
    map.draw(bounds);

    renderUI(g2d);
  }
}
Exemplo n.º 23
0
public class Grid_ implements PlugIn, DialogListener {
  private static String[] colors = {
    "Red", "Green", "Blue", "Magenta", "Cyan", "Yellow", "Orange", "Black", "White"
  };
  private static String color = "Cyan";
  private static String[] types = {"Lines", "Crosses", "Points", "None"};
  private static String type = types[0];
  private static double areaPerPoint;
  private static boolean randomOffset;
  private Random random = new Random(System.currentTimeMillis());
  private ImagePlus imp;
  private double tileWidth, tileHeight;
  private int xstart, ystart;
  private int linesV, linesH;
  private double pixelWidth = 1.0, pixelHeight = 1.0;
  private String units = "pixels";

  public void run(String arg) {
    imp = IJ.getImage();
    showDialog();
  }

  void drawPoints() {
    int one = 1;
    int two = 2;
    GeneralPath path = new GeneralPath();
    for (int h = 0; h < linesV; h++) {
      for (int v = 0; v < linesH; v++) {
        float x = (float) (xstart + h * tileWidth);
        float y = (float) (ystart + v * tileHeight);
        path.moveTo(x - two, y - one);
        path.lineTo(x - two, y + one);
        path.moveTo(x + two, y - one);
        path.lineTo(x + two, y + one);
        path.moveTo(x - one, y - two);
        path.lineTo(x + one, y - two);
        path.moveTo(x - one, y + two);
        path.lineTo(x + one, y + two);
      }
    }
    showGrid(path);
  }

  void drawCrosses() {
    GeneralPath path = new GeneralPath();
    float arm = 5;
    for (int h = 0; h < linesV; h++) {
      for (int v = 0; v < linesH; v++) {
        float x = (float) (xstart + h * tileWidth);
        float y = (float) (ystart + v * tileHeight);
        path.moveTo(x - arm, y);
        path.lineTo(x + arm, y);
        path.moveTo(x, y - arm);
        path.lineTo(x, y + arm);
      }
    }
    showGrid(path);
  }

  void showGrid(Shape shape) {
    ImageCanvas ic = imp.getCanvas();
    if (ic == null) return;
    if (shape == null) ic.setDisplayList(null);
    else ic.setDisplayList(shape, getColor(), null);
  }

  void drawLines() {
    GeneralPath path = new GeneralPath();
    int width = imp.getWidth();
    int height = imp.getHeight();
    for (int i = 0; i < linesV; i++) {
      float xoff = (float) (xstart + i * tileWidth);
      path.moveTo(xoff, 0f);
      path.lineTo(xoff, height);
    }
    for (int i = 0; i < linesH; i++) {
      float yoff = (float) (ystart + i * tileHeight);
      path.moveTo(0f, yoff);
      path.lineTo(width, yoff);
    }
    showGrid(path);
  }

  void showDialog() {
    int width = imp.getWidth();
    int height = imp.getHeight();
    Calibration cal = imp.getCalibration();
    int places;
    if (cal.scaled()) {
      pixelWidth = cal.pixelWidth;
      pixelHeight = cal.pixelHeight;
      units = cal.getUnits();
      places = 2;
    } else {
      pixelWidth = 1.0;
      pixelHeight = 1.0;
      units = "pixels";
      places = 0;
    }
    if (areaPerPoint == 0.0)
      areaPerPoint =
          (width * cal.pixelWidth * height * cal.pixelHeight) / 81.0; // default to 9x9 grid
    ImageWindow win = imp.getWindow();
    GenericDialog gd = new GenericDialog("Grid...");
    gd.addChoice("Grid Type:", types, type);
    gd.addNumericField("Area per Point:", areaPerPoint, places, 6, units + "^2");
    gd.addChoice("Color:", colors, color);
    gd.addCheckbox("Random Offset", randomOffset);
    gd.addDialogListener(this);
    gd.showDialog();
    if (gd.wasCanceled()) showGrid(null);
  }

  public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
    int width = imp.getWidth();
    int height = imp.getHeight();
    type = gd.getNextChoice();
    areaPerPoint = gd.getNextNumber();
    color = gd.getNextChoice();
    randomOffset = gd.getNextBoolean();

    double minArea = (width * height) / 50000.0;
    if (type.equals(types[1]) && minArea < 144.0) minArea = 144.0;
    else if (minArea < 16) minArea = 16.0;
    if (areaPerPoint / (pixelWidth * pixelHeight) < minArea) {
      String err = "\"Area per Point\" too small";
      if (gd.wasOKed()) IJ.error("Grid", err);
      else IJ.showStatus(err);
      return true;
    }
    double tileSize = Math.sqrt(areaPerPoint);
    tileWidth = tileSize / pixelWidth;
    tileHeight = tileSize / pixelHeight;
    if (randomOffset) {
      xstart = (int) (random.nextDouble() * tileWidth);
      ystart = (int) (random.nextDouble() * tileHeight);
    } else {
      xstart = (int) (tileWidth / 2.0 + 0.5);
      ystart = (int) (tileHeight / 2.0 + 0.5);
    }
    linesV = (int) ((width - xstart) / tileWidth) + 1;
    linesH = (int) ((height - ystart) / tileHeight) + 1;
    if (gd.invalidNumber()) return true;
    if (type.equals(types[0])) drawLines();
    else if (type.equals(types[1])) drawCrosses();
    else if (type.equals(types[2])) drawPoints();
    else showGrid(null);
    return true;
  }

  Color getColor() {
    Color c = Color.cyan;
    if (color.equals(colors[0])) c = Color.red;
    else if (color.equals(colors[1])) c = Color.green;
    else if (color.equals(colors[2])) c = Color.blue;
    else if (color.equals(colors[3])) c = Color.magenta;
    else if (color.equals(colors[4])) c = Color.cyan;
    else if (color.equals(colors[5])) c = Color.yellow;
    else if (color.equals(colors[6])) c = Color.orange;
    else if (color.equals(colors[7])) c = Color.black;
    else if (color.equals(colors[8])) c = Color.white;
    return c;
  }
}
Exemplo n.º 24
0
  @Override
  public void onStart(Node node) {
    ParameterTree paramTree = node.newParameterTree();
    mapFileName = paramTree.getString(node.resolveName("~/mapFileName"));

    last_localization = System.currentTimeMillis();

    try {
      polymap = new PolygonMap(mapFileName);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Point2D.Double robotStart = polymap.getRobotStart();

    Rectangle2D.Double cSpaceWorld =
        CSpace.CSpaceWorldRect(polymap.getWorldRect(), polymap.getRobotStart(), RADIUS);
    List<PolygonObstacle> cSpaceObstacles =
        CSpace.computeCSpace(polymap, getRobot(), polymap.getRobotStart());

    Map<int[], Point2D.Double> fiducialPairs = new HashMap<int[], Point2D.Double>();

    // Finish adding to fiducial pairs here from map

    localization = new Localization(cSpaceObstacles, cSpaceWorld, robotStart, fiducialPairs);

    blobTrack = new BlobTracking(width, height);
    final boolean reverseRGB = node.newParameterTree().getBoolean("reverse_rgb", false);

    localPub = node.newPublisher("/rss/localization", "rss_msgs/OdometryMsg");
    stopPub = node.newPublisher("/rss/stop", "rss_msgs/ResetMsg");

    vidSub = node.newSubscriber("/rss/video", "sensor_msgs/Image");
    vidSub.addMessageListener(
        new MessageListener<org.ros.message.sensor_msgs.Image>() {
          @Override
          public void onNewMessage(org.ros.message.sensor_msgs.Image message) {
            byte[] rgbData;
            if (reverseRGB) {
              rgbData = Image.RGB2BGR(message.data, (int) message.width, (int) message.height);
            } else {
              rgbData = message.data;
            }
            assert ((int) message.width == width);
            assert ((int) message.height == height);
            handle(rgbData);
          }
        });

    depthSub = node.newSubscriber("/rss/depth", "sensor_msgs/Image");
    depthSub.addMessageListener(
        new MessageListener<org.ros.message.sensor_msgs.Image>() {
          @Override
          public void onNewMessage(org.ros.message.sensor_msgs.Image message) {
            byte[] rgbData;
            if (reverseRGB) {
              rgbData = Image.RGB2BGR(message.data, (int) message.width, (int) message.height);
            } else {
              rgbData = message.data;
            }
            assert ((int) message.width == width);
            assert ((int) message.height == height);
            handle(rgbData);
          }
        });

    odoSub = node.newSubscriber("/rss/odometry", "rss_msgs/OdometryMsg");
    odoSub.addMessageListener(
        new MessageListener<org.ros.message.rss_msgs.OdometryMsg>() {
          @Override
          public void onNewMessage(org.ros.message.rss_msgs.OdometryMsg message) {
            odo_x = message.x;
            odo_y = message.y;
            odo_theta = message.theta;

            Point2D.Double curr_point;
            OdometryMsg msg = new OdometryMsg();
            if (LOCALIZE) {
              synchronized (localization) {
                curr_point = localization.encoderUpdate(odo_x, odo_y);
              }
              msg.x = curr_point.x;
              msg.y = curr_point.y;
            } else {
              msg.x = odo_x;
              msg.y = odo_y;
            }
            msg.theta = odo_theta;
            localPub.publish(msg);
          }
        });

    Thread visionThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                handleImage();
                try {
                  Thread.sleep(10);
                } catch (Exception exc) {
                  exc.printStackTrace();
                }
              }
            });
    visionThread.start();
  }
Exemplo n.º 25
0
  public static void main(String[] args) {
    long time;
    long answer;
    boolean errors = false;
    long desiredAnswer;

    time = System.currentTimeMillis();
    answer = new AvoidRoads().numWays(6, 6, new String[] {"0 0 0 1", "6 6 5 6"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 252L;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new AvoidRoads().numWays(1, 1, new String[] {});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 2L;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new AvoidRoads().numWays(35, 31, new String[] {});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 6406484391866534976L;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new AvoidRoads().numWays(2, 2, new String[] {"0 0 1 0", "1 2 2 2", "1 1 2 1"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 0L;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();

    if (errors) System.out.println("Some of the test cases had errors :-(");
    else System.out.println("You're a stud (at least on the test data)! :-D ");
  }
Exemplo n.º 26
0
  public static void main(String[] args) {
    long time;
    int[] answer;
    boolean errors = false;
    int[] desiredAnswer;

    boolean same;

    time = System.currentTimeMillis();
    answer = new HappyCells().getHappy(new String[] {"XXX", "X.X", "XXX"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = new int[] {1, 0, 0};
    System.out.println("Your answer:");
    if (answer.length > 0) {
      System.out.print("\t{ " + answer[0]);
      for (int i = 1; i < answer.length; i++) System.out.print(", " + answer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    System.out.println("Desired answer:");
    if (desiredAnswer.length > 0) {
      System.out.print("\t{ " + desiredAnswer[0]);
      for (int i = 1; i < desiredAnswer.length; i++) System.out.print(", " + desiredAnswer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    same = desiredAnswer.length == answer.length;
    for (int i = 0; i < answer.length && same; i++) if (answer[i] != desiredAnswer[i]) same = false;
    if (!same) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new HappyCells().getHappy(new String[] {"."});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = new int[] {1, 0, 0};
    System.out.println("Your answer:");
    if (answer.length > 0) {
      System.out.print("\t{ " + answer[0]);
      for (int i = 1; i < answer.length; i++) System.out.print(", " + answer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    System.out.println("Desired answer:");
    if (desiredAnswer.length > 0) {
      System.out.print("\t{ " + desiredAnswer[0]);
      for (int i = 1; i < desiredAnswer.length; i++) System.out.print(", " + desiredAnswer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    same = desiredAnswer.length == answer.length;
    for (int i = 0; i < answer.length && same; i++) if (answer[i] != desiredAnswer[i]) same = false;
    if (!same) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer =
        new HappyCells().getHappy(new String[] {"XXXXXX", "X.XXXX", "XXX.XX", "X..XXX", "XXXXXX"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = new int[] {1, 1, 1};
    System.out.println("Your answer:");
    if (answer.length > 0) {
      System.out.print("\t{ " + answer[0]);
      for (int i = 1; i < answer.length; i++) System.out.print(", " + answer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    System.out.println("Desired answer:");
    if (desiredAnswer.length > 0) {
      System.out.print("\t{ " + desiredAnswer[0]);
      for (int i = 1; i < desiredAnswer.length; i++) System.out.print(", " + desiredAnswer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    same = desiredAnswer.length == answer.length;
    for (int i = 0; i < answer.length && same; i++) if (answer[i] != desiredAnswer[i]) same = false;
    if (!same) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new HappyCells().getHappy(new String[] {"..."});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = new int[] {0, 0, 3};
    System.out.println("Your answer:");
    if (answer.length > 0) {
      System.out.print("\t{ " + answer[0]);
      for (int i = 1; i < answer.length; i++) System.out.print(", " + answer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    System.out.println("Desired answer:");
    if (desiredAnswer.length > 0) {
      System.out.print("\t{ " + desiredAnswer[0]);
      for (int i = 1; i < desiredAnswer.length; i++) System.out.print(", " + desiredAnswer[i]);
      System.out.println(" }");
    } else System.out.println("\t{ }");
    same = desiredAnswer.length == answer.length;
    for (int i = 0; i < answer.length && same; i++) if (answer[i] != desiredAnswer[i]) same = false;
    if (!same) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();

    if (errors) System.out.println("Some of the test cases had errors :-(");
    else System.out.println("You're a stud (at least on the test data)! :-D ");
  }
  public static void main(String[] args) {
    long time;
    int answer;
    boolean errors = false;
    int desiredAnswer;

    time = System.currentTimeMillis();
    answer = new TheQuestionsAndAnswersDivOne().find(2, new String[] {"No", "Yes"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 2;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new TheQuestionsAndAnswersDivOne().find(2, new String[] {"No", "No", "No"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 6;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new TheQuestionsAndAnswersDivOne().find(3, new String[] {"Yes", "No", "No", "Yes"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 12;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new TheQuestionsAndAnswersDivOne().find(3, new String[] {"Yes", "Yes", "Yes", "No"});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 18;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();

    if (errors) System.out.println("Some of the test cases had errors :-(");
    else System.out.println("You're a stud (at least on the test data)! :-D ");
  }
Exemplo n.º 28
0
  public static void main(String[] args) {
    long time;
    int answer;
    boolean errors = false;
    int desiredAnswer;

    time = System.currentTimeMillis();
    answer = new CuttingBitString().getmin("101101101");
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 3;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new CuttingBitString().getmin("1111101");
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 1;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new CuttingBitString().getmin("00000");
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = -1;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new CuttingBitString().getmin("110011011");
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 3;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new CuttingBitString().getmin("1000101011");
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = -1;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new CuttingBitString().getmin("111011100110101100101110111");
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 5;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();

    if (errors) System.out.println("Some of the test cases had errors :-(");
    else System.out.println("You're a stud (at least on the test data)! :-D ");
  }
Exemplo n.º 29
0
 public Memento createMemento(String a_description) {
   m_modifiedTime = System.currentTimeMillis();
   byte[] bytes = m_glyph.makeTextDocument().getBytes();
   return new Memento(a_description, bytes);
 }
Exemplo n.º 30
0
  public static void main(String[] args) {
    long time;
    double answer;
    boolean errors = false;
    double desiredAnswer;

    time = System.currentTimeMillis();
    answer = new MarblePositioning().totalWidth(new int[] {1, 2, 3, 4, 5, 6, 7, 8});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 50.58155219373389;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new MarblePositioning().totalWidth(new int[] {7, 7, 7});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 28.0D;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new MarblePositioning().totalWidth(new int[] {10, 20, 30});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 62.92528739883945D;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer = new MarblePositioning().totalWidth(new int[] {100, 100, 11, 11, 25});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 200.0D;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();
    time = System.currentTimeMillis();
    answer =
        new MarblePositioning()
            .totalWidth(new int[] {903214, 252429, 550970, 58607, 889016, 695517});
    System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds");
    desiredAnswer = 4430821.778043712D;
    System.out.println("Your answer:");
    System.out.println("\t" + answer);
    System.out.println("Desired answer:");
    System.out.println("\t" + desiredAnswer);
    if (answer != desiredAnswer) {
      errors = true;
      System.out.println("DOESN'T MATCH!!!!");
    } else System.out.println("Match :-)");
    System.out.println();

    if (errors) System.out.println("Some of the test cases had errors :-(");
    else System.out.println("You're a stud (at least on the test data)! :-D ");
  }