Worm Obstacles


The Obstacles object maintains an array of Rectangle objects called boxes. Each object contains the top-left hand coordinate of a box and the length of its square sides.

The public methods in the Obstacles class are synchronized since the event thread of the game could add a box to the obstacles list (via a call to add( )) while the animation thread is examining or drawing the list.

add( ) is defined as

     synchronized public void add(int x, int y)     {       boxes.add( new Rectangle(x,y, BOX_LENGTH, BOX_LENGTH));       wcTop.setBoxNumber( boxes.size( ) );   // report new no. of boxes     }

The method updates the boxes text field at the top-level of the game by calling setBoxNumber( ).

WormPanel delegates the task of drawing the obstacles to the Obstacles object, by calling draw( ):

     synchronized public void draw(Graphics g)     // draw a series of blue boxes     {       Rectangle box;       g.setColor(Color.blue);       for(int i=0; i < boxes.size( ); i++) {         box = (Rectangle) boxes.get(i);         g.fillRect( box.x, box.y, box.width, box.height);       }     }  // end of draw( )

Worm communicates with Obstacles to determine if its new head (a Point object, p) intersects with any of the boxes:

     synchronized public boolean hits(Point p, int size)     {       Rectangle r = new Rectangle(p.x, p.y, size, size);       Rectangle box;       for(int i=0; i < boxes.size( ); i++) {         box = (Rectangle) boxes.get(i);         if (box.intersects(r))           return true;       }       return false;     }  // end of hits( )



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