Tải bản đầy đủ (.pdf) (98 trang)

Black Art of Java Game Programming PHẦN 7 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.15 MB, 98 trang )

Black Art of Java Game Programming:Building the JAVAroids Game
// key bindings
static final int LEFTINDEX = 0;
static final int LEFT = 'q'; // rotate left
static final int RIGHTINDEX = 1;
static final int RIGHT = 'w'; // rotate right
static final int THRUSTINDEX = 2;
static final int THRUST = 'o'; // thrust
static final int FIREINDEX = 3;
static final int FIRE = 'p'; // fire
static final int SHIELDINDEX = 4;
static final int SHIELD = ' '; // shield
/////////////////////////////////////////////////////////////////
// update Ship and Fire sprites based on key buffer
/////////////////////////////////////////////////////////////////
public void update() {
// update fire sprites
for ( int i=0 ; i<MAX_SHOTS; i++) {
f[i].update();
}
// if ship's alive
if (shipAlive) {
// check the key buffer and perform the
// associated action
if (keyState[LEFTINDEX])
s.rotateLeft();
if (keyState[RIGHTINDEX])
s.rotateRight();
if (keyState[THRUSTINDEX])
s.thrust();
if (keyState[FIREINDEX])


handleFire();
if (keyState[SHIELDINDEX])
updateShield();
// update the Ship sprite
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/561-570.html (7 von 10) [13.03.2002 13:19:18]
Black Art of Java Game Programming:Building the JAVAroids Game
s.update();
}
// otherwise, the ship's not alive!
else {
// if the waiting period's over,
// initialize a new Ship sprite
if (!gameOver && (waitPeriod <= 0)) {
s.setAngle(270);
s.setPosition(width/2,height/2);
s.setVelocity(0,0);
s.rotate(0);
shieldStrength = 100;
shipAlive = true;
s.restore();
}
}
}
/////////////////////////////////////////////////////////////////
// initialize parameters for a new game
/////////////////////////////////////////////////////////////////
public void newGame() {
s.setAngle(270);
s.setPosition(width/2,height/2);
s.setVelocity(0,0);

s.rotate(0);
shieldStrength = 100;
shipAlive = true;
shipsLeft = 2;
gameOver = false;
s.restore();
}
/////////////////////////////////////////////////////////////////
// increase Shield strength (when the Ship touches a powerup
/////////////////////////////////////////////////////////////////
public void increaseShield() {
shieldStrength += 30;
if (shieldStrength > 250)
shieldStrength = 250;
}
/////////////////////////////////////////////////////////////////
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/561-570.html (8 von 10) [13.03.2002 13:19:18]
Black Art of Java Game Programming:Building the JAVAroids Game
// handle keyDown events by setting the appropriate
// field in the key buffer
/////////////////////////////////////////////////////////////////
public void keyDown(Event e,int k) {
switch(k) {
case LEFT:
keyState[LEFTINDEX] = true;
break;
case RIGHT:
keyState[RIGHTINDEX] = true;
break;
case FIRE:

keyState[FIREINDEX] = true;
break;
case THRUST:
keyState[THRUSTINDEX] = true;
break;
case SHIELD:
keyState[SHIELDINDEX] = true;
break;
default:
break;
}
}
/////////////////////////////////////////////////////////////////
// handle keyDown events by setting the appropriate
// field in the key buffer
/////////////////////////////////////////////////////////////////
public void keyUp(Event e,int k) {
switch(k) {
case LEFT:
keyState[LEFTINDEX] = false;
break;
case RIGHT:
keyState[RIGHTINDEX] = false;
break;
case FIRE:
keyState[FIREINDEX] = false;
break;
case THRUST:
keyState[THRUSTINDEX] = false;
break;

case SHIELD:
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/561-570.html (9 von 10) [13.03.2002 13:19:18]
Black Art of Java Game Programming:Building the JAVAroids Game
keyState[SHIELDINDEX] = false;
break;
default:
break;
}
}
/////////////////////////////////////////////////////////////////
// update Shield strength (when the player's activating Shield)
/////////////////////////////////////////////////////////////////
private void updateShield() {
if ( shieldStrength <= 0) {
shieldStrength = 0;
}
}
/////////////////////////////////////////////////////////////////
// start a new Fire sprite
/////////////////////////////////////////////////////////////////
private void handleFire() {
for (int i=0; i<MAX_SHOTS; i++) {
if (!f[i].isActive()) {
// start fire from ship's nose at angle theta
f[i].initialize(s.p.xpoints[0],s.p.ypoints[0],s.theta);
break;
}
}
}
}

Previous Table of Contents Next
file:///D|/Downloads/Books/Computer/Java/Bl Java%20Game%20Programming/ch13/561-570.html (10 von 10) [13.03.2002 13:19:18]
Black Art of Java Game Programming:Building the JAVAroids Game

Black Art of Java Game Programming
by Joel Fan
Sams, Macmillan Computer Publishing
ISBN: 1571690433 Pub Date: 11/01/96

Previous Table of Contents Next
The Enemy Manager
By now, you should be getting a better idea of how these managers are organized! The
EnemyManager class is responsible for the Enemy sprites and their Fire sprites, which it initializes in
its constructor. The update() method checks for collisions between the enemy objects and the ship
(and this code is really similar to the AstManager’s update()). In addition, update() starts new enemy
ships, using the method NewEnemy(), and initiates enemy firing at random intervals. Finally, the
paint() method cycles through all enemy ship sprites and enemy fire sprites, and tells each one to paint
itself.
Listing 13-16 shows the EnemyManager class.
Listing 13-16 EnemyManager class
/////////////////////////////////////////////////////////////////
//
// EnemyManager responsible for controlling the
// Enemy alien sprites, and Enemy Fire
//
/////////////////////////////////////////////////////////////////
public class EnemyManager extends Object {
// constants to define two sizes of enemy ships
static final int LARGE = 0;
static final int SMALL = 1;

static final int SRATX = 3; // x-ratio of large to small
static final int SRATY = 2; // y-ratio of large to small
// the enemy ship templates
// x-coordinate template
static final int tpx[][] = {
{14,11,8,-8,-11,-14,-6,6,14,-14},
{14/SRATX,11/SRATX,8/SRATX,-8/SRATX,-11/SRATX,-14/SRATX,
-6/SRATX,6/SRATX,14/SRATX,-14/SRATX} } ;
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (1 von 7) [13.03.2002 13:19:19]
Black Art of Java Game Programming:Building the JAVAroids Game
// y-coordinate template
static final int tpy[][] = {
{0,3,6,6,3,0,-4,-4,0,0},
{0/SRATY,3/SRATY,6/SRATY,6/SRATY,3/SRATY,0/SRATY,-4/SRATY,
-4/SRATY,0/SRATY,0/SRATY} } ;
// screen boundaries
static int width,height;
// constants parameters for enemy ships
static final int MAX_ENEMIES = 3;
static final int MAX_SHOTS_PER_ENEMY = 2;
static final int MAX_SHOTS = MAX_ENEMIES*MAX_SHOTS_PER_ENEMY;
// arrays for color, length, and value of various enemy ships
static final Color ENEMY_COLOR[] =
{Color.green,Color.red,Color.orange};
static final int ENEMY_LENGTH[] = {14,14,5};
static final int VALUE[] = {500,750,1000};
// maximum speed
static final int MAX_VX = 9, MAX_VY = 9;
// how often enemies appear, and how often they fire
static double enemy_freq = 0.995 ;

static double fire_freq = 0.995;
// array of Enemy sprites
private Enemy e[] = new Enemy[MAX_ENEMIES];
// array of Fire sprites
private Fire f[] = new Fire[MAX_SHOTS_PER_ENEMY*MAX_ENEMIES];
// references to other game objects
ShipManager sm;
EffManager efm;
Ship ship;
Fire[] shipfire;
GameManager game;
/////////////////////////////////////////////////////////////////
// EnemyManager constructor
/////////////////////////////////////////////////////////////////
public EnemyManager(int width,int height,
ShipManager sm,
EffManager efm,
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (2 von 7) [13.03.2002 13:19:19]
Black Art of Java Game Programming:Building the JAVAroids Game
GameManager g) {
ship = sm.getShip(); // get ship needed for
// collision detection
shipfire = sm.getFire(); // get ship's fire for
this.sm = sm; // collision detection
this.efm = efm;
game = g;
// initialize the three enemy sprites
e[0] = new Enemy(tpx[0],tpy[0],tpx[0].length, // template
0,0, // initial loc
ENEMY_COLOR[0], // color

width,height, // screen bounds
ENEMY_LENGTH[0],VALUE[0]); // length,value
e[1] = new Enemy(tpx[0],tpy[0],tpx[0].length,
0,0,ENEMY_COLOR[1],
width,height,
ENEMY_LENGTH[1],VALUE[1]);
e[2] = new Enemy(tpx[1],tpy[1],tpx[1].length,
0,0,
ENEMY_COLOR[2],
width,height,
ENEMY_LENGTH[2],VALUE[2]);
// suspend the three enemy sprites
for (int i=0; i<MAX_ENEMIES; i++) {
e[i].suspend();
}
// create and suspend the Fire sprites
for ( int i=0 ; i<MAX_SHOTS; i++) {
f[i] = new Fire(ENEMY_COLOR[i/MAX_SHOTS_PER_ENEMY],
width,height);
f[i].suspend();
}
// save screen bounds
this.width = width;
this.height = height;
}
/////////////////////////////////////////////////////////////////
// initialize for new game
/////////////////////////////////////////////////////////////////
public void newGame() {
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (3 von 7) [13.03.2002 13:19:19]

Black Art of Java Game Programming:Building the JAVAroids Game
for (int i=0; i<MAX_ENEMIES; i++) {
e[i].suspend();
}
for (int i=0 ; i<MAX_SHOTS; i++) {
f[i] = new Fire(ENEMY_COLOR[i/MAX_SHOTS_PER_ENEMY],
width,height);
f[i].suspend();
}
}
/////////////////////////////////////////////////////////////////
// update enemy ships and enemy fire
// CHECK FOR COLLISIONS WITH SHIP OR SHIP FIRE
/////////////////////////////////////////////////////////////////
public void update() {
// check if any of the fire sprites hit the Player's ship.
// If so, tell the ShipManager to destroy the ship
for ( int i=0 ; i<MAX_SHOTS; i++) {
f[i].update();
if (f[i].intersect(ship)) {
sm.destroyShip();
}
}
/////////////////////////////////////////////////////////////////
// cycle through all enemies
for ( int i=0 ; i<MAX_ENEMIES; i++) {
// place a new enemy on the screen at random intervals
if (!e[i].isActive()) {
if (Math.random() > enemy_freq) {
NewEnemy(i);

}
}
// else update and check for collisions
else {
e[i].update();
// if it intersects the ship
if (e[i].intersect(ship)) {
// increase score
game.updateScore(e[i].value);
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (4 von 7) [13.03.2002 13:19:19]
Black Art of Java Game Programming:Building the JAVAroids Game
// tell sm to destroy ship
sm.destroyShip();
// suspend enemy and create explosion
e[i].suspend();
efm.addEnemyExplosion(e[i].locx,e[i].locy);
}
// check if enemy intersect's ship's fire
for (int j=0; j<shipfire.length; j++) {
if (e[i].intersect(shipfire[j])) {
sm.stopFire(j); // stop fire sprite
e[i].suspend(); // stop enemy sprite
efm.addEnemyExplosion(e[i].locx,e[i].locy);
game.updateScore(e[i].value);
}
}
// create new enemy fire at random intervals
if (Math.random() > fire_freq) {
Fire(i);
}

}
}
}
/////////////////////////////////////////////////////////////////
// Accessor methods
/////////////////////////////////////////////////////////////////
public Enemy[] getEnemy() {
return e;
}
public Fire[] getFire() {
return f;
}
public void destroyEnemy(int i) {
e[i].suspend();
}
public void stopFire(int i) {
f[i].suspend();
}
/////////////////////////////////////////////////////////////////
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (5 von 7) [13.03.2002 13:19:19]
Black Art of Java Game Programming:Building the JAVAroids Game
// make new enemy at slot i of the Enemy array e
/////////////////////////////////////////////////////////////////
private void NewEnemy(int i) {
// set the enemy speed
e[i].setVelocity(GameMath.getRand(2*MAX_VX)-MAX_VX,
GameMath.getRand(2*MAX_VY)-MAX_VY);
// set the enemy position
int px = (Math.random() > 0.5) ? 0 : width;
int py = GameMath.getRand(height);

e[i].setPosition(px,py);
// restore the sprite
e[i].restore();
}
/////////////////////////////////////////////////////////////////
// initialize enemy fire for enemy ship i
/////////////////////////////////////////////////////////////////
private void Fire(int i) {
for (int j = i*MAX_SHOTS_PER_ENEMY;
j < (i+1)*MAX_SHOTS_PER_ENEMY;
j++) {
// if there's a slot in enemy fire array,
// initialize and restore the fire sprite
if (!f[j].isActive()) {
f[j].initialize(e[i].locx,e[i].locy,
GameMath.getRand(360)); // random angle
f[j].restore();
}
}
}
/////////////////////////////////////////////////////////////////
// paint the enemy ships and their fire
/////////////////////////////////////////////////////////////////
public void paint(Graphics g) {
for ( int i=0 ; i<MAX_ENEMIES; i++) {
e[i].paint(g);
}
for ( int i=0 ; i<MAX_SHOTS; i++) {
f[i].paint(g);
}

file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (6 von 7) [13.03.2002 13:19:19]
Black Art of Java Game Programming:Building the JAVAroids Game
}
}
Previous Table of Contents Next
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/570-575.html (7 von 7) [13.03.2002 13:19:19]
Black Art of Java Game Programming:Building the JAVAroids Game

Black Art of Java Game Programming
by Joel Fan
Sams, Macmillan Computer Publishing
ISBN: 1571690433 Pub Date: 11/01/96

Previous Table of Contents Next
The Effect Manager
For the effect manager, we’re going to depart from our policy of avoiding object instantiations during
game play. This is because the number of explosions is tricky to judge beforehand, so it’s easier to
keep a Vector of explosions, and insert new explosions when the other manager classes detect
collisions. Thus, EffManager provides the public methods addShipExplosion(),
addEnemyExplosion(), and addAstExplosion(), which the other managers can invoke. These methods
create new Explosion objects that are added to the explosions Vector.
Listing 13-17 contains the complete effect manager class.
Listing 13-17 EffManager class
/////////////////////////////////////////////////////////////////
//
// EffManager: handles effects, such as explosions and sound
//
/////////////////////////////////////////////////////////////////
public class EffManager extends Object {
Vector explosions;

AudioClip expsound;
/////////////////////////////////////////////////////////////////
// EffManager constructor
/////////////////////////////////////////////////////////////////
public EffManager(AudioClip expsound) {
explosions = new Vector();
this.expsound = expsound;
}
/////////////////////////////////////////////////////////////////
// make a ship explosion at x,y
/////////////////////////////////////////////////////////////////
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/575-577.html (1 von 3) [13.03.2002 13:19:20]
Black Art of Java Game Programming:Building the JAVAroids Game
public void addShipExplosion(int x,int y) {
Explosion exp = new Explosion(Color.red,x,y,20);
Explosion exp1 = new Explosion(Color.yellow,x+2,y+2,25);
explosions.addElement(exp);
explosions.addElement(exp1);
if (expsound != null) {
expsound.play();
}
}
/////////////////////////////////////////////////////////////////
// make an asteroid explosion at x,y
/////////////////////////////////////////////////////////////////
public void addAstExplosion(int x,int y) {
Explosion exp = new Explosion(Color.white,x,y,15);
explosions.addElement(exp);
if (expsound != null) {
expsound.play();

}
}
/////////////////////////////////////////////////////////////////
// make an asteroid explosion at x,y
/////////////////////////////////////////////////////////////////
public void addEnemyExplosion(int x,int y) {
Explosion exp = new Explosion(Color.orange,x,y,15);
explosions.addElement(exp);
if (expsound != null) {
expsound.play();
}
}
/////////////////////////////////////////////////////////////////
// make an explosion of the given color at x,y
/////////////////////////////////////////////////////////////////
public void addExplosion(Color c,int x, int y, int u) {
Explosion exp = new Explosion(c,x,y,u);
explosions.addElement(exp);
if (expsound != null) {
expsound.play();
}
}
/////////////////////////////////////////////////////////////////
// paint the explosions by stepping through the
// explosions Vector
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/575-577.html (2 von 3) [13.03.2002 13:19:20]
Black Art of Java Game Programming:Building the JAVAroids Game
/////////////////////////////////////////////////////////////////
public void paint (Graphics g) {
Enumeration e;

e = explosions.elements();
while (e.hasMoreElements()) {
Sprite exp = (Sprite) e.nextElement();
exp.paint(g);
}
}
/////////////////////////////////////////////////////////////////
// update the explosions by stepping through the
// explosions Vector
/////////////////////////////////////////////////////////////////
public void update() {
Enumeration e;
e = explosions.elements();
while (e.hasMoreElements()) {
Explosion exp = (Explosion) e.nextElement();
exp.update();
// if the explosion's finished, remove it from vector
if (exp.isDone()) {
explosions.removeElement(exp);
}
}
}
}
Previous Table of Contents Next
file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch13/575-577.html (3 von 3) [13.03.2002 13:19:20]
Black Art of Java Game Programming:Building the JAVAroids Game

Black Art of Java Game Programming
by Joel Fan
Sams, Macmillan Computer Publishing

ISBN: 1571690433 Pub Date: 11/01/96

Previous Table of Contents Next
The Game Manager
The GameManager class contains the top-level structure of JAVAroids. The game opens with an
introductory screen, which lists the point values of the objects in the game. After this, the player can
test drive his ship, and learn the controls. Then, the player can start the game. The transition between
these screens is triggered by a mouseUp event.
GameManager implements the Runnable interface by defining a method called run(). The heart of the
run() method is the Video Game Loop, which we covered back in Chapter 5, Building a Video Game.
This loop coordinates the sequence of actions that take place in Figure 13-17. GameManager also
defines handlers for key events, which it passes along to the ShipManager.
Finally, the GameManager source is presented in Listing 13-18. JAVAroids is finished!
Listing 13-18 GameManager class
/////////////////////////////////////////////////////////////////
//
// GameManager:
// responsible for tracking status of game and keeping score
//
/////////////////////////////////////////////////////////////////
public class GameManager extends Applet implements Runnable {
// variables for double buffering and animation
Thread animation;
Graphics gbuf;
Image im;
static final int REFRESH_RATE = 72; // in ms
// size of the game applet: change as needed
static final int MAX_HEIGHT = 400;
static final int MAX_WIDTH = 400;
// game parameters

file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (1 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
private int score; // score
private boolean playing; // playing or not
private boolean gameOver; // is game over
private int intro_screen; // which screen
static final int EXTRA_SHIP = 10000; // #pts for extra ship
private int current_extra = 0; // counts extras
// constants for the introduction part of the game
static final int INSTRUCTIONS = 1;
static final int TEST_DRIVE = 2;
static final int INTRO_OVER = 3;
// references to manager classes
AstManager am; // asteroids
ShipManager sm; // ship
EnemyManager em; // enemy ships
EffManager efm; // effects
// sound
URL codebase;
AudioClip expsound = null;
// variables to monitor performance during game
Date time;
long t1,t2,dt;
// fonts
static Font bigfont = new Font("TimesRoman", Font.BOLD,24);
static Font medfont = new Font("TimesRoman", Font.PLAIN,18);
static Font smallfont = new Font("TimesRoman", Font.PLAIN,12);
/////////////////////////////////////////////////////////////////
// initialize applet
/////////////////////////////////////////////////////////////////

public void init() {
// initialize screen
setBackground(Color.black);
setFont(smallfont);
// initialize double buffer
im = createImage(MAX_WIDTH,MAX_HEIGHT);
gbuf = im.getGraphics();
// initialize sound
codebase = getCodeBase();
// System.out.println(codebase.toString());
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (2 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
resize(MAX_WIDTH,MAX_HEIGHT);
// initialize game state
gameOver = true;
intro_screen = 1;
playing = false;
}
/////////////////////////////////////////////////////////////////
// start applet
/////////////////////////////////////////////////////////////////
public void start() {
// load sound
try {
expsound = getAudioClip(getCodeBase(),"Explosion.au");
}
catch (Exception exc) {
System.out.println("Sound not loaded");
};
// initialize manager classes

efm = new EffManager(expsound);
sm = new ShipManager(MAX_WIDTH,MAX_HEIGHT,efm,this);
em = new EnemyManager(MAX_WIDTH,MAX_HEIGHT,sm,efm,this);
am = new AstManager(MAX_WIDTH,MAX_HEIGHT,sm,em,efm,this);
// start animation
if (animation == null) {
animation = new Thread(this);
if (animation != null) {
animation.start();
}
else
System.out.println("Insufficient memory to fork thread!");
}
}
/////////////////////////////////////////////////////////////////
// stop applet
/////////////////////////////////////////////////////////////////
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (3 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
public void stop() {
if (animation != null) {
animation.stop();
animation = null;
}
}
/////////////////////////////////////////////////////////////////
// set gameOver flag
/////////////////////////////////////////////////////////////////
public void setGameOver() {
gameOver = true;

}
/////////////////////////////////////////////////////////////////
// start a new game
/////////////////////////////////////////////////////////////////
private void newGame() {
// tell managers to start a new game
em.newGame();
am.newGame();
sm.newGame();
// set font for game
gbuf.setFont(smallfont);
// initialize parameters
current_extra = 0;
score = 0;
gameOver = false;
playing = true;
}
/////////////////////////////////////////////////////////////////
//
// Event Handlers
//
/////////////////////////////////////////////////////////////////
// if mouseUp occurs, proceed to next screen of introduction.
// if game's being played, restart the game.
public boolean mouseUp(Event e,int x,int y) {
if (intro_screen == INSTRUCTIONS) {
intro_screen = TEST_DRIVE;
sm.getShip().setPosition(385,75);
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (4 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game

sm.getShip().restore();
}
// else restart the game
else if (intro_screen == TEST_DRIVE) {
intro_screen = INTRO_OVER;
newGame();
}
else
newGame();
return true;
}
// pass key events to the ShipManager
public boolean keyDown(Event e, int k) {
sm.keyDown(e,k);
return true;
}
// pass key events to the ShipManager
public boolean keyUp(Event e, int k) {
sm.keyUp(e,k);
return true;
}
/////////////////////////////////////////////////////////////////
// the game driver
/////////////////////////////////////////////////////////////////
public void run() {
startInstructions();
// the Video Game Loop
while (true) {
if (playing) {
time = new Date(); // track time

t1 = time.getTime();
if (!gameOver) {
sm.update(); // update ship
}
em.update(); // update enemies
am.update(); // update asteroids
efm.update(); // update effects
repaint();
Thread.currentThread().yield();
time = new Date(); // track time
t2 = time.getTime();
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (5 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
dt = t2-t1; // how long did it take?
// sleep
try {
Thread.sleep (REFRESH_RATE-(int)dt < 0
? 8
: REFRESH_RATE-(int)dt);
} catch (Exception exc) { };
}
// else not playing
else {
updateOpening(); // update opening
repaint();
Thread.currentThread().yield();
try {
Thread.sleep (REFRESH_RATE);// sleep
} catch (Exception exc) { };
}

}
}
/////////////////////////////////////////////////////////////////
// initialize the AstManager and EnemyManager for the
// INSTRUCTIONS screen.
/////////////////////////////////////////////////////////////////
private void startInstructions() {
Asteroid a[] = am.getAsts();
Asteroid p = am.getPowerup();
// set asteroids in instruction screen
a[0].setPosition(270,98);
a[0].setRotationRate(4);
a[0].setVelocity(1,2);
a[0].restore();
a[am.NUM_LARGE].setPosition(330,138);
a[am.NUM_LARGE].setRotationRate(-4);
a[am.NUM_LARGE].setVelocity(-1,-1);
a[am.NUM_LARGE].restore();
a[am.NUM_LARGE+am.NUM_MEDIUM].setPosition(370,178);
a[am.NUM_LARGE+am.NUM_MEDIUM].setRotationRate(5);
a[am.NUM_LARGE+am.NUM_MEDIUM].setVelocity(2,-1);
a[am.NUM_LARGE+am.NUM_MEDIUM].restore();
// set powerup in intro screen
p.setPosition(330,340);
p.restore();
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (6 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
// set enemies for intro screen
Enemy e[] = em.getEnemy();
e[0].setPosition(10,214);

e[0].setVelocity(2,0);
e[0].restore();
e[1].setPosition(390,254);
e[1].setVelocity(-3,0);
e[1].restore();
e[2].setPosition(7,294);
e[2].setVelocity(4,0);
e[2].restore();
}
/////////////////////////////////////////////////////////////////
// update the opening screens
/////////////////////////////////////////////////////////////////
private void updateOpening() {
if (intro_screen == INSTRUCTIONS) {
am.update();
Enemy e[] = em.getEnemy();
e[0].update();
e[1].update();
e[2].update();
efm.update();
}
else if (intro_screen == TEST_DRIVE) {
sm.update();
}
}
/////////////////////////////////////////////////////////////////
// update the score. If the score passes threshold
// (every EXTRA_SHIP points) give an extra ship!
/////////////////////////////////////////////////////////////////
public void updateScore(int val) {

score += val;
if ((score / EXTRA_SHIP) > current_extra) {
sm.extraShip(); // give extra ship
current_extra = score/EXTRA_SHIP;
}
}
/////////////////////////////////////////////////////////////////
// override update() to eliminate flicker
/////////////////////////////////////////////////////////////////
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (7 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
public void update(Graphics g) {
paint(g); // don't clear screen
}
/////////////////////////////////////////////////////////////////
// return a string of n that is 0-padded with the given length
/////////////////////////////////////////////////////////////////
public String PadNumber(int n,int len) {
StringBuffer s;
s = new StringBuffer(Integer.toString(n));
while (s.length () < len) {
s.insert(0,"0");
}
return s.toString();
}
/////////////////////////////////////////////////////////////////
// define Strings used in the Opening screens
/////////////////////////////////////////////////////////////////
// Strings used in INSTRUCTIONS screen
String javaroidsString = new String("JAVAroids!");

String galleryString = new String("The Lineup ");
String largeAstString =
new String("30 points for Big Asteroid");
String mediumAstString =
new String("60 points for Medium Asteroid");
String smallAstString =
new String("90 points for Small Asteroid");
String greenAlienString =
new String("500 points for Green Alien");
String redAlienString =
new String("750 points for Red Alien");
String orangeAlienString =
new String("1000 points for Orange Alien");
String clickMouseString1 =
new String("Click mouse to continue ");
String powerupString1 =
new String("Touch PowerUp for");
String powerupString2 =
new String("extra shield strength:");
// Strings used in the TEST_DRIVE screen
String shipControlString =
new String("Test Drive your ship NOW > ");
String rotLeftString = new String("Press 'q' to Rotate Left");
String rotRightString =
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (8 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
new String("Press 'w' to Rotate Right");
String thrustString = new String("Press 'o' to Thrust");
String fireString = new String("Press 'p' to Fire");
String shieldString =

new String("Press <space bar> for Shield");
String extraShipString =
new String("Extra Ship every 10,000 points");
String goodLuckString =
new String("GOOD LUCK!");
String clickMouseString =
new String("Click mouse to begin!");
String byMeString = new String("by Joel Fan");
String gameOverString = new String("GAME OVER");
String clickMouseString2 =
new String("Click mouse to play again!");
/////////////////////////////////////////////////////////////////
// paint to the screen, depending on mode of game
/////////////////////////////////////////////////////////////////
public void paint(Graphics g) {
// clear offscreen buffer
gbuf.setColor(Color.black);
gbuf.fillRect(0,0,MAX_WIDTH,MAX_HEIGHT);
if (playing) {
// if game's not over, show the ship.
if (!gameOver) {
sm.paint(gbuf);
}
// otherwise, display the Game Over message
else {
gbuf.setFont(bigfont);
gbuf.setColor(Color.cyan);
gbuf.drawString(byMeString,
MAX_WIDTH/2 - 55, MAX_HEIGHT/2-60);
gbuf.setColor(Color.magenta);

gbuf.drawString(gameOverString,
MAX_WIDTH/2 - 65, MAX_HEIGHT/2);
gbuf.drawString(clickMouseString2,
MAX_WIDTH/2 - 120, MAX_HEIGHT/2+35);
gbuf.setFont(smallfont);
file:///D|/Downloads/Books/Computer/Java/Bla 0Java%20Game%20Programming/ch13/578-588.html (9 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
}
// tell other manager classes to paint themselves
em.paint(gbuf); // paint enemies
am.paint(gbuf); // paint asteroids
efm.paint(gbuf); // paint effects
// draw the score
gbuf.drawString(PadNumber(score,6),20,20);
// draw offscreen image to screen
g.drawImage(im,0,0,this);
}
else if (intro_screen == INSTRUCTIONS) {
paintInstructions(g);
}
else if (intro_screen == TEST_DRIVE) {
paintTestDrive(g);
}
}
/////////////////////////////////////////////////////////////////
// paint Instructions screen
// coordinates are hardcoded for simplicity
/////////////////////////////////////////////////////////////////
public void paintInstructions(Graphics g) {
gbuf.setFont(bigfont);

// set a random color
gbuf.setColor(new Color(GameMath.getRand(155)+100,
GameMath.getRand(155)+100,
GameMath.getRand(155)+100));
gbuf.drawString(javaroidsString,MAX_WIDTH/2 - 60, 30);
gbuf.setColor(Color.yellow);
gbuf.setFont(medfont);
gbuf.setColor(Color.magenta);
gbuf.setFont(bigfont);
gbuf.drawString(largeAstString,25,80);
gbuf.drawString(mediumAstString,25,120);
gbuf.drawString(smallAstString,25,160);
gbuf.setColor(Color.green);
gbuf.drawString(greenAlienString,25,200);
gbuf.setColor(Color.red);
gbuf.drawString(redAlienString,25,240);
file:///D|/Downloads/Books/Computer/Java/Bl Java%20Game%20Programming/ch13/578-588.html (10 von 12) [13.03.2002 13:19:21]
Black Art of Java Game Programming:Building the JAVAroids Game
gbuf.setColor(Color.orange);
gbuf.drawString(orangeAlienString,25,280);
gbuf.setColor(Color.green);
gbuf.drawString(powerupString1,25,320);
gbuf.drawString(powerupString2,50,350);
gbuf.setColor(Color.yellow);
gbuf.drawString(clickMouseString1,MAX_WIDTH/2-120,385);
am.paint(gbuf);
Enemy e[] = em.getEnemy();
e[0].paint(gbuf);
e[1].paint(gbuf);
e[2].paint(gbuf);

efm.paint(gbuf);
// dump offscreen buffer to screen
g.drawImage(im,0,0,this);
}
/////////////////////////////////////////////////////////////////
// paint the test drive screen
// coordinates are hardcoded for simplicity
/////////////////////////////////////////////////////////////////
public void paintTestDrive(Graphics g) {
gbuf.setFont(smallfont);
sm.paint(gbuf); // paint the ship
gbuf.setFont(bigfont);
gbuf.setColor(new Color(GameMath.getRand(155)+100,
GameMath.getRand(155)+100,
GameMath.getRand(155)+100));
gbuf.drawString(javaroidsString,MAX_WIDTH/2 - 60, 50);
gbuf.setColor(Color.magenta);
gbuf.drawString(shipControlString,25,80);
gbuf.setColor(Color.orange);
gbuf.drawString(rotLeftString,25,130);
gbuf.drawString(rotRightString,25,170);
gbuf.drawString(thrustString,25,210);
gbuf.drawString(fireString,25,250);
gbuf.drawString(shieldString,25,290);
gbuf.setColor(Color.cyan);
gbuf.drawString(extraShipString,25,340);
gbuf.setColor(Color.green);
gbuf.drawString(clickMouseString,MAX_WIDTH/2-120,385);
g.drawImage(im,0,0,this);
}

file:///D|/Downloads/Books/Computer/Java/Bl Java%20Game%20Programming/ch13/578-588.html (11 von 12) [13.03.2002 13:19:21]

×