The Game Panel

The WormPanel class is similar to the GamePanel class developed in Chapter 2, with some additional methods for drawing the game scene. WormPanel contains an extended version of the reportStats() method used for timing the Swing and utility timers in Chapter 2, called printStats(). Its principal extension is to report the average UPS (updates per second) in addition to the average FPS.

A class diagram showing all the WormPanel methods is given in Figure 3-4.

The WormPanel constructor sets up the game components and initializes timing elements:

    public WormPanel(WormChase wc, long period)
    {
      wcTop = wc;
      this.period = period;

      setBackground(Color.white);
      setPreferredSize( new Dimension(PWIDTH, PHEIGHT));

      setFocusable(true);
      requestFocus();    // now has focus, so receives key events
      readyForTermination();

      // create game components
      obs = new Obstacles(wcTop);
      fred = new Worm(PWIDTH, PHEIGHT, obs);

      addMouseListener( new MouseAdapter() {
        public void mousePressed(MouseEvent e)
WormPanel methods in detail

Figure 3-4. WormPanel methods in detail

        { testPress(e.getX(), e.getY()); }
      });

      // set up message font
      font = new Font("SansSerif", Font.BOLD, 24);
      metrics = this.getFontMetrics(font);

      // initialise timing elements
      fpsStore = new double[NUM_FPS];
      upsStore = new double[NUM_FPS];
      for (int i=0; i < NUM_FPS; i++) {
        fpsStore[i] = 0.0;
        upsStore[i] = 0.0;
      }
    }  // end of WormPanel()

The time period intended for each frame ...

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.