Java Reference
In-Depth Information
paddle .draw(g2) ;
if
(gameStarted)
{
player .draw(g2) ;
}
}
public void
changeBallSpeed(
int
speed)
{
timer . setDelay(speed) ;
}
...
}
The
setDelay
method of the
Timer
class changes the delay of the timer. The color of
the ball is changed by calling the
changeColor
method on the
Ball
class. Note that the
Ball
class actually does not have a
changeColor
method, and therefore the
changeColor
method of the
BreakoutShape
superclass is called. The stickmen are drawn only when the
game has started.
Note that the
start
and
stop
methods are careful about the value of the variable
timer
.
For example, the variable is initially equal to
null
when the program started. Therefore,
the
pause
method needs to check that the variable is not equal to
null
before it stops
the timer. Conversely, the
start
method needs to make sure that there is no timer that is
currently running. If there is such a timer, then it is stopped before creating and starting
the new timer.
If we run the program so far, we can use the menu to change the color of the ball, the
speed of the ball, and to start and stop the game. The only thing that is left to do is add
the bricks.
11.7 Adding the Bricks
As a last step, let us add the bricks to the game. Every time before we move the ball, we
will now check that the virtual ball will not intersect one or more of the bricks. If it does,
then the ball needs to bounce off the bricks. Note that in the current setup, the virtual ball
can intersect at most two of the bricks. First, let us consider the new
Brick
class.
public class
Brick
extends
BreakoutShape
{
private static final int
HEIGHT = 1 0 ;
private static final int
WIDTH = 3 0 ;
private static final int
BRICK H GAP = 2 ;
private static final int
BRICK V GAP = 2 ;
public
Brick(
int
row ,
int
col , Color color)
{
super
(
new
Rectangle2D .Double(BRICKH GAP + row
∗
(BRICK H GAP +
B r i c k . WIDTH) , BRICK V GAP + c o l
∗
(BRICK V GAP + B r i c k . HEIGHT) ,
WIDTH, HEIGHT ) ,
c o l o r ,
true
);
}
private
Brick(Rectangle2D rectangle , Color color )
{
super
(rectangle , color ,
true
);
}