CHAPTER 12 ■ VIDEO GAMES
if (!targets[i].isDone()) {
// if not done, draw it in the game area
targets[i].draw(g);
} else {
// if it is done, make a new one and put it in the array;
// the old one can then be garbage collected
// as no reference to it now exists
targets[i] = new Target(this);
}
}
}
// We have to have this method to fulfill the MouseListener contract
@Override
public void mouseClicked(MouseEvent e) {
}
// We have to have this method to fulfill the MouseListener contract
@Override
public void mouseEntered(MouseEvent e) {
}
// We have to have this method to fulfill the MouseListener contract
@Override
public void mouseExited(MouseEvent e) {
}
// We have to have this method to fulfill the MouseListener contract
@Override
public void mousePressed(MouseEvent e) {
}
// Here's where we check for user input within the game field
// and check to see if the input changes the game
// (because the user hit a target)
@Override
public void mouseReleased(MouseEvent e) {
for (int i = 0; i < targets.length; i++) {
targets[i].pointInTarget(e.getX(), e.getY());
}
}
}
As we've just seen, the TargetClickPanel class only provides a place for targets to appear, handles
mouse clicks in the play area (the TargetClick class handles mouse clicks in the menu and the frame),
and keeps the five targets in play.
The Target class has the simplest mission of the three classes that comprise the TargetClick game: It
draws a target and figures out whether a target has been hit. That may seem like too much to do, and
your first instinct may be to move the hit logic out of this class. However, an instance of the Target class
has to stop drawing its target if the player hits the target. Consequently, it makes sense to put the hit
logic in the Target class. Again, giving each class a clear purpose trumps separating logic from
presentation. When deciding whether to separate code, ask yourself two useful questions: Can I separate