SpaceInvaders
Class SpaceInvaders

java.lang.Object
  |
  +--java.awt.Component
        |
        +--java.awt.Container
              |
              +--java.awt.Panel
                    |
                    +--java.applet.Applet
                          |
                          +--SpaceInvaders.SpaceInvaders
All Implemented Interfaces:
javax.accessibility.Accessible, java.awt.event.ActionListener, java.util.EventListener, java.awt.image.ImageObserver, java.awt.event.ItemListener, java.awt.event.KeyListener, java.awt.MenuContainer, java.lang.Runnable, java.io.Serializable

public class SpaceInvaders
extends java.applet.Applet
implements java.awt.event.ActionListener, java.awt.event.ItemListener, java.awt.event.KeyListener, java.lang.Runnable

An applet simulating the popular Space Invaders video game. An initial screen asks player to specify a spaceship style and difficulty level to use in the game. A "Start game" button brings up the game screen. The difficulty level is achieved by adjusting the speed of the aliens. After each game, the same spaceship and difficulty choice menus appear along with a "Next game" button to allow continuous play without restarting the applet. Rules: Player may have up to three lasers on screen at a time. Three rows of eight aliens advance left to right, down, then right to left across the screen until player has shot them all or one of them hits the spaceship. Lasers are shot by pressing the spacebar, the spaceship can be moved right or left by arrow keys.

Since:
Java 1.1
Version:
1.5, January 2002
Author:
Susan B. Cavanaugh
See Also:
Serialized Form

Inner classes inherited from class java.applet.Applet
java.applet.Applet.AccessibleApplet
 
Inner classes inherited from class java.awt.Panel
java.awt.Panel.AccessibleAWTPanel
 
Inner classes inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Inner classes inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.AWTTreeLock
 
Field Summary
private  int alienCount
          aliens remaining
private  java.awt.Image[] alienImage
          alien image style array
private  boolean appInit
          applet initialization flag
private  int BEGINNER
          beginner game speed
private  boolean clearScreen
          screen clearing flag
private  int COLS
          number of columns in alien force
private  java.awt.Choice diffChoices
          game difficulty choice menu
private  int EXPERT
          expert game speed
private  java.applet.AudioClip gameAudio
          game background music
private  boolean gameOver
          game over flag
private  Score gameScore
          current game score
private  int height
          applet height
private  java.applet.AudioClip hitAudio
          laser hitting alien sound
private  int INTERMEDIATE
          intermediate game speed
private  int LASERS
          maximum number of lasers allowed to fly
private  java.applet.AudioClip laserShoot
          laser shooting swoosh
private  java.awt.Image modShipImage
          modern spaceship image
private  Alien[][] myAliens
          alien array
private  Ship myShip
          the spaceship
private  boolean playGame
          proceed with game flag
private  int ROWS
          number of rows in alien force
private  Point SCORE_POSITION
          position of score on screen
private  java.awt.Image selShipImage
          spaceship image selection
private  boolean setGame
          first game setup flag
private  java.awt.Choice shipChoices
          spaceship choice menu
private  java.applet.AudioClip shipHitAudio
          alien hitting ship sound
private  java.awt.Image shipImage
          current spaceship image
private  Star[] stars
          array of colored stars
private  java.awt.Button startButton
          start game button
private  java.awt.Image stdShipImage
          standard spaceship image
private  java.lang.Thread timer
          thread that controls game speed
private  int width
          applet width
private  boolean youLose
          lose game flag
private  java.applet.AudioClip youWinAudio
          victory gong
private  Laser[] zappers
          laser array
 
Fields inherited from class java.applet.Applet
accessibleContext, serialVersionUID, stub
 
Fields inherited from class java.awt.Panel
base, nameCounter
 
Fields inherited from class java.awt.Container
component, containerListener, containerSerializedDataVersion, dbg, dispatcher, layoutMgr, listeningBoundsChildren, listeningChildren, maxSize, ncomponents, printing, printingThreads
 
Fields inherited from class java.awt.Component
actionListenerK, adjustmentListenerK, appContext, background, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, changeSupport, componentListener, componentListenerK, componentOrientation, componentSerializedDataVersion, containerListenerK, cursor, dropTarget, enabled, eventMask, focusListener, focusListenerK, font, foreground, graphicsConfig, hasFocus, hierarchyBoundsListener, hierarchyBoundsListenerK, hierarchyListener, hierarchyListenerK, incRate, inputMethodListener, inputMethodListenerK, isInc, isPacked, itemListenerK, keyListener, keyListenerK, LEFT_ALIGNMENT, locale, LOCK, metrics, minSize, mouseListener, mouseListenerK, mouseMotionListener, mouseMotionListenerK, name, nameExplicitlySet, newEventsOnly, ownedWindowK, parent, peer, peerFont, popups, prefSize, privateKey, RIGHT_ALIGNMENT, textListenerK, TOP_ALIGNMENT, valid, visible, windowClosingException, windowListenerK, x, y
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
SpaceInvaders()
           
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent ae)
          Handles game start button functions including starting game audio clip.
 boolean alienHitsShip(Alien alien, Ship ship)
          Determines if an alien collided with the spaceship.
 java.lang.String getAppletInfo()
          Returns information about this applet.
 java.lang.String[][] getParameterInfo()
          Returns information about the parameters that are settable in the HTML file.
 void init()
          Initialize the game: Set black background with stars randomly distributed, load game sounds and spaceship and alien images, initialize game object locations as they will appear on screen.
 void itemStateChanged(java.awt.event.ItemEvent ie)
          Handles menu selections for game difficulty and spaceship style.
 void keyPressed(java.awt.event.KeyEvent ke)
          Handles a space bar press as an attempt to shoot a laser and shoots a laser only if fewer than the maximum number allowed are on screen; play shooting sound if shot was made.
 void keyReleased(java.awt.event.KeyEvent ke)
          not used
 void keyTyped(java.awt.event.KeyEvent ke)
          not used
 boolean laserHitsAlien(Laser zap, Alien alien)
          Determines if a laser has hit an alien.
 void paint(java.awt.Graphics g)
          Paint all game objects and manage the moving of aliens and lasers.
 void run()
          Controls game speed by sleeping, then repainting when needed.
 void start()
          Restarts game music after minimization/maximization sequence if the music had been playing, then start game motion thread.
 void stop()
          Stops Space Invaders game including all audio clips.
 void update(java.awt.Graphics g)
          Overrides update to eliminate clearing of the graphics context before each screen paint in order to avoid annoying flicker and clears the screen when a flag is set.
 
Methods inherited from class java.applet.Applet
destroy, getAccessibleContext, getAppletContext, getAudioClip, getAudioClip, getCodeBase, getDocumentBase, getImage, getImage, getLocale, getParameter, isActive, newAudioClip, play, play, resize, resize, setStub, showStatus
 
Methods inherited from class java.awt.Panel
, addNotify, constructComponentName
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, adjustListeningChildren, applyOrientation, checkGD, countComponents, createChildHierarchyEvents, createHierarchyEvents, deliverEvent, dispatchEventImpl, dispatchEventToSelf, doLayout, eventEnabled, findComponentAt, findComponentAt, findComponentAt, getAccessibleAt, getAccessibleChild, getAccessibleChildrenCount, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents_NoClientCode, getComponents, getInsets, getLayout, getListeners, getMaximumSize, getMinimumSize, getMouseEventTarget, getPreferredSize, getWindow, initIDs, insets, invalidate, invalidateTree, isAncestorOf, layout, lightweightPaint, lightweightPrint, list, list, locate, minimumSize, nextFocus, numListening, paintComponents, paintHeavyweightComponents, paramString, postProcessKeyEvent, postsOldMouseEvents, preferredSize, preProcessKeyEvent, print, printComponents, printHeavyweightComponents, processContainerEvent, processEvent, proxyEnableEvents, proxyRequestFocus, readObject, remove, remove, removeAll, removeContainerListener, removeNotify, setFocusOwner, setFont, setLayout, transferFocus, validate, validateTree, writeObject
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addPropertyChangeListener, addPropertyChangeListener, areInputMethodsEnabled, bounds, checkImage, checkImage, checkWindowClosingException, coalesceEvents, contains, contains, createImage, createImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, getAccessibleIndexInParent, getAccessibleStateSet, getBackground, getBounds, getBounds, getColorModel, getComponentOrientation, getCursor, getDropTarget, getFont_NoClientCode, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getInputContext, getInputMethodRequests, getLocation, getLocation, getLocationOnScreen_NoTreeLock, getLocationOnScreen, getName, getNativeContainer, getParent_NoClientCode, getParent, getPeer, getSize, getSize, getToolkit, getToolkitImpl, getTreeLock, getWidth, getWindowForObject, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isDisplayable, isDoubleBuffered, isEnabled, isEnabledImpl, isFocusTraversable, isLightweight, isOpaque, isRecursivelyVisible, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, resetGC, reshape, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setForeground, setLocale, setLocation, setLocation, setName, setSize, setSize, setVisible, show, show, size, toString, transferFocus
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, registerNatives, wait, wait, wait
 

Field Detail

SCORE_POSITION

private final Point SCORE_POSITION
position of score on screen

ROWS

private final int ROWS
number of rows in alien force

COLS

private final int COLS
number of columns in alien force

LASERS

private final int LASERS
maximum number of lasers allowed to fly

BEGINNER

private final int BEGINNER
beginner game speed

INTERMEDIATE

private final int INTERMEDIATE
intermediate game speed

EXPERT

private final int EXPERT
expert game speed

myShip

private Ship myShip
the spaceship

gameScore

private Score gameScore
current game score

width

private int width
applet width

height

private int height
applet height

zappers

private Laser[] zappers
laser array

myAliens

private Alien[][] myAliens
alien array

alienCount

private int alienCount
aliens remaining

gameAudio

private java.applet.AudioClip gameAudio
game background music

hitAudio

private java.applet.AudioClip hitAudio
laser hitting alien sound

shipHitAudio

private java.applet.AudioClip shipHitAudio
alien hitting ship sound

youWinAudio

private java.applet.AudioClip youWinAudio
victory gong

laserShoot

private java.applet.AudioClip laserShoot
laser shooting swoosh

alienImage

private java.awt.Image[] alienImage
alien image style array

shipImage

private java.awt.Image shipImage
current spaceship image

selShipImage

private java.awt.Image selShipImage
spaceship image selection

stdShipImage

private java.awt.Image stdShipImage
standard spaceship image

modShipImage

private java.awt.Image modShipImage
modern spaceship image

stars

private Star[] stars
array of colored stars

startButton

private java.awt.Button startButton
start game button

shipChoices

private java.awt.Choice shipChoices
spaceship choice menu

diffChoices

private java.awt.Choice diffChoices
game difficulty choice menu

appInit

private boolean appInit
applet initialization flag

setGame

private boolean setGame
first game setup flag

clearScreen

private boolean clearScreen
screen clearing flag

youLose

private boolean youLose
lose game flag

timer

private java.lang.Thread timer
thread that controls game speed

gameOver

private boolean gameOver
game over flag

playGame

private boolean playGame
proceed with game flag
Constructor Detail

SpaceInvaders

public SpaceInvaders()
Method Detail

init

public void init()
Initialize the game: Set black background with stars randomly distributed, load game sounds and spaceship and alien images, initialize game object locations as they will appear on screen.
Overrides:
init in class java.applet.Applet

start

public void start()
Restarts game music after minimization/maximization sequence if the music had been playing, then start game motion thread.
Overrides:
start in class java.applet.Applet

run

public void run()
Controls game speed by sleeping, then repainting when needed.
Specified by:
run in interface java.lang.Runnable

update

public void update(java.awt.Graphics g)
Overrides update to eliminate clearing of the graphics context before each screen paint in order to avoid annoying flicker and clears the screen when a flag is set.
Overrides:
update in class java.awt.Container
Parameters:
g - Graphics context to draw in.

paint

public void paint(java.awt.Graphics g)
Paint all game objects and manage the moving of aliens and lasers. Game ends when all aliens have been shot down, or one of the aliens has hit the spaceship.
Overrides:
paint in class java.awt.Container
Parameters:
g - Graphics context to draw in.

laserHitsAlien

public boolean laserHitsAlien(Laser zap,
                              Alien alien)
Determines if a laser has hit an alien. Method: Test all four corners of the laser to see if any of them falls within the alien object. Since the laser is smaller than the alien, this test is sufficient.
Parameters:
zap - the Laser object
alien - the Alien object
Returns:
laser "is within alien" flag

alienHitsShip

public boolean alienHitsShip(Alien alien,
                             Ship ship)
Determines if an alien collided with the spaceship. Method: Assumes there is a collision if alien is lower on screen than ship's nose AND alien's x coordinate is between ship's x extents.
Parameters:
alien - the Alien object
ship - the Ship object
Returns:
alien hit spaceship flag

keyPressed

public void keyPressed(java.awt.event.KeyEvent ke)
Handles a space bar press as an attempt to shoot a laser and shoots a laser only if fewer than the maximum number allowed are on screen; play shooting sound if shot was made.
Specified by:
keyPressed in interface java.awt.event.KeyListener
Parameters:
ke - KeyEvent object describing the user input

keyTyped

public void keyTyped(java.awt.event.KeyEvent ke)
not used
Specified by:
keyTyped in interface java.awt.event.KeyListener

keyReleased

public void keyReleased(java.awt.event.KeyEvent ke)
not used
Specified by:
keyReleased in interface java.awt.event.KeyListener

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent ae)
Handles game start button functions including starting game audio clip.
Specified by:
actionPerformed in interface java.awt.event.ActionListener
Parameters:
ae - ActionEvent object describing the user input

itemStateChanged

public void itemStateChanged(java.awt.event.ItemEvent ie)
Handles menu selections for game difficulty and spaceship style.
Specified by:
itemStateChanged in interface java.awt.event.ItemListener
Parameters:
ie - ItemEvent object describing the user input

stop

public void stop()
Stops Space Invaders game including all audio clips.
Overrides:
stop in class java.applet.Applet

getAppletInfo

public java.lang.String getAppletInfo()
Returns information about this applet.
Overrides:
getAppletInfo in class java.applet.Applet

getParameterInfo

public java.lang.String[][] getParameterInfo()
Returns information about the parameters that are settable in the HTML file.
Overrides:
getParameterInfo in class java.applet.Applet