games programming with java

72
240-492 Java Games: exAliens/9 Games Programming with Java Games Programming with Java Objectives Objectives extend the basic Aliens game extend the basic Aliens game a background, explosion effects, scoring, a GUI a background, explosion effects, scoring, a GUI interface, start and end dialog boxes interface, start and end dialog boxes 240-492, Special Topics in Comp. Eng. II Semester 1, 2002-2003 9. Extended Alien A ttack v.2 Attack of the Clones?

Upload: adonia

Post on 14-Jan-2016

35 views

Category:

Documents


0 download

DESCRIPTION

Games Programming with Java. 240-492, Special Topics in Comp. Eng. II Semester 1, 2002-2003. Objectives extend the basic Aliens game a background, explosion effects, scoring, a GUI interface, start and end dialog boxes. 9. Extended Alien Attack v.2 Attack of the Clones?. Overview. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Games Programming with Java

240-492 Java Games: exAliens/9 1

Games Programming with JavaGames Programming with Java

ObjectivesObjectives– extend the basic Aliens gameextend the basic Aliens game

a background, explosion effects, scoring, a GUI interface, start and a background, explosion effects, scoring, a GUI interface, start and end dialog boxesend dialog boxes

240-492, Special Topics in Comp. Eng. II Semester 1, 2002-2003

9. Extended Alien Attack v.2Attack of the Clones?

Page 2: Games Programming with Java

240-492 Java Games: exAliens/9 2

OverviewOverview

1. 1. Extended Alien AttackExtended Alien Attack2.2. GameManager ExtensionsGameManager Extensions3.3. GunManager ExtensionsGunManager Extensions4.4. UFOManager ExtensionsUFOManager Extensions5.5. GunSpriteGunSprite6.6. MissileSpriteMissileSprite7.7. UFOSpriteUFOSprite8.8. Extensions to ImagesSpriteExtensions to ImagesSprite

Page 3: Games Programming with Java

240-492 Java Games: exAliens/9 3

1. Extended Alien Attack1. Extended Alien Attack

Your mission:Your mission:

Thisdialog boxappears when thegame isstarted.

Page 4: Games Programming with Java

240-492 Java Games: exAliens/9 4

1.1.Playing 1.1.Playing

the Game the Game

$ java GameManager

Page 5: Games Programming with Java

240-492 Java Games: exAliens/9 5

It’s all over:energy is gone,and a poor score :(

Page 6: Games Programming with Java

240-492 Java Games: exAliens/9 6

1.2. Game Restrictions1.2. Game Restrictions Most of the restriction are as beforeMost of the restriction are as before

– but notice the changes to the key controlsbut notice the changes to the key controls

The GUI reports the user’s current score, numbThe GUI reports the user’s current score, numbers of UFOs destroyed, and general messages.ers of UFOs destroyed, and general messages.

When the player’s energy level reaches 0, the gWhen the player’s energy level reaches 0, the game terminates, and the score is judged.ame terminates, and the score is judged.

Page 7: Games Programming with Java

240-492 Java Games: exAliens/9 7

1.3. Control Hierarchy1.3. Control Hierarchy

Game Manager

Gun Manager UFO Manager

Gun Sprite Missile Sprite UFO Sprites

creation andinitialisation

updates

redraws

method calls

the manager receives sprite status infofor reporting

Page 8: Games Programming with Java

240-492 Java Games: exAliens/9 8

1.4. Sprite Interactions1.4. Sprite Interactions

GunSprite MissileSpriteUFOSpriteUFOSpriteUFOSpriteUFOSprite

moves fromGunManager

get gun barrel position;tell gun that it hasbeen hit by a UFO

launch fromGunManager

check if missile intersectsa UFO; announce hit

GameManager

reporthit

send msgs;report death;report landing

Page 9: Games Programming with Java

240-492 Java Games: exAliens/9 9

1.5. Game Background1.5. Game Background

Many of the extensions are from:Many of the extensions are from:– ""Black Art of Java Game ProgrammingBlack Art of Java Game Programming””

Joel Fan et al., The Waite Group, 1996Joel Fan et al., The Waite Group, 1996Chapter Chapter 66

– I have recoded them to use my sprite classes, anI have recoded them to use my sprite classes, and modern Java codingd modern Java coding

Page 10: Games Programming with Java

240-492 Java Games: exAliens/9 10

2. GameManager Extensions2. GameManager Extensions

Pass GameManager references to the Gun anPass GameManager references to the Gun and UFO managers.d UFO managers.

New scoring methods and variables.New scoring methods and variables. New GUI controls to display the game stats/sNew GUI controls to display the game stats/s

corecore– textfields, progress bartextfields, progress bar

New gun movement keysNew gun movement keys– to avoid arrow keys problemsto avoid arrow keys problems

continued

Page 11: Games Programming with Java

240-492 Java Games: exAliens/9 11

An unscaled skyline imageAn unscaled skyline image– requires transparent sprite imagesrequires transparent sprite images– scaling slows redrawingscaling slows redrawing

Loading of an explosion AudioClip.Loading of an explosion AudioClip.

Start and end dialog boxesStart and end dialog boxes– see earlier slidessee earlier slides

Page 12: Games Programming with Java

240-492 Java Games: exAliens/9 12

2.1. GameManager UML2.1. GameManager UML

Page 13: Games Programming with Java

240-492 Java Games: exAliens/9 13

2.2. GameManager.java2.2. GameManager.java (Extended) (Extended)import java.applet.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.net.*;import java.io.File;

public class GameManager extends JFrame { GameManagerPanel gmp; int totalScore, numKilled, numLanded, numGunHits; static final int MAX_ENERGY = 10; int energyLevel; JTextField jtfScore, jtfKilled, jtfMessage; JProgressBar jpEnergy; AudioClip explosionSound;

:

scoring GUIelements andvariables

Page 14: Games Programming with Java

240-492 Java Games: exAliens/9 14

public GameManager() { super( "Alien Attack!!" ); Container c = getContentPane(); c.setLayout( new BorderLayout() ); totalScore = 0; numKilled = 0; numLanded = 0; numGunHits = 0; energyLevel = MAX_ENERGY; try { explosionSound = Applet.newAudioClip(

new File("Explosion.au").toURL() ); } catch(MalformedURLException e) { System.out.println(

"Sound file Explosion.au not found");} gmp = new GameManagerPanel(this);

c.add( gmp, "Center"); JPanel p = gameStatsPanel(); c.add( p, "South");

:

initialise varsand load sound

Page 15: Games Programming with Java

240-492 Java Games: exAliens/9 15

addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_NUMPAD4) gmp.moveLeft(); else if (keyCode == KeyEvent.VK_NUMPAD6) gmp.moveRight(); else if (keyCode == KeyEvent.VK_NUMPAD8) gmp.fireMissile(); } });

: use the number pad for gun control

Page 16: Games Programming with Java

240-492 Java Games: exAliens/9 16

addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) { gameOver(); } } );

pack(); setResizable(false); show(); this.requestFocus(); // or key focus diappears } // end of GameManager()

Page 17: Games Programming with Java

240-492 Java Games: exAliens/9 17

private JPanel gameStatsPanel() { // build first row of status info

JLabel jlScore = new JLabel("Score: "); jtfScore = new JTextField(5); jtfScore.setEditable(false);

JLabel jlKilled = new JLabel("UFOs killed: "); jtfKilled = new JTextField(5); jtfKilled.setEditable(false);

JLabel jlEnergy = new JLabel("Energy: "); jpEnergy = new JProgressBar(0, MAX_ENERGY); jpEnergy.setValue(MAX_ENERGY); jpEnergy.setStringPainted(true);

:

place game infoat bottom ofJFrame

Page 18: Games Programming with Java

240-492 Java Games: exAliens/9 18

JPanel p1 = new JPanel( new FlowLayout() ); p1.add(jlScore); p1.add(jtfScore); p1.add(jlKilled); p1.add(jtfKilled); p1.add(jlEnergy); p1.add(jpEnergy);

// build second row of status info

JLabel jlName = new JLabel("Your Name: "); jtfName = new JTextField(20);

:

Page 19: Games Programming with Java

240-492 Java Games: exAliens/9 19

JLabel jlMesg = new JLabel("Game Messages: "); jtfMessage = new JTextField(20); jtfMessage.setEditable(false);

JPanel p2 = new JPanel( new FlowLayout() ); p2.add(jlMesg); p2.add(jtfMessage);

// put the rows together JPanel p = new JPanel(); p.setLayout(

new BoxLayout(p, BoxLayout.Y_AXIS)); p.add(p1); p.add(p2);

return p; } // end of gameStatsPanel()

replaces stdout used in 1st version

Page 20: Games Programming with Java

240-492 Java Games: exAliens/9 20

public void setMessage(String mesg) { jtfMessage.setText(mesg); }

// called by sprites to update score info public void ufoKilled() { numKilled++; jtfKilled.setText(""+numKilled); calcScore(); }

public void ufoLanded() { numLanded++; calcScore(); energyLevel -= 1; // arbitrary reduction jpEnergy.setValue(energyLevel); }

Page 21: Games Programming with Java

240-492 Java Games: exAliens/9 21

public void gunHitByUFO() { numGunHits++; calcScore(); energyLevel -= 2; // arbitrary reduction jpEnergy.setValue(energyLevel); }

private void calcScore() { totalScore = 4*numKilled - 2*numLanded

- 2*numGunHits; // arbitrary jtfScore.setText(""+totalScore); }

public int getEnergyLevel() { return energyLevel; }

Page 22: Games Programming with Java

240-492 Java Games: exAliens/9 22

public void playExplosion() { explosionSound.play(); }

public void gameOver() { gmp.stopTimer(); // stops game updates String judgement; if (totalScore <= 0) judgement = "\nWere you asleep?"; else if (totalScore <=10) judgement =

"\nMy pet goldfish could do better!"; else judgement = "\nNot too bad"; JOptionPane.showMessageDialog(this,

"Your Score: " + totalScore + judgement, "Game Over", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }

Page 23: Games Programming with Java

240-492 Java Games: exAliens/9 23

public static void main( String args[] ) { new GameManager(); }

} // end of GameManager class

Page 24: Games Programming with Java

240-492 Java Games: exAliens/9 24

class GameManagerPanel extends JPanel implements ActionListener

{ static final int PWIDTH = 500; static final int PHEIGHT = 500;

private GameManager gameMan; private GunManager gm; private UFOManager um;

private Image bgImage; // background image private Timer animatorTimer; private boolean atGameStart;

// true at the game start:

Page 25: Games Programming with Java

240-492 Java Games: exAliens/9 25

public GameManagerPanel(GameManager gameMan) { setBackground(Color.black); setPreferredSize(

new Dimension(PWIDTH, PHEIGHT));

bgImage = new ImageIcon("image/skyline.jpg").getImage();

gm = new GunManager(PWIDTH, PHEIGHT, gameMan); um = new UFOManager( gm.getGun(),

PWIDTH, PHEIGHT, gameMan); gm.makeMissile( um.getUFOs() ); this.gameMan = gameMan;

atGameStart = true;:

for sprite commsback to manager

Page 26: Games Programming with Java

240-492 Java Games: exAliens/9 26

// create the timer

animatorTimer = new Timer(50, this); //50ms animatorTimer.setInitialDelay(0); animatorTimer.setCoalesce(true);

animatorTimer.start(); } // end of GameManagerPanel()

Page 27: Games Programming with Java

240-492 Java Games: exAliens/9 27

public void stopTimer() { animatorTimer.stop(); }

public void moveLeft() { gm.moveGunLeft(); }

public void moveRight() { gm.moveGunRight(); }

public void fireMissile() { gm.fireMissile(); }

Page 28: Games Programming with Java

240-492 Java Games: exAliens/9 28

public void actionPerformed(ActionEvent e) // timer triggers execution of this method { if (atGameStart) { JOptionPane.showMessageDialog(gameMan,

"The year is 2217, your mission is to\n" + "defend Earth from Alien Attack\n" + "Use the number pad keys '4' and '6'\n" + "to move your gun left and right,\n" + "and '8' to fire a missile.\n\n" + "When your energy drops to 0, it's goodbye.",

"Alien Attack",JOptionPane.INFORMATION_MESSAGE);

atGameStart = false; }

:

this dialog only appearsat game start

Page 29: Games Programming with Java

240-492 Java Games: exAliens/9 29

if (gameMan.getEnergyLevel() <= 0) // game over

gameMan.gameOver(); else { // continue game gm.updateSprites(); um.updateSprites(); repaint(); } } // end of actionPerformed()

Page 30: Games Programming with Java

240-492 Java Games: exAliens/9 30

public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(bgImage, 0, 0, null);

// no image scaling required gm.drawSprites(g); um.drawSprites(g); }

} // end of GameManagerPanel class

the redraw order isimportant: backgroundfiirst, then sprites

Page 31: Games Programming with Java

240-492 Java Games: exAliens/9 31

3. GunManager Extensions3. GunManager Extensions

The GunManager passes a GameManager rThe GunManager passes a GameManager reference down to the gun sprite.eference down to the gun sprite.

The gun sprite can then send information to The gun sprite can then send information to the GameManager about being hit.the GameManager about being hit.

Page 32: Games Programming with Java

240-492 Java Games: exAliens/9 32

3.1. GunManager UML3.1. GunManager UML

Page 33: Games Programming with Java

240-492 Java Games: exAliens/9 33

3.2. GunManager.java3.2. GunManager.java (Extended) (Extended)

import javax.swing.*;import java.awt.*;import java.util.*;

public class GunManager { private GunSprite gun; private MissileSprite missile; private int pWidth, pHeight; static final int GUN_MOVE = 10;

public GunManager(int w, int h, GameManager gm) { gun = new GunSprite(w, h, gm); pWidth = w; pHeight = h; }

the onlychanges

Page 34: Games Programming with Java

240-492 Java Games: exAliens/9 34

public void makeMissile(ArrayList targets) { missile = new MissileSprite(

targets, pWidth, pHeight); }

public void moveGunLeft() { gun.move(-GUN_MOVE); }

public void moveGunRight() { gun.move(GUN_MOVE); }

public void fireMissile() { missile.launch( gun.getGunX() ); }

Page 35: Games Programming with Java

240-492 Java Games: exAliens/9 35

public GunSprite getGun() { return gun; }

public void updateSprites() { gun.updateSprite(); missile.updateSprite(); }

public void drawSprites(Graphics g) { gun.drawSprite(g); missile.drawSprite(g); }

} // end of GunManager class

Page 36: Games Programming with Java

240-492 Java Games: exAliens/9 36

4. UFOManager Extensions4. UFOManager Extensions

The UFOManager passes a GameManager rThe UFOManager passes a GameManager reference down to each UFO sprite.eference down to each UFO sprite.

A UFO sprite can then send information to tA UFO sprite can then send information to the GameManager.he GameManager.

Page 37: Games Programming with Java

240-492 Java Games: exAliens/9 37

4.1. UFOManager UML4.1. UFOManager UML

Page 38: Games Programming with Java

240-492 Java Games: exAliens/9 38

4.2. UFOManager.java4.2. UFOManager.java (Extended) (Extended)

import javax.swing.*;import java.awt.*;import java.util.*;

public class UFOManager { private ArrayList ufos; static final int NUM_UFOS = 7;

// the game has 7 ufos

private JPanel parent; private int pWidth, pHeight;

:

Page 39: Games Programming with Java

240-492 Java Games: exAliens/9 39

public UFOManager(GunSprite gun, int w, int h, GameManager gm)

{ int xPosn, yPosn; pWidth = w; pHeight = h;

ufos = new ArrayList(); for (int i=0; i < NUM_UFOS; i++) { xPosn = getRand( pWidth ); yPosn = getRand( pHeight/3 ); ufos.add( new UFOSprite(xPosn, yPosn,

pWidth, pHeight, gun, gm) ); } } // end of UFOManager()

the onlychanges

Page 40: Games Programming with Java

240-492 Java Games: exAliens/9 40

public ArrayList getUFOs() { return ufos; }

public void updateSprites() { UFOSprite ufo; for (int i=0; i < ufos.size(); i++) { ufo = (UFOSprite) ufos.get(i); if ( ufo.isActive())

ufo.updateSprite(); else { // reuse ufo in a new position

initPosition(ufo); ufo.setActive(true);

} } } // end of updateSprites()

Page 41: Games Programming with Java

240-492 Java Games: exAliens/9 41

private void initPosition(UFOSprite ufo) { int xPosn = getRand( pWidth ); int yPosn = getRand( pHeight/3 ); ufo.setPosition(xPosn, yPosn); }

public void drawSprites(Graphics g) { UFOSprite ufo; for (int i=0; i < ufos.size(); i++) { ufo = (UFOSprite) ufos.get(i); ufo.drawSprite(g); } }

// random number generator between 0-x private int getRand(int x) { return (int)(x * Math.random()); }

} // end of UFOManager class

Page 42: Games Programming with Java

240-492 Java Games: exAliens/9 42

5. GunSprite5. GunSprite

GunSpriteUFOSpriteUFOSpriteUFOSpriteUFOSprite

moves fromGunManager

get gun barrel position;tell gun that it hasbeen hit by a UFO

GameManager

reporthit

Page 43: Games Programming with Java

240-492 Java Games: exAliens/9 43

5.1. GunSprite Extensions5.1. GunSprite Extensions

GunSprite has a revised hit() method whGunSprite has a revised hit() method which sends information to GameManager.ich sends information to GameManager.

Page 44: Games Programming with Java

240-492 Java Games: exAliens/9 44

5.2. GunSprite UML5.2. GunSprite UML

Page 45: Games Programming with Java

240-492 Java Games: exAliens/9 45

5.3. GunSprite.java (Extended)5.3. GunSprite.java (Extended)import java.awt.*;import javax.swing.*;import AndySprite.ImagesSprite;

public class GunSprite extends ImagesSprite{ private GameManager gm;

GunSprite(int w, int h, GameManager gm) { super(w, h); this.gm = gm; setStep(0,0); // no movement loadImage("image", "gun"); setPosition( getPWidth()/2 - getWidth()/2,

getPHeight() - getHeight()); setActive(true); }

Page 46: Games Programming with Java

240-492 Java Games: exAliens/9 46

public void move(int xDist) { int newBPosn = locx + xDist + getWidth()/2;

// position of gun barrel

if (newBPosn < 0) // barrel off lhs locx = -getWidth()/2; else if (newBPosn > getPWidth())

// barrel off screen on rhs locx = getPWidth() - getWidth()/2; else // within screen locx += xDist;

setPosition(locx, locy); }

public int getGunX() // return central barrel x-coord position { return locx + getWidth()/2; }

Page 47: Games Programming with Java

240-492 Java Games: exAliens/9 47

public int getGunY() // return gun y-coord position { return locy; }

public void hit() // gun is hit by a ufo { gm.setMessage("Gun is hit by a UFO!"); gm.gunHitByUFO(); }

public void updateSprite() // no built-in movement behaviour, // and drawing area is fixed { }

} // end of GunSprite class

the onlymajor change

Page 48: Games Programming with Java

240-492 Java Games: exAliens/9 48

6. MissileSprite6. MissileSprite

The MissileSprite class is unchanged from tThe MissileSprite class is unchanged from the one in the basic game.he one in the basic game.

Page 49: Games Programming with Java

240-492 Java Games: exAliens/9 49

6.1. MissileSprite.java6.1. MissileSprite.java

import java.awt.*;import javax.swing.*;import java.util.*;

import AndySprite.ImagesSprite;

public class MissileSprite extends ImagesSprite{ static final int Y_SPEED = -27;

// missile flies upwards

ArrayList targets;:

completelyunchanged

Page 50: Games Programming with Java

240-492 Java Games: exAliens/9 50

MissileSprite(ArrayList ts, int w, int h) { super(w, h); setStep(0, Y_SPEED); // movement loadImage("image", "missile");

targets = ts; // sprites to hit

// (x,y) loc is not set until missile fired

setActive(false); // missile not enabled yet }

Page 51: Games Programming with Java

240-492 Java Games: exAliens/9 51

public void launch(int xLocation) // xLocation is barrel position of gun { if (!isActive()) { // if not already flying locy = getPHeight() - getHeight(); locx = xLocation; setActive(true); } }

Page 52: Games Programming with Java

240-492 Java Games: exAliens/9 52

public void updateSprite() { UFOSprite ufo; if (isActive()) { if (locy+getHeight() <= 0) // off top screen setActive(false); else { Rectangle me = getMyRectangle(); for(int i=0; i < targets.size(); i++) { ufo = (UFOSprite) targets.get(i); if ( ufo.intersect(me) ) { ufo.hit(); // tell target is hit setActive(false); break; }} moveSprite(); }} } // end of updateSprite()

} // end of MissileSprite class

Page 53: Games Programming with Java

240-492 Java Games: exAliens/9 53

7. UFOSprite7. UFOSprite

GunSprite MissileSpriteUFOSpriteUFOSpriteUFOSpriteUFOSprite

get gun barrel position;tell gun that it hasbeen hit by a UFO

check if missile intersectsa UFO; announce hit

GameManagersend msgs;report death;report landing

Page 54: Games Programming with Java

240-492 Java Games: exAliens/9 54

7.1. UFOSprite Extensions7.1. UFOSprite Extensions

Each UFOSprite has a reference to GameMEach UFOSprite has a reference to GameManager so that landing, destruction, and otheanager so that landing, destruction, and other messages, can be communicated to the Gr messages, can be communicated to the GUI.UI.

An An EXPLODEEXPLODE state state– requires new explosion related methodsrequires new explosion related methods– uses an explosion animationuses an explosion animation

Page 55: Games Programming with Java

240-492 Java Games: exAliens/9 55

7.2. Simple State Diagram7.2. Simple State Diagram(no probabilities)

standby

attack

retreat

land

spritecreation land

successfully

explode

hit()

hit()hit()

Page 56: Games Programming with Java

240-492 Java Games: exAliens/9 56

7.3.7.3.UFOUFOSprite Sprite UMLUML

Page 57: Games Programming with Java

240-492 Java Games: exAliens/9 57

7.4. UFOSprite.java7.4. UFOSprite.java (Extended) (Extended)import javax.swing.*;import java.awt.*;import AndySprite.ImagesLoopSprite;

public class UFOSprite extends ImagesLoopSprite{ static final int UFO_NUMS = 6; static final int EXPL_NUMS = 4; // expl frames

int state; // current UFO state static final int STANDBY = 0; // UFO states static final int ATTACK = 1; static final int RETREAT = 2; static final int LAND = 3; static final int EXPLODE = 4; // new state

:

Page 58: Games Programming with Java

240-492 Java Games: exAliens/9 58

// probability of state transitions static final double STANDBY_EXIT = .95; static final double ATTACK_EXIT = .95; static final double RETREAT_EXIT = .95; static final double LAND_EXIT = .95; static final double FLIP_X = 0.9; static final int RETREAT_Y = 17;

:

Page 59: Games Programming with Java

240-492 Java Games: exAliens/9 59

private GunSprite gun; private GameManager gm;

private int explosion_counter; // detect when explosion has finished

public UFOSprite(int x, int y, int w, int h,GunSprite g, GameManager gm)

{ super(x,y,w,h, "image", "ufo", UFO_NUMS); gun = g; this.gm = gm; setCurrentImageNo( getRand(UFO_NUMS-1) ); startStandby(); } // end of UFOSprite()

Page 60: Games Programming with Java

240-492 Java Games: exAliens/9 60

public void hit() // ufo is invulnerable when attacking, but is // pushed back; otherwise, time to explode { if (state == ATTACK) { // tell gm gm.setMessage("Your puny missiles have little effect Earthling!"); locy -= RETREAT_Y; // some effect now } else // time to explode startExplode(); // previously just printed a message }

Page 61: Games Programming with Java

240-492 Java Games: exAliens/9 61

// the state machine for the UFO public void updateSprite() { if (gun.intersect( getMyRectangle() )) {

gun.hit(); // UFO has hit the gun setActive(false);

} else { // otherwise update UFO state double r1 = Math.random(); double r2 = Math.random(); switch (state) { case STANDBY: standbyAction(r1,r2); break; case ATTACK: attackAction(r1,r2); break;

:

Page 62: Games Programming with Java

240-492 Java Games: exAliens/9 62

case RETREAT: retreatAction(r1,r2); break; case LAND: landAction(r1,r2); break; case EXPLODE: explodeAction(); break; } super.updateSprite();

// do inherited update as well } } // end of updateSprite()

Page 63: Games Programming with Java

240-492 Java Games: exAliens/9 63

// For each action there is a choice whether // to change state or stay in existing state

private void standbyAction(double r1, double r2) { if (r1 > STANDBY_EXIT) { // change state

if (r2 > 0.5) // attack or land startAttack(); else startLand(); }

else if ((locx < getWidth()) || // stay (locx > getPWidth() - getWidth()) ||

(r2 > FLIP_X)) dx = -dx; // change x direction

} // end of standbyAction()

Page 64: Games Programming with Java

240-492 Java Games: exAliens/9 64

private void attackAction(double r1, double r2) { if ((r1 > ATTACK_EXIT) || (locy > gun.getGunY() - RETREAT_Y))

startRetreat(); else if ((locx < getWidth()) || (locx > getPWidth() - getWidth()) ||

(r2 > FLIP_X)) dx = -dx;

} // end of attackAction()

Page 65: Games Programming with Java

240-492 Java Games: exAliens/9 65

private void retreatAction(double r1, double r2) { if (r1 > RETREAT_EXIT) {

if (r2 > 0.5) // attack or go to standby startAttack(); else startStandby();

} else if (locy < RETREAT_Y)

startStandby(); } // end of retreatAction()

Page 66: Games Programming with Java

240-492 Java Games: exAliens/9 66

private void landAction(double r1, double r2) { if (r1 > LAND_EXIT)

startStandby(); else if (locy >= getPHeight()-getHeight()) { // time to land gm.setMessage("ufo landed"); // tell gm gm.ufoLanded(); setActive(false); } } // end of landAction()

Page 67: Games Programming with Java

240-492 Java Games: exAliens/9 67

private void explodeAction() { explosion_counter++; if (explosion_counter == EXPL_NUMS) {

// finished showing explosion; tell gm gm.setMessage("Arrrgh... UFO destroyed!"); gm.ufoKilled();

clearImages(); // reset image to ufo loadImages("image", "ufo", UFO_NUMS); setLooping(true); // show ufo looping startStandby();

setActive(false); } } // end of explodeAction()

new statebehaviour

Page 68: Games Programming with Java

240-492 Java Games: exAliens/9 68

private void startStandby() { setStep( getRand(8)-4, 0); // move left or right state = STANDBY; }

private void startAttack() { // move left or right; descend quickly setStep( getRand(10)-5, getRand(5)+4 ); state = ATTACK; }

private void startRetreat() { setStep(0, -getRand(3) - 2 ); // move up quickly state = RETREAT; }

Page 69: Games Programming with Java

240-492 Java Games: exAliens/9 69

protected void startLand() { setStep( 0, getRand(3) + 2 ); // descend state = LAND; }

protected void startExplode() // load new image sequence { explosion_counter = 0; clearImages(); // set images to explode loadImages("image", "explode", EXPL_NUMS); setLooping(false); // show seq only once state = EXPLODE; gm.playExplosion(); // play sound }

private int getRand(int x) { return (int)(x * Math.random()); }

} // end of UFOSprite class

start of explode state

Page 70: Games Programming with Java

240-492 Java Games: exAliens/9 70

7.5. Animating an Explosion7.5. Animating an Explosion

The UFOSprite displays a looping series of The UFOSprite displays a looping series of UFO images.UFO images.

To become an explosion:To become an explosion:– the UFO images must be deleted (cleared);the UFO images must be deleted (cleared);– explosion images must be loaded;explosion images must be loaded;– looping must be switched off (made false)looping must be switched off (made false)

This is done in startExplode()This is done in startExplode()

continued

Page 71: Games Programming with Java

240-492 Java Games: exAliens/9 71

After an ExplosionAfter an Explosion

The UFOSprite will be reused, so its images The UFOSprite will be reused, so its images must be reset to be UFOs:must be reset to be UFOs:– the explosion images must be cleared;the explosion images must be cleared;– the UFO images must be loaded again;the UFO images must be loaded again;– looping must be switched onlooping must be switched on

This is done in explodeAction().This is done in explodeAction().

Page 72: Games Programming with Java

240-492 Java Games: exAliens/9 72

8. Extension to ImagesSprite8. Extension to ImagesSprite

It would be useful if multiple sequences of iIt would be useful if multiple sequences of images could be stored in an ImagesSprite omages could be stored in an ImagesSprite object.bject.

Then there would be no need to keep cleariThen there would be no need to keep clearing/loading the UFO and explosion image seng/loading the UFO and explosion image sequences in UFOSprite.quences in UFOSprite.