Java Reference
In-Depth Information
11.5 Drawing the Stickmen
Next, we will add code that keeps track of the number of lives. Let us first start with
the
Player
class that keeps track of the number of available lives and draws stickmen for
them.
import
java .awt .
∗
;
import
java. io .File ;
import
javax . imageio .ImageIO;
public class
Player
{
private static int
INITIAL NUM LIVES = 3 ;
private static int
IMAGE Y POSITION = 450;
private static int
IMAGE H GAP = 5 ;
private int
numLives ;
public
Player ()
{
this
. numLives = INITIAL NUM LIVES ;
}
public void
killPlayer()
{
numLives
−−
;
}
public boolean
isAlive()
{
return
(numLives
>
0) ;
}
public void
draw(Graphics2D g2)
{
try
{
Image image = ImageIO. read (
new
File(
"player.gif"
));
for
(
int
x=0;x
<
numLives ; x++)
{
g2 . drawImage( image , x
∗
(image . getWidth(
null
)+IMAGEH GAP) ,
IMAGE Y POSITION ,
null
);
}
}
catch
(Exception newException)
{
}
}
}
The code starts with 3 lives, where this number is saved in a constant and can be
changed. The
killPlayer
method removes a life, while the
isAlive
method reports on
whether there are lives left. Note that this is an excellent example of data encapsulation
because the world outside the class does not know how many lives are left. It does not know
because it does not need to know. As is the case in the CIA, information between classes
should be shared only on a need-to-know basis. The less information that is shared, the
easier it is to identify erroneous code.
The
draw
method draws a stickman for each available life. In our code, the image of
a stickman is saved in
player.gif
. Feel free to create your own image. Depending on the
size of the image, the variable
IMAGE Y POSITION
mayhavetobemodified.Notethatthe
method has a
try-catch
block, which is formally explained in Chapter 13. The reason is
that the code can raise an exception if the file
player.gif
does not exist. The code does
nothing to handle the exception.