Class Asteroids

java.lang.Object
  |
  +--java.awt.Component
        |
        +--java.awt.Container
              |
              +--java.awt.Panel
                    |
                    +--java.applet.Applet
                          |
                          +--Asteroids

public class Asteroids
extends java.applet.Applet
implements java.lang.Runnable

Asteroids code can be used for an applet or an applciation. This works because an Applet is a panel.

See Also:
Serialized Form

Inner classes inherited from class java.awt.Component
java.awt.Component.AWTTreeLock
 
Field Summary
(package private)  AsteroidsGame asteroidsgame
          The game object that holds all of our sprites.
(package private) static java.awt.Color backgroundcolor
          Background color.
(package private) static java.applet.AudioClip crashSound
          Sound clip for ship hitting an asteroid.
(package private)  java.lang.String currentsoundfilename
           
(package private)  boolean detail
          A flag used to toggle more detail in the image.
(package private) static java.applet.AudioClip explosionSound
          Sound clip for bullet blowing up an asteroid, missile, or Ufo.
(package private) static java.applet.AudioClip fireSound
          Sound clip for ship shooting a bullet.
(package private)  java.awt.Font font
          The font to use onscreen.
(package private)  int fontHeight
           
(package private)  java.awt.FontMetrics fontmetric
           
(package private)  int fontWidth
           
(package private) static java.awt.Color foregroundcolor
          Foreground color.
(package private) static java.lang.Thread loadThread
          This thread is for loading the sounds.
(package private) static java.lang.Thread loopThread
          This thread is for driving the simulation updates.
(package private) static java.applet.AudioClip missileSound
          Sound clip for the missile moving.
(package private)  java.awt.Dimension offDimension
          Size of the offscreen buffer.
(package private)  java.awt.Graphics offGraphics
          Graphics of the offscreen buffer.
(package private)  java.awt.Image offImage
          Image of the offscreen buffer.
(package private) static Randomizer randomizer
          Use this to randomize everybody's settings.
(package private) static RealPixelConverter realpixelconverter
          Use this to convert between the real coordinates of the Sprite shape polygons and the pixel-sized coordinates used in the shapetransform by the draw function.
(package private) static java.applet.AudioClip saucerSound
          Sound clip for the Ufo moving.
(package private) static boolean soundflag
          A mute flag user can use to turn sound on and off.
(package private) static boolean soundsloaded
          Use this flag to signal if you successfully loaded the sounds.
(package private) static int START_PIXELHEIGHT
          Intended size of the start window.
(package private) static int START_PIXELWIDTH
          Intended size of the start window.
(package private) static java.applet.AudioClip thrustersSound
          Sound clip for the ship's thrusters firing.
private  double timestep
          Use this to time how long the updates take.
(package private) static boolean triedgettingsounds
          Leave this flag off until you've finished trying to load the sound.
(package private)  boolean trueapplet
          Flag for whether this is being run as a true applet or simply as an application.
(package private) static java.applet.AudioClip warpSound
          Sound clip for the hyperspace jump.
 
Fields inherited from class java.applet.Applet
serialVersionUID, stub
 
Fields inherited from class java.awt.Panel
base, nameCounter, serialVersionUID
 
Fields inherited from class java.awt.Container
component, containerListener, containerSerializedDataVersion, dispatcher, layoutMgr, maxSize, ncomponents, serialVersionUID
 
Fields inherited from class java.awt.Component
actionListenerK, adjustmentListenerK, appContext, assert, background, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, changeSupport, componentListener, componentListenerK, componentOrientation, componentSerializedDataVersion, containerListenerK, cursor, dropTarget, enabled, eventMask, focusListener, focusListenerK, font, foreground, hasFocus, height, incRate, inputMethodListener, inputMethodListenerK, isInc, isPacked, itemListenerK, keyListener, keyListenerK, LEFT_ALIGNMENT, locale, LOCK, minSize, mouseListener, mouseListenerK, mouseMotionListener, mouseMotionListenerK, name, nameExplicitlySet, newEventsOnly, ownedWindowK, parent, peer, peerFont, popups, prefSize, RIGHT_ALIGNMENT, serialVersionUID, textListenerK, TOP_ALIGNMENT, valid, visible, width, windowListenerK, x, y
 
Constructor Summary
Asteroids()
           
 
Method Summary
 java.lang.String getAppletInfo()
           
(package private)  double heightpixel()
          Accessor to the current pixel dimensions of the view.
 void init()
          Init does the work of a constructor: it creates a new AsteroidsGame.
 boolean isFocusTraversable()
          In order for the panel to be able to get focus so it can use its KeyListener, I have to do this overload.
 boolean keyDown(java.awt.Event e, int key)
          Call the ship.keyPressed method and let the ship use the arrow keys, the spacebar and the h key.
 boolean keyUp(java.awt.Event e, int key)
          Call the ship.keyPressed method and let the ship use the arrow keys, the spacebar and the h key.
 java.applet.AudioClip loadSound(java.lang.String soundname)
          This function tries to load a soundfile and return an audioclip.
 void loadSounds()
          This uses the loadSound(AudioClip, String) function which has pieces to comment in and out depending on the JDK being used.
 void paint(java.awt.Graphics g)
           
 void run()
          First use the loadThread to load the sounds, then set loadThread to null and use a while loop on loopthread to repeatedly update the sprites and call repaint.
(package private)  double scale()
          The conversion factor used in strectching or shrinking the real length to a pixel length.
 void setPixelWindow(java.awt.Dimension d)
          Mutator to tell the converter about a new pixel view window size.
 void start()
          Load the sounds by starting a loadThread, also start the main loopThread.
 void stop()
          Stop the loadThread and the loopThread by setting them to null.
 void update(java.awt.Graphics g)
           
(package private)  double widthpixel()
          Accessor to the current pixel dimensions of the view.
 
Methods inherited from class java.applet.Applet
destroy, getAppletContext, getAudioClip, getAudioClip, getCodeBase, getDocumentBase, getImage, getImage, getLocale, getParameter, getParameterInfo, 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, applyOrientation, countComponents, deliverEvent, dispatchEventImpl, dispatchEventToSelf, doLayout, eventEnabled, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents_NoClientCode, getComponents, getCursorTarget, getInsets, getLayout, getMaximumSize, getMinimumSize, getMouseEventTarget, getPreferredSize, getWindow, initIDs, insets, invalidate, invalidateTree, isAncestorOf, layout, lightweightPrint, list, list, locate, minimumSize, nextFocus, paintComponents, paramString, postProcessKeyEvent, postsOldMouseEvents, preferredSize, preProcessKeyEvent, print, printComponents, printOneComponent, processContainerEvent, processEvent, proxyEnableEvents, proxyRequestFocus, readObject, remove, remove, removeAll, removeContainerListener, removeNotify, setCursor, setFocusOwner, setFont, setLayout, transferFocus, updateCursor, validate, validateTree, writeObject
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addPropertyChangeListener, addPropertyChangeListener, areInputMethodsEnabled, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, getBackground, getBounds, getBounds, getColorModel, getComponentOrientation, getCursor, getDropTarget, getFont_NoClientCode, getFont, getFontMetrics, getForeground, getGraphics, getHeight, getInputContext, getInputMethodRequests, getIntrinsicCursor, getLocation, getLocation, 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, isLightweight, isOpaque, isShowing, isValid, isVisible, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, remove, removeComponentListener, removeFocusListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, reshape, setBackground, setBounds, setBounds, setComponentOrientation, 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

randomizer

static Randomizer randomizer
Use this to randomize everybody's settings. Seed it with the time in milliseconds so that each session is different.

backgroundcolor

static java.awt.Color backgroundcolor
Background color. Changed by 'b' key.

foregroundcolor

static java.awt.Color foregroundcolor
Foreground color. Changed by 'b' key.

loadThread

static java.lang.Thread loadThread
This thread is for loading the sounds. It seems to be giving me a lot of problems.

loopThread

static java.lang.Thread loopThread
This thread is for driving the simulation updates.

triedgettingsounds

static boolean triedgettingsounds
Leave this flag off until you've finished trying to load the sound. We can eliminate sounds, and the hanging, by making this true.

soundsloaded

static boolean soundsloaded
Use this flag to signal if you successfully loaded the sounds. At present my sounds aren't loading, so I leave this set to false.

crashSound

static java.applet.AudioClip crashSound
Sound clip for ship hitting an asteroid.

explosionSound

static java.applet.AudioClip explosionSound
Sound clip for bullet blowing up an asteroid, missile, or Ufo.

fireSound

static java.applet.AudioClip fireSound
Sound clip for ship shooting a bullet.

missileSound

static java.applet.AudioClip missileSound
Sound clip for the missile moving.

saucerSound

static java.applet.AudioClip saucerSound
Sound clip for the Ufo moving.

thrustersSound

static java.applet.AudioClip thrustersSound
Sound clip for the ship's thrusters firing.

warpSound

static java.applet.AudioClip warpSound
Sound clip for the hyperspace jump.

START_PIXELWIDTH

static final int START_PIXELWIDTH
Intended size of the start window. This should match the size of the image on the HTML page. It's used by the Asteroids Frame as well.

START_PIXELHEIGHT

static final int START_PIXELHEIGHT
Intended size of the start window. This should match the size of the image on the HTML page. It's used by the Asteroids Frame as well.

realpixelconverter

static RealPixelConverter realpixelconverter
Use this to convert between the real coordinates of the Sprite shape polygons and the pixel-sized coordinates used in the shapetransform by the draw function.

timestep

private double timestep
Use this to time how long the updates take. Our initial strategy is just to force it to stay constant. Later we might try adaptively changing it.

soundflag

static boolean soundflag
A mute flag user can use to turn sound on and off. We make it static, as there will only be one such flag per program, even if there were multiple windows.

detail

boolean detail
A flag used to toggle more detail in the image. Detail includes background stars and filling in the asteroids. Turn this off for greater speed.

asteroidsgame

AsteroidsGame asteroidsgame
The game object that holds all of our sprites.

font

java.awt.Font font
The font to use onscreen.

fontmetric

java.awt.FontMetrics fontmetric

fontWidth

int fontWidth

fontHeight

int fontHeight

currentsoundfilename

java.lang.String currentsoundfilename

offDimension

java.awt.Dimension offDimension
Size of the offscreen buffer.

offImage

java.awt.Image offImage
Image of the offscreen buffer.

offGraphics

java.awt.Graphics offGraphics
Graphics of the offscreen buffer.

trueapplet

boolean trueapplet
Flag for whether this is being run as a true applet or simply as an application. It makes a difference in the loadsounds method.
Constructor Detail

Asteroids

public Asteroids()
Method Detail

scale

double scale()
The conversion factor used in strectching or shrinking the real length to a pixel length.

widthpixel

double widthpixel()
Accessor to the current pixel dimensions of the view.

heightpixel

double heightpixel()
Accessor to the current pixel dimensions of the view.

setPixelWindow

public void setPixelWindow(java.awt.Dimension d)
Mutator to tell the converter about a new pixel view window size.

getAppletInfo

public java.lang.String getAppletInfo()
Overrides:
getAppletInfo in class java.applet.Applet

isFocusTraversable

public boolean isFocusTraversable()
In order for the panel to be able to get focus so it can use its KeyListener, I have to do this overload. (By default panels can't get focus.)
Overrides:
isFocusTraversable in class java.awt.Component

init

public void init()
Init does the work of a constructor: it creates a new AsteroidsGame.
Overrides:
init in class java.applet.Applet

start

public void start()
Load the sounds by starting a loadThread, also start the main loopThread.
Overrides:
start in class java.applet.Applet

stop

public void stop()
Stop the loadThread and the loopThread by setting them to null.
Overrides:
stop in class java.applet.Applet

loadSounds

public void loadSounds()
This uses the loadSound(AudioClip, String) function which has pieces to comment in and out depending on the JDK being used.

loadSound

public java.applet.AudioClip loadSound(java.lang.String soundname)
This function tries to load a soundfile and return an audioclip. While it's at work, it sets the currentsoundname to the soundname for reporting. If it fails, it writes a message to the console and also sets the Asteroids soundsloaded to false. The loadSound function has complications. (1) The method we use to load sounds for a true Asteroids applet object (that is, one initialized from within a web browser) won't work for a fake Asteroids applet object (that is, one initialized by a call to new Asteroids() from within the public main function). So we have a trueapplet switch. (2) The application sound-loadng method only works in Java 1.2, so this code is inside a JDK.version==2 block. (3) Java 1.0 can't load sounds from a jar file, so we need a separate version for this.

run

public void run()
First use the loadThread to load the sounds, then set loadThread to null and use a while loop on loopthread to repeatedly update the sprites and call repaint.
Specified by:
run in interface java.lang.Runnable

keyDown

public boolean keyDown(java.awt.Event e,
                       int key)
Call the ship.keyPressed method and let the ship use the arrow keys, the spacebar and the h key. Then process possible m, p, or s keys.
Overrides:
keyDown in class java.awt.Component

keyUp

public boolean keyUp(java.awt.Event e,
                     int key)
Call the ship.keyPressed method and let the ship use the arrow keys, the spacebar and the h key. Then process possible m, p, or s keys.
Overrides:
keyUp in class java.awt.Component

paint

public void paint(java.awt.Graphics g)
Overrides:
paint in class java.awt.Container

update

public void update(java.awt.Graphics g)
Overrides:
update in class java.awt.Container