240-492 java games: aliens/81 games programming with java v objectives –to describe and illustrate...

72
240-492 Java Games: Aliens/8 Games Programming with Java Games Programming with Java Objectives Objectives to describe and illustrate techniques for writing larger to describe and illustrate techniques for writing larger games games control hierarchies, sprite interactions, managers, sprite subcl control hierarchies, sprite interactions, managers, sprite subcl asses, state diagrams asses, state diagrams 240-492, Special Topics in Comp. Eng. II Semester 1, 2002-2003 8. Alien Att ack v.1

Upload: bruno-rich

Post on 25-Dec-2015

243 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 1

Games Programming with JavaGames Programming with Java

ObjectivesObjectives– to describe and illustrate techniques for writing larger gamesto describe and illustrate techniques for writing larger games

control hierarchies, sprite interactions, managers, sprite subclasses, statcontrol hierarchies, sprite interactions, managers, sprite subclasses, state diagrams e diagrams

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

8. Alien Attack v.1

Page 2: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 2

OverviewOverview

1. 1. Alien AttackAlien Attack2. 2. Control HierarchyControl Hierarchy3. 3. The Game ManagerThe Game Manager4. 4. The Gun ManagerThe Gun Manager5. 5. The UFO ManagerThe UFO Manager6.6. The Gun SpriteThe Gun Sprite7.7. The Missile SpriteThe Missile Sprite8.8. The UFO SpriteThe UFO Sprite

Page 3: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 3

1. Alien Attack1. Alien Attack

Your mission:Your mission:– to prevent aliens from landing on Earth, by dto prevent aliens from landing on Earth, by d

estroying their UFOs before they landestroying their UFOs before they land you can shoot missiles at UFOs from a missile layou can shoot missiles at UFOs from a missile la

uncheruncher

– to avoid being touched by a UFOto avoid being touched by a UFO

Page 4: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 4

1.1. Playing the Game1.1. Playing the Game

continued

Alien UFOs (7 of them)

a missile

the missilelauncher

the gunbarrel

Page 5: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 5

I closed the game

Page 6: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 6

1.2. Game Restrictions1.2. Game Restrictions The launcher can only move left or right, and stoThe launcher can only move left or right, and sto

ps at the edges of the windowps at the edges of the window– movement is done using the left and right arrow keysmovement is done using the left and right arrow keys

A missile will not destroy a UFO when it is in its A missile will not destroy a UFO when it is in its ‘attack’ state.‘attack’ state.

A destroyed UFO disappears, but a new one appeA destroyed UFO disappears, but a new one appears immediately!ars immediately!

continued

Page 7: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 7

A missile can only be fired straight upA missile can only be fired straight up– a missile is fired by pressing the up arrow keya missile is fired by pressing the up arrow key

Only one missile can be fired at a timeOnly one missile can be fired at a time– another cannot be fired until the current missile another cannot be fired until the current missile

has hit a UFO has hit a UFO oror gone off the top of the screen gone off the top of the screen

Page 8: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 8

1.3. Game Background1.3. Game Background

The original version of this game is describThe original version of this game is described in:ed in:– ""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 5Chapter 5

– I have recoded it to use my sprite classes, and I have recoded it to use my sprite classes, and modern Java coding.modern Java coding.

Page 9: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 9

2. Control Hierarchy2. Control Hierarchy

Game Manager

Gun Manager UFO Manager

Gun Sprite Missile Sprite UFO Sprites

creation andinitialisation

updates

redraws

continued

method calls

Page 10: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 10

A hierarchy of managers is a good way to A hierarchy of managers is a good way to hidhide detailse details– e.g. the e.g. the GameManagerGameManager does not need to know abo does not need to know abo

ut the low-level interactions between sprites contut the low-level interactions between sprites controlled by the rolled by the GunManagerGunManager

A hierarchy helps A hierarchy helps scaleabilityscaleability– as more sprites are added, the top-levels of the gaas more sprites are added, the top-levels of the ga

me are affected lessme are affected less

Page 11: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 11

Sprite InteractionsSprite 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

Page 12: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 12

3. The Game Manager3. The Game Manager

Main tasks:Main tasks:– 1. 1. createcreate and and initialiseinitialise gun and ufo managers gun and ufo managers– 2. translate player key presses into 2. translate player key presses into callscalls to the to the

gun manager methodsgun manager methods 2.1. move the gun2.1. move the gun 2.2. fire a missile2.2. fire a missile

– 3. pass 3. pass updateupdate and and redrawredraw requests to gun and requests to gun and ufo managersufo managers

Most managers carry outthese 5 kinds of tasks

Page 13: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 13

3.1. GameManager UML3.1. GameManager UML

Page 14: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 14

3.2. GameManager.java Code3.2. GameManager.java Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class GameManager extends JFrame { GameManagerPanel gmp;

public GameManager() { super( "Alien Attack!!" ); Container c = getContentPane(); c.setLayout( new BorderLayout() ); gmp = new GameManagerPanel();

c.add( gmp, "Center");:

Page 15: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 15

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

setDefaultCloseOperation( Frame.EXIT_ON_CLOSE);

pack(); setResizable(false); show(); } // end of GameManager()

a key press ispassed to theGameManagerPanel

Page 16: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 16

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

} // end of GameManager class

Page 17: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 17

class GameManagerPanel extends JPanel

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

private GunManager gm; private UFOManager um;

:

Page 18: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 18

public GameManagerPanel() { setBackground(Color.black); setPreferredSize(new Dimension(PWIDTH,PHEIGHT));

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

// create the timer Timer animatorTimer = new Timer(50, this);

animatorTimer.setInitialDelay(0); animatorTimer.setCoalesce(true);

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

task 1

Part of initialisation issharing info. between sub-managers and sprites

Page 19: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 19

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

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

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

tasks 2.1 and 2.2

Page 20: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 20

public void actionPerformed(ActionEvent e) // timer triggers execution of this method { gm.updateSprites(); um.updateSprites(); repaint(); }

public void paintComponent(Graphics g) { super.paintComponent(g); gm.drawSprites(g); um.drawSprites(g); }

} // end of GameManagerPanel class

task 3

task 3

Page 21: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 21

4. The Gun Manager4. The Gun Manager

Main tasks:Main tasks:– 1. 1. createcreate and and initialiseinitialise a a GunSpriteGunSprite and and MissilMissil

eSpriteeSprite object object– 2. pass gun movement requests to 2. pass gun movement requests to GunSpriteGunSprite

– 3. pass firing requests to 3. pass firing requests to MissileSpriteMissileSprite

– 4. pass 4. pass updateupdate and and redrawredraw requests to both sprite requests to both spritess

Page 22: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 22

4.1. GunManager UML4.1. GunManager UML

Page 23: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 23

4.2. GunManager.java Code4.2. GunManager.java Code

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;:

Page 24: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 24

public GunManager(int w, int h) // Only the gun is made here; the missile is // created by makeMissile() { gun = new GunSprite(w, h); pWidth = w; pHeight = h; }

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

pWidth, pHeight); }

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

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

task 1

task 2

Page 25: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 25

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

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

task 3

task 4

Page 26: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 26

4.3. Notes4.3. Notes

The missile sprite is passed an arraylist of UThe missile sprite is passed an arraylist of UFO references when it is created (FO references when it is created (targetstargets):):

missile = new MissileSprite(targets, pWidth, pHeight);

– this means that the missile can communicate direthis means that the missile can communicate directly with the UFOsctly with the UFOs

Page 27: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 27

5. The UFO Manager5. The UFO Manager

Main tasks:Main tasks:– 1. 1. createcreate and and initialiseinitialise 7 7 UFOSpriteUFOSprite objects objects

1.1. these are reused through out the game1.1. these are reused through out the game 1.2. part of the initialisation is to generate a rando1.2. part of the initialisation is to generate a rando

m starting position for each objectm starting position for each object

– 2. pass 2. pass updateupdate and and redrawredraw requests to all the requests to all the spritessprites

Page 28: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 28

5.1. UFOManager UML5.1. UFOManager UML

Page 29: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 29

5.2. UFOManager.java Code5.2. UFOManager.java Code

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 int pWidth, pHeight;:

Page 30: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 30

public UFOManager(GunSprite gun, int w, int h) { 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) ); } } // end of UFOManager()

task 1

task 1.2

Page 31: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 31

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 posn

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

} } } // end of updateSprites()

task 2

Page 32: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 32

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); } }

task 2

task 1.1

Page 33: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 33

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

} // end of UFOManager class

Page 34: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 34

5.3. Notes5.3. Notes

Each UFO sprite is passed a reference to the Each UFO sprite is passed a reference to the gun sprite when it is created (gun sprite when it is created (gungun):):

new UFOSprite(xPosn, yPosn,

pWidth, pHeight, gun)

– this means a UFO can communicate directly withis means a UFO can communicate directly with the gunth the gun

Page 35: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 35

6. The Gun Sprite6. The Gun Sprite

It processes updates and redraws from the GIt processes updates and redraws from the Gun manager, and has the interactions:un manager, and has the interactions:

GunSpriteUFOSpriteUFOSpriteUFOSpriteUFOSprite

moves fromGunManager

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

Page 36: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 36

6.1. Gun Positioning6.1. Gun Positioning

We must calculate the top-left (x,y) coordinWe must calculate the top-left (x,y) coordinate for the gun sprite so that it rests on the bate for the gun sprite so that it rests on the bottom of the window.ottom of the window.

The sprite must not be allowed to go too far The sprite must not be allowed to go too far left or rightleft or right– its central ‘gun barrel’ must never go outside thits central ‘gun barrel’ must never go outside th

e windowe window

Page 37: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 37

Window LengthsWindow Lengths

PHeight(panel height)

PWidth (panel width)

width

height

barrelcontinued

Page 38: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 38

Coordinate: ( PWidth/2-width/2, PHeight-height)

Minimum x position: -width/2

Maximum x position: PWidth-width/2

The current barrel x-coordinate isthe current x-coordinate of the image (locx) + width/2

Page 39: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 39

6.2. GunSprite UML6.2. GunSprite UML

Page 40: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 40

6.3. GunSprite.java Code6.3. GunSprite.java Codeimport java.awt.*;import javax.swing.*;import AndySprite.ImagesSprite;

public class GunSprite extends ImagesSprite{ GunSprite(int w, int h) /* Override ImagesSprite() constructor so currect starting posn for sprite can be calculated before image is made visible.*/ { super(w, h); setStep(0,0); // no movement loadImage("image", "gun"); setPosition(getPWidth()/2 - getWidth()/2,

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

Page 41: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 41

public void move(int xDist) // move but keep barrel on-screen { int newBPosn = locx + xDist + getWidth()/2; // position of gun barrel

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

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

setPosition(locx, locy); }

Page 42: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 42

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

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

public void hit() // gun is hit by a ufo { System.out.println("Gun is hit by a UFO!"); }

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

} // end of GunSprite class

Page 43: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 43

7. The Missile Sprite7. The Missile Sprite

It processes updates and redraws from the GIt processes updates and redraws from the Gun manager, and has the interactions:un manager, and has the interactions:

MissileSpriteUFOSpriteUFOSpriteUFOSpriteUFOSprite

launch fromGunManager

check if missile intersectsa UFO; announce hit

Page 44: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 44

7.1. Missile Initialisation7.1. Missile Initialisation

The gun manager can The gun manager can partiallypartially initialise the initialise the gun sprite:gun sprite:– set its speed in the y-directionset its speed in the y-direction

But its (x,y) location is set only when the miBut its (x,y) location is set only when the missile is ‘fired’; then the missile is made actissile is ‘fired’; then the missile is made active.ve.

Page 45: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 45

7.2. Missile Termination7.2. Missile Termination

A missile is finished when:A missile is finished when:– it passes off the top of the window, orit passes off the top of the window, or– it hits (intersects) a UFOit hits (intersects) a UFO

this requires an intersection test with each UFO at eacthis requires an intersection test with each UFO at each updateh update

the missile must have references to all the UFOsthe missile must have references to all the UFOs

The missile sprite is reused by making it inacThe missile sprite is reused by making it inactive.tive.

Page 46: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 46

7.3. MissileSprite UML7.3. MissileSprite UML

Page 47: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 47

7.4. MissileSprite.java Code7.4. MissileSprite.java Code

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; // the UFOs:

Page 48: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 48

MissileSprite(ArrayList ts, int w, int h) /* Override ImagesSprite() constructor so sprite can be partially setup. It is started by a separate call to fireMissile(). */ { super(w, h); setStep(0, Y_SPEED); // movement loadImage("image", "missile");

targets = ts; // ufos to try to hit

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

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

Page 49: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 49

public void launch(int xLocation) // xLocation is the barrel posn of the gun { if (!isActive()) {

// if not already flying locy = getPHeight() - getHeight(); locx = xLocation; setActive(true); } }

the x location is supplied by thegun manager, which gets it fromthe gun sprite

Page 50: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 50

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

Page 51: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 51

8. The UFO Sprite8. The UFO Sprite

It processes updates and redraws from the UIt processes updates and redraws from the UFO manager, and has the interactions:FO manager, and has the interactions:

GunSprite MissileSpriteUFOSpriteUFOSpriteUFOSpriteUFOSprite

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

check if missile intersectsa UFO; announce hit

Page 52: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 52

8.1. UFO Behaviour8.1. UFO Behaviour

A UFO sprite must act in an ‘interesting’ wA UFO sprite must act in an ‘interesting’ way, which cannot be easily predicted by the ay, which cannot be easily predicted by the player.player.

Each UFO should act in a (slightly) differenEach UFO should act in a (slightly) different way.t way.

continued

Page 53: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 53

Complex behaviour is represented by multiple internal Complex behaviour is represented by multiple internal states inside the spritestates inside the sprite– each state has a different behavioureach state has a different behaviour

A good way to model multiple states is with a A good way to model multiple states is with a state trastate transition diagramnsition diagram..

The unpredicatable behaviour required for a sprite meaThe unpredicatable behaviour required for a sprite means that the state diagram will ns that the state diagram will use probabilities to deciduse probabilities to decide on its transitionse on its transitions..

Page 54: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 54

8.2. Four UFO States8.2. Four UFO States

1. Standby.1. Standby.– the UFO moves left and right onlythe UFO moves left and right only

2. Attack.2. Attack.– the UFO moves quickly downwards towards ththe UFO moves quickly downwards towards th

e missile launcher, and left and righte missile launcher, and left and right– it is invunerable to missilesit is invunerable to missiles

continued

Page 55: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 55

3. Retreat3. Retreat– the UFO moves upwards, away from the missilthe UFO moves upwards, away from the missil

e launchere launcher

4. Land.4. Land.– the UFO descends at a slow rate, with the intentthe UFO descends at a slow rate, with the intent

ion of landingion of landing

Page 56: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 56

8.3. Simple State Diagram8.3. Simple State Diagram(no probabilities)

standby

attack

retreat

land

spritecreation land

successfully

Page 57: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 57

More Detailed State DiagramMore Detailed State Diagram(with probabilities and some tests)

standby >0.95

attack

retreat

land

spritecreation >0.95

>0.95

>0.95 botm?

landsuccessfully

far?

Y

N

Y

or

N

Y

Yor

NN

Y

N

Y

andnear

N

Page 58: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 58

8.4. State Diagram to Code8.4. State Diagram to Code

Entering a stateEntering a state is coded with the method: is coded with the method:– start<State>()start<State>()

– it initialises the sprite’s new movementit initialises the sprite’s new movement– it initialises the new stateit initialises the new state

continued

Page 59: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 59

Processing inside a stateProcessing inside a state (and any tests) is c (and any tests) is coded with the method:oded with the method:– <State>Action()<State>Action()

– it evaluates the tests, calculates probabilities, anit evaluates the tests, calculates probabilities, and then calls the relevant d then calls the relevant start<State>()start<State>() meth method if a new state is going to be enteredod if a new state is going to be entered

continued

Page 60: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 60

The The entire state diagramentire state diagram is controlled from is controlled from updateSprite()updateSprite()

– it knows the current state by storing the value in it knows the current state by storing the value in the the statestate variable variable

– at each update, it calls the relevant at each update, it calls the relevant <State>Action()<State>Action() method to decide what to d method to decide what to do nexto next

Page 61: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 61

UFOSprite UMLUFOSprite UML

4 Action methods

4 start methods

Page 62: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 62

UFOSprite.javaUFOSprite.javaimport javax.swing.*;import java.awt.*;import AndySprite.ImagesLoopSprite;

public class UFOSprite extends ImagesLoopSprite{ static final int UFO_NUMS = 6;

int state; // current UFO state // UFO state values, represented by constants static final int STANDBY = 0; static final int ATTACK = 1; static final int RETREAT = 2; static final int LAND = 3;

:

Page 63: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 63

// probabilities used in 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;

private GunSprite gun;

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

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

Page 64: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 64

public void hit() // alien is invulnerable when it's attacking; // otherwise, deactive sprite (so can be reused)

{ if (state == ATTACK) System.out.println("Your puny missiles

have no effect Earthling!"); else { System.out.println(

"Arrrgh... UFO destroyed!"); setActive(false); } }

Page 65: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 65

// 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;

:

a switch based onthe state value decides which Action()method to call

Page 66: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 66

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

// do inherited update as well// which will animate the UFO

} } // end of updateSprite()

Page 67: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 67

// For each action decide whether to change // state or stay in the 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()) || (locx > getPWidth() - getWidth()) ||

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

} // end of standbyAction()

Page 68: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 68

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 69: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 69

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 70: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 70

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

startStandby(); else if (locy >=getPHeight()-getHeight()) {

// touched the ground System.out.println("ufo landed") ; setActive(false); } } // end of landAction()

private void startStandby() { setStep( getRand(8)-4, 0);

// move left or right state = STANDBY; }

Page 71: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 71

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; }

protected void startLand() { setStep( 0, getRand(3) + 2 );

// descend quickly state = LAND; }

Page 72: 240-492 Java Games: Aliens/81 Games Programming with Java v Objectives –to describe and illustrate techniques for writing larger games u control hierarchies,

240-492 Java Games: Aliens/8 72

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

} // end of UFOSprite class