Example #1
1
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // used until/unless gui is created
    consoleHandler = new FancyConsoleHandler();
    // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);

    // todo: why is this here?
    Runtime.getRuntime().addShutdownHook(new ServerShutdownThread());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));
  }
Example #2
1
 static {
   if (Configuration.isMacOS()) {
     System.setProperty("apple.laf.useScreenMenuBar", "true");
     System.setProperty("com.apple.mrj.application.apple.menu.about.name", APP_NAME);
     System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
   }
 }
 /** Implementation of Runnable interface. DO NOT access this method directly. */
 public void run() {
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       true); // animated frames are updated by this thread so no need to repaint
   long sleepTime = delayTime;
   while (animationThread == Thread.currentThread()) {
     long currentTime = System.currentTimeMillis();
     for (int i = 0; i < stepsPerDisplay; i++) {
       doStep();
       stepCounter++;
       if (animationThread != Thread.currentThread()) {
         break; // check for stop condition
       } else {
         Thread.yield(); // give other threads a chance to run if needed
       }
     }
     org.opensourcephysics.display.GUIUtils.renderAnimatedFrames();
     // adjust the sleep time to try and achieve a constant animation rate
     // some VMs will hang if sleep time is less than 10
     sleepTime = Math.max(10, delayTime - (System.currentTimeMillis() - currentTime));
     try {
       Thread.sleep(sleepTime);
     } catch (InterruptedException ie) {
     }
   }
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       false); // animated frames are updated by this thread so no need to repaint
 }
  public final void runMovement() {
    if (!isShowing()) {
      return;
    }
    final int distance;
    final Rectangle bounds = getBounds();
    if (myAnchor == ToolWindowAnchor.LEFT || myAnchor == ToolWindowAnchor.RIGHT) {
      distance = bounds.width;
    } else {
      distance = bounds.height;
    }
    int count = 0;
    myOffset = 0;
    paintImmediately(
        0, 0, getWidth(), getHeight()); // first paint requires more time than next ones
    final long startTime = System.currentTimeMillis();

    while (true) {
      paintImmediately(0, 0, getWidth(), getHeight());
      final long timeSpent = System.currentTimeMillis() - startTime;
      count++;
      if (timeSpent >= myDesiredTimeToComplete) break;
      final double onePaintTime = (double) timeSpent / count;
      int iterations = (int) ((myDesiredTimeToComplete - timeSpent) / onePaintTime);
      iterations = Math.max(1, iterations);
      myOffset += (distance - myOffset) / iterations;
    }
  }
Example #5
0
 void addToRoiManager(ImagePlus imp) {
   if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager())
     IJ.error("run(\"Add to Manager\") may not work in batch mode macros");
   Frame frame = WindowManager.getFrame("ROI Manager");
   if (frame == null) IJ.run("ROI Manager...");
   if (imp == null) return;
   Roi roi = imp.getRoi();
   if (roi == null) return;
   frame = WindowManager.getFrame("ROI Manager");
   if (frame == null || !(frame instanceof RoiManager)) IJ.error("ROI Manager not found");
   RoiManager rm = (RoiManager) frame;
   boolean altDown = IJ.altKeyDown();
   IJ.setKeyUp(IJ.ALL_KEYS);
   if (altDown && !IJ.macroRunning()) IJ.setKeyDown(KeyEvent.VK_SHIFT);
   if (roi.getState() == Roi.CONSTRUCTING) { // wait (up to 2 sec.) until ROI finished
     long start = System.currentTimeMillis();
     while (true) {
       IJ.wait(10);
       if (roi.getState() != Roi.CONSTRUCTING) break;
       if ((System.currentTimeMillis() - start) > 2000) {
         IJ.beep();
         IJ.error("Add to Manager", "Selection is not complete");
         return;
       }
     }
   }
   rm.runCommand("add");
   IJ.setKeyUp(IJ.ALL_KEYS);
 }
Example #6
0
  public static void main(String[] s) {
    System.out.println("STAGE 1");
    System.setProperty("sun.awt.enableExtraMouseButtons", "true");
    boolean propValue = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons"));
    if (!propValue) {
      throw new RuntimeException(
          "TEST FAILED(1) : System property sun.awt.enableExtraMouseButtons = " + propValue);
    }
    if (!Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled()) {
      throw new RuntimeException(
          "TEST FAILED(1) : Toolkit.areExtraMouseButtonsEnabled() returns false");
    }

    System.out.println("STAGE 2");
    System.setProperty("sun.awt.enableExtraMouseButtons", "false");
    propValue = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons"));
    if (propValue) {
      throw new RuntimeException(
          "TEST FAILED(2) : System property sun.awt.enableExtraMouseButtons = " + propValue);
    }
    if (!Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled()) {
      throw new RuntimeException(
          "TEST FAILED(2) : Toolkit.areExtraMouseButtonsEnabled() returns false");
    }
    System.out.println("Test passed.");
  }
Example #7
0
  public static void main(String[] args) {
    JFrame frame = new JFrame("Maze View");

    Random random = new Random();
    long startTime = System.nanoTime();
    MazeNode maze = MazeNode.generate(random, 100, 100);
    System.out.println("Gen : " + elapsedMs(startTime) + "ms");

    startTime = System.nanoTime();
    int sx = 0; // random.nextInt(maze.width);
    int sy = 0; // random.nextInt(maze.height);
    int dx = maze.width - 1; // random.nextInt(maze.width);
    int dy = maze.height - 1; // random.nextInt(maze.height);
    Path path = PathSolver.solve(maze, sx, sy, dx, dy);
    System.out.println("Solve : " + elapsedMs(startTime) + "ms");
    int pathSize = 0;
    PathCell pathIt = path.first;
    while (pathIt != null) {
      pathSize++;
      pathIt = pathIt.next;
    }
    System.out.println("Path Size: " + pathSize);

    frame.add(new JScrollPane(new MazeView(maze, sx, sy, dx, dy, path)));

    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    SwingUtilities.invokeLater(() -> frame.setVisible(true));
  }
Example #8
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
 private MouseOrTabletOperation(
     String name,
     String description,
     WorldPainterView view,
     int delay,
     boolean oneshot,
     String statisticsKey,
     String iconName) {
   super(
       name,
       description,
       (iconName != null) ? iconName : name.toLowerCase().replaceAll("\\s", ""));
   setView(view);
   this.delay = delay;
   this.oneShot = oneshot;
   this.statisticsKey = statisticsKey;
   statisticsKeyUndo = statisticsKey + ".undo";
   legacy =
       (SystemUtils.isMac() && System.getProperty("os.version").startsWith("10.4."))
           || "true"
               .equalsIgnoreCase(
                   System.getProperty("org.pepsoft.worldpainter.disableTabletSupport"));
   if (legacy) {
     logger.warn("Tablet support disabled for operation " + name);
   }
 }
Example #10
0
  /**
   * Returns JPicEdt's install directory w/o trailing "/", provided the command line looks like :
   *
   * <p><code>java -classpath other-class-paths:jpicedt-install-dir/lib/jpicedt.jar jpicedt.JPicEdt
   * </code> (where <code>/</code> may be replaced by the actual respective separator for files on
   * the underlying platform).
   *
   * <p>For Windows platform, the install directory is tried to be detected 1st with the MSWindows
   * file-separator (<code>\</code>), and if this does not work, a subsequent trial is made with
   * <code>/</code>.
   *
   * <p>That is, the old way (java -jar jpicedt.jar) won't work. However, classpath can contain
   * relative pathname (then user.dir get prepended).
   *
   * <p>Code snippet was adapted from jEdit/JEdit.java (http://www.jedit.org).
   *
   * @return the value of the "user.dir" Java property if "lib/jpicedt.jar" wasn't found in the
   *     command line.
   */
  public static String getJPicEdtHome() {

    String classpath = System.getProperty("java.class.path"); // e.g.
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/lib/jpicedt.jar"
    // File.separator = "/" on Unix, "\\" on Windows,...
    String fileSeparator = File.separator;
    int index;
    // File.pathSeparator = ":" on Unix/MacOS-X platforms, ";" on Windows
    // search ":" backward starting from
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/^lib/jpicedt.jar"

    String homeDir = null;
    int trials = 2;
    do {
      index = classpath.toLowerCase().indexOf("lib" + fileSeparator + "jpicedt.jar");
      int start = classpath.lastIndexOf(File.pathSeparator, index);
      if (start == -1)
        start =
            0; // File.pathSeparator not found => lib/jpicedt.jar probably at beginning of classpath
      else start += File.pathSeparator.length(); // e.g. ":^/home..."

      if (index >= start) {
        homeDir = classpath.substring(start, index);
        if (homeDir.endsWith(fileSeparator)) homeDir = homeDir.substring(0, homeDir.length() - 1);
      }
      switch (trials) {
        case 2:
          if (File.pathSeparator.equals(";") && homeDir == null) {
            // MS-Windows case, this must work both with / and \
            trials = 1;
            fileSeparator = "/";
          } else trials = 0;
          break;
        case 1:
          if (homeDir != null && !fileSeparator.equals(File.separator)) {
            homeDir.replace(fileSeparator, File.separator);
          }
          trials = 0;
          break;

        default:
          trials = 0;
          break;
      }
    } while (trials != 0);

    if (homeDir != null) {
      if (homeDir.equals("")) homeDir = System.getProperty("user.dir");
      else if (!new File(homeDir).isAbsolute())
        homeDir = System.getProperty("user.dir") + File.separator + homeDir;
    } else {
      homeDir = System.getProperty("user.dir");
      if (homeDir.endsWith(
          "lib")) // this is the case if jpicedt run as "java -jar jpicedt.jar" from inside lib/ dir
      homeDir = homeDir.substring(0, homeDir.lastIndexOf("lib"));
    }

    // System.out.println("JPicEdt's home = " + homeDir);
    return homeDir;
  }
Example #11
0
 public static void release(int x, int y, int button) {
   int buttonModifiers = getButtonModifiers(button);
   Component target = getTarget();
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_RELEASED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
   isPressed = false;
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_CLICKED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
 }
  public void run() {
    while (true) {
        /* loop forever */
      switch (command) {
        case COMMAND_NONE:
          setTitle("None");
          proxy.stop('A');
          break;
        case COMMAND_FORWARDS:
          setTitle("Forwards");
          direction = DIRECTION_FORWARDS;
          proxy.forward('A');
          break;
        case COMMAND_BACKWARDS:
          setTitle("Backwards");
          direction = DIRECTION_BACKWARDS;
          proxy.backward('A');
          break;
        default:
          System.out.println("unknown command " + command);
          System.exit(1);
      }

      try {
        Thread.sleep(DELAY_MS);
      } catch (Exception e) {
        System.out.println(e);
        System.exit(1);
      }
    }
  }
  private JComponent createLabelsPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(0, 2, 10, 1));

    // Creates a StyledLabel to warn up so that we don't include class loading time into the
    // performance test.
    // This is the same for all three cases.
    new JLabel("Bold Italic Underlined");

    long start = System.currentTimeMillis();
    for (int i = 0; i < COUNT; i++) {
      JLabel label = new JLabel("Bold Italic Underlined");
      panel.add(label);
    }
    panel.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(
                new PartialLineBorder(Color.gray, 1, true),
                " JLabel (Plain) Examples - use " + (System.currentTimeMillis() - start) + " ms ",
                TitledBorder.CENTER,
                TitledBorder.CENTER,
                null,
                Color.RED),
            BorderFactory.createEmptyBorder(6, 4, 4, 4)));
    return panel;
  }
Example #14
0
 @Override
 public int compare(AbstractFoldingAreaPainter afap1, AbstractFoldingAreaPainter afap2) {
   if (afap1.getWeight() == afap2.getWeight() && !afap1.equals(afap2)) {
     return System.identityHashCode(afap1) - System.identityHashCode(afap2);
   }
   return afap1.getWeight() - afap2.getWeight();
 }
  // initialize data hash table servers
  // read server addresses from file and initialize the servers
  private void initServers() {

    try {
      java.net.URL path = ClassLoader.getSystemResource(clientSettingFile);
      FileReader fr = new FileReader(path.getFile());
      BufferedReader br = new BufferedReader(fr);
      try {
        String[] portMap = br.readLine().split(",");
        mServerCount = portMap.length;
        mPortMap = new int[mServerCount];
        for (int i = 0; i < mServerCount; i++) {
          mPortMap[i] = Integer.parseInt(portMap[i]);
        }
      } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
      }
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
      System.exit(-1);
    }

    mDhtServerArray = new IDistributedHashTable[mServerCount];
    for (int i = 0; i < mServerCount; i++) {
      try {
        mDhtServerArray[i] =
            (IDistributedHashTable)
                Naming.lookup("rmi://localhost:" + mPortMap[i] + "/DistributedHashTable");
        appendOutput("server: " + (i + 1) + " is connected");
      } catch (Exception e) {
        appendOutput("initServers: " + (i + 1) + " " + e.getMessage());
      }
    }
  }
Example #16
0
 public static void main(String[] args) {
   try {
     if (args.length != 1) throw new IllegalArgumentException("Wrong number of arguments");
     FileReader in = new FileReader(args[0]);
     HardcopyWriter out = null;
     Frame f = new Frame("PrintFile: " + args[0]);
     f.setSize(200, 50);
     f.show();
     try {
       out = new HardcopyWriter(f, args[0], 10, .75, .75, .75, .75);
     } catch (HardcopyWriter.PrintCanceledException e) {
       System.exit(0);
     }
     f.setVisible(false);
     char[] buffer = new char[4096];
     int numchars;
     while ((numchars = in.read(buffer)) != -1) out.write(buffer, 0, numchars);
     out.close();
   } catch (Exception e) {
     System.err.println(e);
     System.err.println("Usage: java HardcopyWriter$PrintFile <filename>");
     System.exit(1);
   }
   System.exit(0);
 }
    public synchronized void paint(Graphics g) {
      if (needToStartThread) {
        totalDrawTime = 0;
        counter = 0;
        needToStartThread = false;
        startThread(beginAngle, endAngle);
        if (firstImage == null) {
          firstImage = createImageFromComponent(component1);
        }
        if (secondImage == null) {
          secondImage = createImageFromComponent(component2);
        }
      }
      if (firstImage == null || secondImage == null) return;
      Graphics2D g2d = (Graphics2D) g;
      int ww = firstImage.getWidth();
      int hh = firstImage.getHeight();
      {
        BufferedImage currImage = null;
        int[] currPixels = null;
        int w = firstImage.getWidth();
        int offset = (int) (w * angle / 180);
        if (offset < 0) offset = 0;
        if (offset > w) offset = w;

        long beforeDraw = System.currentTimeMillis();
        g2d.drawImage(firstImage, null, 0, 0);
        g2d.drawImage(secondImage, null, w - offset, 0);
        totalDrawTime += (System.currentTimeMillis() - beforeDraw);
        counter++;
      }
    }
  @Override
  public void actionPerformed(ActionEvent AE) {
    if (AE.getSource() == CheckAll) {
      boolean Selection = CheckAll.isSelected();
      if (Selection) CheckAll.setText("Uncheck all");
      else CheckAll.setText("Check all");
      for (int i = 0; i < NumberOfCourses; i++) My[i].CourseCheckBox.setSelected(Selection);
    }

    if (AE.getSource() == DocButton)
      if (TempControll.ConnectionManagerObject.createConnection()) {

        new File(System.getProperty("user.home") + "/TermResultCalculator/StudentDocs/").mkdirs();
        if (gatherDataForDocument()) {
          if (TempControll.StudentPdfObject.createPDF(
              this.Roll, this.Session, this.Selected, this.Taken, this.Completed, this.GPA))
            JOptionPane.showMessageDialog(
                RPS,
                "Report created successfully at "
                    + System.getProperty("user.home")
                    + "/TermResultCalculator/StudentDocs/",
                "Success",
                JOptionPane.INFORMATION_MESSAGE);
          else
            JOptionPane.showMessageDialog(
                RPS, "Error while creating report.", "Error", JOptionPane.ERROR_MESSAGE);
        } else
          JOptionPane.showMessageDialog(
              RPS,
              "At least one course has to be selected.",
              "Error : No Selection",
              JOptionPane.ERROR_MESSAGE);
      }
  }
 public static void main(java.lang.String[] args) {
   String className = null;
   try {
     System.err.println("logging is done using log4j.");
     final ICQMessagingTest_Applet applet = new ICQMessagingTest_Applet();
     className = cfg.REQPARAM_MESSAGING_NETWORK_IMPL_CLASS_NAME.trim();
     CAT.info("Instantiating class \"" + className + "\"...");
     try {
       applet.plugin = (MessagingNetwork) Class.forName(className).newInstance();
       applet.plugin.init();
     } catch (Throwable tr) {
       CAT.error("ex in main", tr);
       System.exit(1);
     }
     java.awt.Frame frame = new java.awt.Frame("MessagingTest");
     frame.addWindowListener(
         new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
             applet.quit();
           }
         });
     frame.add("Center", applet);
     frame.setSize(800, 650);
     frame.setLocation(150, 100);
     applet.init();
     frame.show();
     frame.invalidate();
     frame.validate();
     applet.start();
   } catch (Throwable tr) {
     CAT.error("exception", tr);
     System.exit(1);
   }
 }
 public TestType1CFont(InputStream is) throws IOException {
   super();
   setPreferredSize(new Dimension(800, 800));
   addKeyListener(this);
   BufferedInputStream bis = new BufferedInputStream(is);
   int count = 0;
   ArrayList<byte[]> al = new ArrayList<byte[]>();
   byte b[] = new byte[32000];
   int len;
   while ((len = bis.read(b, 0, b.length)) >= 0) {
     byte[] c = new byte[len];
     System.arraycopy(b, 0, c, 0, len);
     al.add(c);
     count += len;
     b = new byte[32000];
   }
   data = new byte[count];
   len = 0;
   for (int i = 0; i < al.size(); i++) {
     byte from[] = al.get(i);
     System.arraycopy(from, 0, data, len, from.length);
     len += from.length;
   }
   pos = 0;
   //	printData();
   parse();
   // TODO: free up (set to null) unused structures (data, subrs, stack)
 }
  public static void checkSanity() {
    long t = System.currentTimeMillis();

    try {
      r.lock();
      final int fileLength = (int) getRecords().length();
      assert fileLength % RECORD_SIZE == 0;
      int recordCount = fileLength / RECORD_SIZE;

      IntArrayList usedAttributeRecordIds = new IntArrayList();
      IntArrayList validAttributeIds = new IntArrayList();
      for (int id = 2; id < recordCount; id++) {
        int flags = getFlags(id);
        LOG.assertTrue(
            (flags & ~ALL_VALID_FLAGS) == 0,
            "Invalid flags: 0x" + Integer.toHexString(flags) + ", id: " + id);
        if ((flags & FREE_RECORD_FLAG) != 0) {
          LOG.assertTrue(
              DbConnection.myFreeRecords.contains(id),
              "Record, marked free, not in free list: " + id);
        } else {
          LOG.assertTrue(
              !DbConnection.myFreeRecords.contains(id),
              "Record, not marked free, in free list: " + id);
          checkRecordSanity(id, recordCount, usedAttributeRecordIds, validAttributeIds);
        }
      }
    } finally {
      r.unlock();
    }

    t = System.currentTimeMillis() - t;
    LOG.info("Sanity check took " + t + " ms");
  }
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
Example #23
0
  public boolean updateState(Landscape scape) {
    // this method has an added on season change every 1/4 minute

    // first 1/4 minute:
    if ((System.currentTimeMillis() / 15000) % 2 == 0) {
      if ((this.y > scape.getHeight() / 2)
          && (this.x > scape.getWidth() / 2)) { // if this is in the southeast ish
        if (quantity < MAX_QUANTITY) {
          quantity += 2; // grow by 2
        }
      } else { // else grow by 1 each time
        if (quantity < MAX_QUANTITY) {
          quantity++;
        }
      }
    }

    // second 1/4 minute:
    else if ((System.currentTimeMillis() / 15000) % 2 != 0) {
      if ((this.y < (scape.getHeight() / 2))
          && (this.x < scape.getWidth() / 2)) { // if this is in the northwest ish
        if (quantity < MAX_QUANTITY) {
          quantity += 2; // grows by 2
        }
      } else { // else grow by 1 each time
        if (quantity < MAX_QUANTITY) {
          quantity++;
        }
      }
    }

    // System.out.print(this.quantity+",");
    return true; // it can be assumed that this always returns true since peas never die
  }
Example #24
0
  public void saveState(String extension) {
    String directory = (cartridge.romFileName + extension);

    try {
      FileOutputStream fl = new FileOutputStream(directory);
      DataOutputStream sv = new DataOutputStream(fl);

      saveData(sv, directory);

      // write battery ram
      cartridge.saveData(sv, directory);

      // write graphic memory
      graphicsChip.saveData(sv, directory);

      // write io state
      ioHandler.saveData(sv, directory);

      // stats.printStats();

      sv.close();
      fl.close();

    } catch (FileNotFoundException e) {
      System.out.println("Dmgcpu.saveState: Could not open file " + directory);
      System.out.println("Error Message: " + e.getMessage());
      System.exit(-1);
    } catch (IOException e) {
      System.out.println("Dmgcpu.saveState: Could not write to file " + directory);
      System.out.println("Error Message: " + e.getMessage());
      System.exit(-1);
    }

    System.out.println("Saved stage!");
  }
    protected void preCache(List<Position> grid, Position centerPosition)
        throws InterruptedException {
      // Pre-cache the tiles that will be needed for the intersection calculations.
      double n = 0;
      final long start = System.currentTimeMillis();
      for (Position gridPos : grid) // for each grid point.
      {
        final double progress = 100 * (n++ / grid.size());
        terrain.cacheIntersectingTiles(centerPosition, gridPos);

        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                progressBar.setValue((int) progress);
                progressBar.setString(null);
              }
            });
      }

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(100);
            }
          });

      long end = System.currentTimeMillis();
      System.out.printf(
          "Pre-caching time %d milliseconds, cache usage %f, tiles %d\n",
          end - start, terrain.getCacheUsage(), terrain.getNumCacheEntries());
    }
Example #26
0
  /** Execute the specified number of Gameboy instructions. Use '-1' to execute forever */
  public final void execute(int numInstr) {
    terminate = false;
    running = true;
    graphicsChip.startTime = System.currentTimeMillis();
    int b1, b2, b3, offset;

    long t;
    for (int r = 0; (r != numInstr) && (!terminate); r++) {
      t = System.currentTimeMillis();

      instrCount++;

      b1 = JavaBoy.unsign(addressRead(pc));
      offset = addressRead(pc + 1);
      b3 = JavaBoy.unsign(addressRead(pc + 2));
      b2 = JavaBoy.unsign((short) offset);

      // stats.addExecution(b1);
      instructionManager.execute(b1, b2, b3, offset);

      if (ieDelay != -1) {
        if (ieDelay > 0) {
          ieDelay--;
        } else {
          interruptsEnabled = true;
          ieDelay = -1;
        }
      }

      if (interruptsEnabled) {
        checkInterrupts();
      }
      cartridge.update();
      initiateInterrupts();

      if ((t - initialTime) > checkpointTime) {
        initialTime = t;
        saveCheckpointInterrupt = true;
      }

      if (saveInterrupt) {
        saveState(".stsv");
        saveInterrupt = false;
      }
      if (loadStateInterrupt) {
        loadState(".stsv");
        loadStateInterrupt = false;
      }
      if (saveCheckpointInterrupt) {
        saveState(".cksv");
        saveCheckpointInterrupt = false;
      }
      if (loadCheckpointInterrupt) {
        loadState(".cksv");
        loadCheckpointInterrupt = false;
      }
    }
    running = false;
    terminate = false;
  }
 /**
  * This method runs the Runnable and measures how long it takes.
  *
  * @param r is the Runnable for the task that we want to measure
  * @return the time it took to execute this task
  */
 public static long time(Runnable r) {
   long time = -System.currentTimeMillis();
   r.run();
   time += System.currentTimeMillis();
   System.out.println("Took " + time + "ms");
   return time;
 }
  private void tryToInitialize(int counter) {
    boolean existsCompatibleBrowser = getComponent() != null && isCompatible();
    synchronized (this) {
      initialized = existsCompatibleBrowser;
    }
    log.info(System.currentTimeMillis() + " initialized map: " + initialized);

    if (isInitialized()) {
      log.fine(System.currentTimeMillis() + " compatible, further initializing map");
      initializeAfterLoading();
      initializeBrowserInteraction();
      initializeCallbackListener();
      checkLocalhostResolution();
      checkCallback();
    } else {
      if (counter++ < 50) {
        log.info(System.currentTimeMillis() + " WAITING " + counter * 100 + " milliseconds");
        try {
          Thread.sleep(counter * 100);
        } catch (InterruptedException e) {
          // intentionally left empty
        }

        tryToInitialize(counter);
      }
    }
  }
 public void initGame() {
   String cfgname = null;
   if (isApplet()) {
     cfgname = getParameter("configfile");
   } else {
     JFileChooser chooser = new JFileChooser();
     chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
     chooser.setDialogTitle("Choose a config file");
     int returnVal = chooser.showOpenDialog(this);
     if (returnVal == JFileChooser.APPROVE_OPTION) {
       cfgname = chooser.getSelectedFile().getAbsolutePath();
     } else {
       System.exit(0);
     }
     // XXX read this as resource!
     // cfgname = "mygeneratedgame.appconfig";
   }
   gamecfg = new AppConfig("Game parameters", this, cfgname);
   gamecfg.loadFromFile();
   gamecfg.defineFields("gp_", "", "", "");
   gamecfg.saveToObject();
   initMotionPars();
   // unpause and copy settingswhen config window is closed
   gamecfg.setListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           start();
           requestGameFocus();
           initMotionPars();
         }
       });
   defineMedia("simplegeneratedgame.tbl");
   setFrameRate(35, 1);
 }
Example #30
0
  public void run() {

    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;
    int frames = 0;
    int updates = 0;
    //		setFocusable(true);
    requestFocus();

    while (running) {
      long now = System.nanoTime();
      delta += (now - lastTime) / ns;
      lastTime = now;
      while (delta >= 1) {
        update();
        updates++;
        delta--;
      }
      // Renderiza tudo na tela
      render();
      // Calcula FPS
      frames++;

      if ((System.currentTimeMillis() - timer) > 1000) {
        timer += 1000;
        // T�tulo do jogo
        frame.setTitle(title + "  |  " + updates + " ups / " + frames + " fps ");
        updates = 0;
        frames = 0;
      }
    }
    stop();
  }