1 / 72

Games Programming with Java

Games Programming with Java. 240-492, Special Topics in Comp. Eng. II Semester 1, 2002-2003. Objectives to describe and illustrate techniques for writing larger games control hierarchies, sprite interactions, managers, sprite subclasses, state diagrams. 8. Alien Attack v.1. Overview.

ethel
Download Presentation

Games Programming with Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Games Programming with Java 240-492, Special Topics in Comp. Eng. II Semester 1, 2002-2003 • Objectives • to describe and illustrate techniques for writing larger games • control hierarchies, sprite interactions, managers, sprite subclasses, state diagrams 8. Alien Attack v.1

  2. Overview 1. Alien Attack 2. Control Hierarchy 3. The Game Manager 4. The Gun Manager 5. The UFO Manager 6. The Gun Sprite 7. The Missile Sprite 8. The UFO Sprite

  3. 1. Alien Attack • Your mission: • to prevent aliens from landing on Earth, by destroying their UFOs before they land • you can shoot missiles at UFOs from a missile launcher • to avoid being touched by a UFO

  4. 1.1. Playing the Game a missile Alien UFOs (7 of them) the gun barrel the missile launcher continued

  5. I closed the game

  6. 1.2. Game Restrictions • The launcher can only move left or right, and stops at the edges of the window • movement is done using the left and right arrow keys • A missile will not destroy a UFO when it is in its ‘attack’ state. • A destroyed UFO disappears, but a new one appears immediately! continued

  7. A missile can only be fired straight up • a missile is fired by pressing the up arrow key • Only one missile can be fired at a time • another cannot be fired until the current missile has hit a UFO or gone off the top of the screen

  8. 1.3. Game Background • The original version of this game is described in: • "Black Art of Java Game Programming”Joel Fan et al., The Waite Group, 1996Chapter 5 • I have recoded it to use my sprite classes, and modern Java coding.

  9. 2. Control Hierarchy creation andinitialisation Game Manager method calls updates Gun Manager UFO Manager redraws Gun Sprite Missile Sprite UFO Sprites continued

  10. A hierarchy of managers is a good way to hide details • e.g. the GameManager does not need to know about the low-level interactions between sprites controlled by the GunManager • A hierarchy helps scaleability • as more sprites are added, the top-levels of the game are affected less

  11. Sprite Interactions launch from GunManager moves from GunManager UFOSprite UFOSprite GunSprite MissileSprite UFOSprite UFOSprite check if missile intersects a UFO; announce hit get gun barrel position; tell gun that it has been hit by a UFO

  12. 3. The Game Manager Most managers carry out these 5 kinds of tasks • Main tasks: • 1. create and initialise gun and ufo managers • 2. translate player key presses into calls to the gun manager methods • 2.1. move the gun • 2.2. fire a missile • 3. pass update and redraw requests to gun and ufo managers

  13. 3.1. GameManager UML

  14. 3.2. GameManager.java Code import 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");:

  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 is passed to the GameManagerPanel

  16. public static void main( String args[] ) { new GameManager(); } } // end of GameManager class

  17. class GameManagerPanel extends JPanel implements ActionListener{ static final int PWIDTH = 500; static final int PHEIGHT = 500; private GunManager gm; private UFOManager um; :

  18. Part of initialisation is sharing info. between sub-managers and sprites 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

  19. public void moveLeft() { gm.moveGunLeft(); } public void moveRight() { gm.moveGunRight(); } public void fireMissile() { gm.fireMissile(); } tasks 2.1 and 2.2

  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

  21. 4. The Gun Manager • Main tasks: • 1. create and initialise a GunSprite and MissileSprite object • 2. pass gun movement requests to GunSprite • 3. pass firing requests to MissileSprite • 4. pass update and redraw requests to both sprites

  22. 4.1. GunManager UML

  23. 4.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; :

  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

  25. task 3 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 4

  26. 4.3. Notes • The missile sprite is passed an arraylist of UFO references when it is created (targets): missile = new MissileSprite(targets, pWidth, pHeight); • this means that the missile can communicate directly with the UFOs

  27. 5. The UFO Manager • Main tasks: • 1. create and initialise 7 UFOSprite objects • 1.1. these are reused through out the game • 1.2. part of the initialisation is to generate a random starting position for each object • 2. pass update and redraw requests to all the sprites

  28. 5.1. UFOManager UML

  29. 5.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; :

  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

  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

  32. task 1.1 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

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

  34. 5.3. Notes • Each UFO sprite is passed a reference to the gun sprite when it is created (gun): new UFOSprite(xPosn, yPosn, pWidth, pHeight, gun) • this means a UFO can communicate directly with the gun

  35. 6. The Gun Sprite • It processes updates and redraws from the Gun manager, and has the interactions: moves from GunManager UFOSprite UFOSprite GunSprite UFOSprite UFOSprite get gun barrel position; tell gun that it has been hit by a UFO

  36. 6.1. Gun Positioning • We must calculate the top-left (x,y) coordinate for the gun sprite so that it rests on the bottom of the window. • The sprite must not be allowed to go too far left or right • its central ‘gun barrel’ must never go outside the window

  37. Window Lengths PWidth (panel width) PHeight (panel height) height width barrel continued

  38. Coordinate: ( PWidth/2-width/2, PHeight-height) Maximum x position: PWidth-width/2 Minimum x position: -width/2 The current barrel x-coordinate is the current x-coordinate of the image (locx) + width/2

  39. 6.2. GunSprite UML

  40. 6.3. GunSprite.java Code import 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); }

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

  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

  43. 7. The Missile Sprite • It processes updates and redraws from the Gun manager, and has the interactions: launch from GunManager UFOSprite UFOSprite MissileSprite UFOSprite UFOSprite check if missile intersects a UFO; announce hit

  44. 7.1. Missile Initialisation • The gun manager can partially initialise the gun sprite: • set its speed in the y-direction • But its (x,y) location is set only when the missile is ‘fired’; then the missile is made active.

  45. 7.2. Missile Termination • A missile is finished when: • it passes off the top of the window, or • it hits (intersects) a UFO • this requires an intersection test with each UFO at each update • the missile must have references to all the UFOs • The missile sprite is reused by making it inactive.

  46. 7.3. MissileSprite UML

  47. 7.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 upwardsArrayList targets; // the UFOs :

  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 firedsetActive(false); // missile not enabled yet }

  49. public void launch(int xLocation) // xLocation is the barrel posn of the gun { if (!isActive()) { // if not already flyinglocy = getPHeight() - getHeight(); locx = xLocation; setActive(true); } } the x location is supplied by the gun manager, which gets it from the gun sprite

  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

More Related