Java Reference
In-Depth Information
To draw the stickmen, we need to modify the paintComponent method in the
BreakoutPanel class. Of course, we also need to check that there are any lives left be-
fore we draw anything in the method. Here is the rewritten code.
class BreakoutPanel {
private Player player = new Player () ;
...
public void paintComponent(Graphics g)
{
super . paintComponent(g) ;
Graphics2D g2 = (Graphics2D) g ;
if (!player . isAlive())
{
showMessage( "GAME OVER!" ,g2);
return ;
} player .draw(g2) ;
ball .draw(g2);
paddle .draw(g2) ;
} public void showMessage( String s , Graphics2D g2) {
Font myFont = new Font( "SansSerif" , Font .BOLD + Font . ITALIC, 40) ;
g2. setFont(myFont) ;
g2 . setColor (Color .RED) ;
Rectangle2D textBox = myFont. getStringBounds(s , g2.
getFontRenderContext () ) ;
g2. drawString(s , ( int ) (getWidth() / 2 textBox . getWidth() / 2) , (
int ) (getHeight () / 2 textBox . getHeight ())) ;
}
}
We also need to modify the code when the ball goes under the paddle. Instead of exiting
the program, we will start moving the ball upward and kill the player (i.e., remove one life).
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 () )
ba l l . goUp ( ) ;
player. killPlayer() ;
} ball .move() ;
repaint () ;
}
}
}
If you run the game now, three stickmen will appear. Every time we are unable to catch
the ball with the paddle, a stickman will be lost. When we lose all three stickmen, the
message GAME OVER will appear.
 
Search WWH ::




Custom Search