Java Reference
In-Depth Information
Lastly, the
SpeedMenu
class takes care of the speed menu. Again, since the ball is declared
inside the panel, a method from the panel class needs to be called to change the speed of
the ball.
Next, we will present the new code for the
BreakoutPanel
class. Note that now the ball
does not start automatically. Therefore, the timer will be started in the
start
method and
stopped in the
pause
method. We will also stop the timer when all lives are exhausted.
However, we need to allow the option for the user to restart the game after the game
finishes. For that reason, we introduce the Boolean variable
gameStarted
, which keeps
track of whether or not the game is started.
public class
BreakoutPanel
extends
JPanel
{
private
javax . swing .Timer timer ;
private
Ball ball ;
private
Paddle paddle ;
private
Player player ;
private boolean
gameStarted =
false
;
...
public void
start()
{
gameStarted =
true
;
if
(timer !=
null
)
{
timer . stop() ;
if
(!player . isAlive())
{
player =
new
Player () ;
// restart
the game
ball =
new
Ball (Color .RED,
this
);
timer =
new
javax . swing .Timer(BallSpeed .NORMAL. speed() ,
new
BreakoutPanel . TimeListener () ) ;
timer. start() ;
repaint () ;
}
public void
pause ()
{
if
(timer ==
null
)
{
return
;
timer . stop() ;
}
public void
changeBallColor(BallColor color )
{
ball .changeColor(color . color());
repaint () ;
}
public void
paintComponent(Graphics g)
{
super
. paintComponent(g) ;
Graphics2D g2 = (Graphics2D) g ;
if
(!player . isAlive())
{
showMessage(
"GAME OVER!"
,g2);
gameStarted =
false
;
}
else
{
ball .draw(g2);