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()Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access