Java Reference
In-Depth Information
The method checks to see if the two shapes intersect. The RectangularShape class has
an intersects method that takes as input an object of type Rectangle2D and checks if the
two shapes intersect. The getBounds method returns the bounds of a RectangularShape
as an object of type Rectangle2D .
The updated code for the BreakoutPanel class is shown next.
public BreakoutPanel ()
public BreakoutPanel () {
timer = new javax . swing .Timer(10 , new TimeListener () ) ;
class TimeListener implements ActionListener
public void actionPerformed(ActionEvent e)
Ball newBall = ball . getVirtualBall () ;
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 () )
System. exit(0) ;
} ball .move() ;
repaint () ;
Note that the TimeListener class is now an inner class instead of a local anonymous
class. The reason is that the class is becoming large and we decided to give it a name.
Creating a large local anonymous class can put extra burden on someone who tries to
understand how the program works. The actionPerformed method creates a virtual ball
and checks to see if the virtual ball intersects the paddle. If it does, it first changes the
ball direction to up. Since the ball has hit the panel, it should not continue going down.
Next, the program checks to see if the ball intersects the left or right part of the paddle.
The expression newBall.getX() + newBall.getWidth()/2 gives the X value of the middle
of the ball, while the expression paddle.getX() + paddle.getWidth() / 2 returns the X
coordinate of the middle of the paddle. If the virtual ball is predominantly in the left part
of the paddle, then the ball goes next to the left. Conversely, if the virtual ball touches the
right part of the paddle, then the ball bounces to the right. We have also added a simple
code that checks if the ball is below the paddle. For now, this code simply exits the program.
If we run and compile the program, we will see that the ball now bounces off the paddle.
If we are unable to catch the ball, then the game ends. In order to prevent the game from
ending, we will need to keep track of the number of lives.
Search WWH ::

Custom Search