The Worm-Chasing Application


Figure 3-3 shows a class diagram for WormChase, including all its variables and methods.

Figure 3-3. WormChase in detail


The main( ) function in WormChase reads the requested FPS from the command line, converting it to a delay in nanoseconds, which is passed to the WormChase( ) constructor:

     public static void main(String args[])     {       int fps = DEFAULT_FPS;       if (args.length != 0)         fps = Integer.parseInt(args[0]);       long period = (long) 1000.0/fps;       System.out.println("fps: " + fps + "; period: " +period+ " ms");       new WormChase(period*1000000L);    // ms --> nanosecs     }

The WormChase constructor creates the WormPanel canvas, as well as two text fields for displaying the number of boxes added to the scene (jtfBox) and the current time (jtfTime). These text fields can be updated via two public methods:

     public void setBoxNumber(int no)     {  jtfBox.setText("Boxes used: " + no);  }     public void setTimeSpent(long t)     {  jtfTime.setText("Time Spent: " + t + " secs"); }

setBoxNumber( ) is called from the Obstacles object when a new box (obstacle) is created. setTimeSpent( ) is called from WormPanel.

The pausing, resumption, and termination of the game are managed through window listener methods (WormChase implements WindowListener). Pausing is triggered by window deactivation or iconification; the application resumes when the window is activated or de-iconified, and the clicking of the window close box causes termination:

     public void windowActivated(WindowEvent e)     { wp.resumeGame( );  }     public void windowDeactivated(WindowEvent e)     {  wp.pauseGame( );  }     public void windowDeiconified(WindowEvent e)     {  wp.resumeGame( );  }     public void windowIconified(WindowEvent e)     {  wp.pauseGame( ); }     public void windowClosing(WindowEvent e)    {  wp.stopGame( );  }

wp refers to the WormPanel object.




Killer Game Programming in Java
Killer Game Programming in Java
ISBN: 0596007302
EAN: 2147483647
Year: 2006
Pages: 340

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net