Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 12 ■ VIDEO GAMES


targets.remove(currentTarget);
} else {
currentTarget.setY(currentTarget.getY() + ShootingGalleryPanel.TARGET_SPACE / 10);
currentTarget.draw(g);
}
}
}

public void tick() {
for (int targetCounter = 0; targetCounter < targets.size(); targetCounter ++) {
ShootingGalleryTarget currentTarget = targets.get(targetCounter);
currentTarget.setY(currentTarget.getY() + ShootingGalleryPanel.TARGET_SPACE / 10);
}
newTargetTicker++;
if (newTargetTicker > 9) {
newTargetTicker = 0;
ShootingGalleryTarget newTarget =
new ShootingGalleryTarget(targetValue, sprite, 0,
-ShootingGalleryPanel.TARGET_SPACE, this);
targets.add(newTarget);
}
repaint();
}
}

The ShootingGalleryTargetRow class handles the targets in a given row. The paintComponent method
removes targets that move off the bottom and draws all the remaining targets in the row (the
ShootingGalleryShooter class, which handles the player's cursor, removes targets that get shot). The
tick method handles updating the information about the collection of targets. In particular, the tick
method adds a new target to the top of the row every tenth tick, which has the effect of constantly
replenishing the row (one possible way to limit the time the game runs is to limit the total number of
targets in each row – run out of targets and the game is over. Feel free to implement that idea if it
interests you).
Using a LinkedList object to hold the targets allows for adding and removing targets without having
to have a fixed number of targets. Given that targets get shot, the number of targets fluctuates, so we
need a data structure that accommodates the fluctuation.
Now that we've seen how rows of targets work, let’s move on to the actual Target objects.

Listing 12-8. The ShootingGalleryTarget class

package com.bryantcs.examples.videogames;

import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Image;

public class ShootingGalleryTarget {

// The integer things we need to know: value, size, position,
// and offset from the edge of the row (for centering)
private int value, size, xPosition, yPosition, offset;
Free download pdf