Java Reference
In-Depth Information
}
Brick combinedBrick = bricks . get (0) .add( bricks . get (1) ) ;
bounceBall (ball , combinedBrick) ;
}
public void actionPerformed(ActionEvent e)
{
Ball newBall = ball . getVirtualBall () ;
ArrayList < Brick > bricksToBeDeleted = new ArrayList < Brick > () ;
for (Brick brick : bricks) {
if (brick.intersects(newBall)) {
bricksToBeDeleted .add(brick) ;
}
bounceBall(ball , bricksToBeDeleted) ;
for (Brick brick : bricksToBeDeleted)
{
bricks .remove(brick);
if (newBall . intersects (paddle))
{
ba l l . goUp ( ) ;
if (newBall . getX() + newBall . getWidth() / 2 < paddle .getX() +
paddle . getWidth() / 2)
{
ball . goLeft () ;
}
else {
ball . goRight () ;
}
}
else if (ball.getY() > paddle .getY() paddle . getHeight () )
{
player. killPlayer() ;
ba l l . goUp ( ) ;
} ball .move() ;
repaint () ;
}
}
}
In the actionPerformed method, we first collect the bricks that intersect the virtual ball
and bounce the ball off the bricks by calling the bounceBall method. Note that we cannot
delete a brick inside the loop that iterates over the bricks. If we try to do so, an exception
of type ConcurrentModificationException will be generated. The reason is that an array
or an ArrayList cannot be modified while it is traversed using a for-each for loop. An
iterator is created while the elements are traversed and removing an element will make the
method that gets the next element in the list ambiguous.
If the virtual ball intersects a single brick, then we simply check the location of the ball
relative to the brick and change the trajectory of the ball accordingly. This is done in the
first bounceBall method. If there are two bricks that intersect the virtual ball, then we
merge the bricks and call the first bounceBall method again. This case only happens when
the bricks are adjacent horizontally or vertically. Note that it is possible that a ball is both
above and to the right of a brick. In this case, both the horizontal and vertical direction of
the ball will be changed. The class also introduced the createBricks and getRandomColor
methods, which were described in detail in Chapter 9.
We have also changed the paintComponent method. Now it checks if the game has
started and the number of bricks is equal to zero. If this is the case, then this means that
all the bricks have been destroyed and we have won the game. An appropriate message is
 
Search WWH ::




Custom Search