Ejemplo n.º 1
0
  /** Starts the game running. */
  private void startGame() {
    /*
     * Initialize everything we're going to be using.
     */
    this.random = new Random();
    this.snake = new LinkedList<>();
    this.directions = new LinkedList<>();
    this.logicTimer = new Clock(9.0f);
    this.isNewGame = true;

    // Set the timer to paused initially.
    logicTimer.setPaused(true);

    /*
     * This is the game loop. It will update and render the game and will
     * continue to run until the game window is closed.
     */
    while (true) {
      // Get the current frame's start time.
      long start = System.nanoTime();

      // Update the logic timer.
      logicTimer.update();

      /*
       * If a cycle has elapsed on the logic timer, then update the game.
       */
      if (logicTimer.hasElapsedCycle()) {
        updateGame();
      }

      // Repaint the board and side panel with the new content.
      board.repaint();
      side.repaint();

      /*
       * Calculate the delta time between since the start of the frame
       * and sleep for the excess time to cap the frame rate. While not
       * incredibly accurate, it is sufficient for our purposes.
       */
      long delta = (System.nanoTime() - start) / 1000000L;
      if (delta < FRAME_TIME) {
        try {
          Thread.sleep(FRAME_TIME - delta);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }