Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 12 ■ VIDEO GAMES

further? Does further separation make the code easier to understand or maintain? In this case, the code
could have been separated further. However, further separation would just clutter this simple program.


Listing 12-3. The Target class


package com.bryantcs.examples.videogames;


import java.awt.Color;
import java.awt.Graphics;


import javax.swing.JPanel;


public class Target {
// The essential information drawing a target:
// where is it and how big is it right now?
private int drawX, drawY, step;


// Are we done yet? By default, no
private boolean done = false;


// a reference to the game area, which we use
// to find a spot for this target
JPanel panel;


// The constructor
Target(JPanel panel) {
this.panel = panel;
// -30 + 15 creates a 15-pixel border


// Find a random spot in the game field
drawX = TargetClick.random.nextInt(panel.getWidth() - 30) + 15;
drawY = TargetClick.random.nextInt(panel.getHeight() - 30) + 15;


// Start the step counter
step = 0;
}


// Here's where we draw the target
void draw(Graphics g) {
if (!done) {
// if not done, draw a circle that varies in size by the current step
if (step == 0) {
g.setColor(Color.RED);
g.fillOval(drawX - 15, drawY - 15, 10, 10);
}
if (step == 1) {
g.setColor(Color.RED);
g.fillOval(drawX - 15, drawY - 15, 20, 20);
}

Free download pdf