Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 12 ■ VIDEO GAMES


currentStep++;
readyToShoot = false;
} else {
// Otherwise, let the player shoot
readyToShoot = true;
}

// repaint the cursor (otherwise, the cursor won't move)
repaint();
}
}

The ShootingGalleryShooter class handles the only object the player controls: the cursor that
indicates both where a shot will go and whether the player can shoot. Remember that the timer in the
ShootingGalleryPanel class ticks fifty times a second. For that reason, the ShootingGalleryShooter class
keeps track of fifty steps, so that it can impose a one-second delay between shots. Then it uses those 50
steps to draw the cursor's vertical bar, setting it to yellow when a player shoots and, over the course of a
second, setting it back to red as the second passes. When it's all red, the player can shoot again.
There's one last class that we need to examine in order to fully understand the ShootingGallery
game (as we learned in Chapter 11, “Debugging with Eclipse,” fully understanding a program's code is a
key part of software development). The ShootingGalleryTargetSprites class loads the three different
target images and makes them available to the rest of the program. Listing 12-10 shows the
ShootingGalleryTargetSprites class.

Listing 12-10. The ShootingGalleryTargetSprites class

package com.bryantcs.examples.videogames;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ShootingGalleryTargetSprites {

// Variables for the images
// Static so that each one exists in memory only once
private static Image smallTarget = null;
private static Image mediumTarget = null;
private static Image largeTarget = null;

// Load the images into the variables
public void init() {
try {
smallTarget = ImageIO.read(new File("C:\\test\\sprites\\target_small.png"));
mediumTarget = ImageIO.read(new File("C:\\test\\sprites\\target_medium.png"));
largeTarget = ImageIO.read(new File("C:\\test\\sprites\\target_large.png"));
} catch (IOException e) {
Free download pdf