Class AnimationGrid

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by AnimationGrid
All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener

public class AnimationGrid
extends javax.swing.JComponent
implements java.awt.event.ActionListener

The class SimpleAnimationApplet2 provides a generic framework for applets that do simple animations. This framework is appropriate for an animation that runs continuously as long as the applet is active. It is assumed that each time a new frame of the animation is to be drawn, that frame will be drawn completely from scratch. To use this framework, define a subclass of SimpleAnimationApplet2 and override the drawFrame method. This method is responsible for drawing one frame of the animation. If you want to customize the animation, with calls to setFrameCount() and setMillisecondsPerFrame() for example, you can define a "public void init()" method in your applet. Use the init() method to call the customization routines as well as to do any initialization required for your animation. Note that you should not override the standard applet routines start(), stop(), and destroy(), without calling the versions defined below in the SimpleAnimationApplet class. (Alternatively, instead of defining a subclass, you could copy this file, change its name, and edit it.) ^THAT'S WHAT WE DID!^ This applet is compatible with Java version 1.2 or later. It has the same functionality as an older program SimpleAnimationApplet.java, which was written in Java 1.0 and works with any version of Java. David Eck Department of Mathematics and Computer Science Hobart and William Smith Colleges Geneva, NY 14456 eck@hws.edu May 15, 2002

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
private  java.awt.Container container
           
private  long elapsedTime
           
private  boolean firstTime
           
private  int frameCount
           
private  int frameNumber
           
private  boolean gameOver
           
private  Grid grid
           
private  java.awt.image.BufferedImage gridImage
           
private  long oldElapsedTime
           
private  long startTime
           
private  javax.swing.Timer timer
           
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
AnimationGrid(java.awt.Container container, Grid grid)
          Constructs a new animation grid inside the container based on the objects in grid.
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent evt)
          Repaints the frame each time it changes.
private  void drawBomb(java.awt.Graphics g, int x, int y, Bomb bomb)
          Draws the bomb at grid cell (x,y).
private  void drawBox(java.awt.Graphics g, int x, int y, Box box)
          Draws Box box at location (x,y).
private  void drawFire(java.awt.Graphics g, int x, int y, Fire fire)
          Draws Fire fire at location (x,y).
 void drawFrame(java.awt.Graphics g)
          Is called each time the frame changes.
private  void drawGrid(java.awt.Graphics g)
          in charge of drawing the grid and all the elements in the grid.
private  void drawPlayer(java.awt.Graphics g, int x, int y, Player p)
          Draws Player p at location (x,y).
private  void drawPowerUp(java.awt.Graphics g, int x, int y, PowerUp powerUp)
          Draws PowerUp powerUp at location (x,y).
private  void drawWall(java.awt.Graphics g, int x, int y, Wall wall)
          Draws Wall wall at location (x,y).
 void gameOver()
          Draws the Game Over image.
 long getElapsedTime()
          Return the total number of milliseconds that the animation has been running (not including the time when the applet is suspended by the system)
 int getFrameNumber()
          Get the current frame number.
 int getHeight()
          Returns the height of the applet, in pixels.
 int getWidth()
          Returns the width of the applet, in pixels.
 void paintComponent(java.awt.Graphics g)
          Draws the components of the board.
 void setFrameCount(int max)
          If you want your animation to loop through a set of frames over and over, you should call this routine to set the frameCount to the number of frames in the animation.
 void setFrameNumber(int frameNumber)
          Set the current frame number.
 void setMillisecondsPerFrame(int time)
          Set the APPROXIMATE number of milliseconds to be used for each frame.
 void start()
          Called by the system when the applet is first started or restarted after being stopped.
 void stop()
          Called by the system to suspend the applet.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

gridImage

private java.awt.image.BufferedImage gridImage

container

private java.awt.Container container

grid

private Grid grid

frameNumber

private int frameNumber

frameCount

private int frameCount

startTime

private long startTime

oldElapsedTime

private long oldElapsedTime

elapsedTime

private long elapsedTime

timer

private javax.swing.Timer timer

firstTime

private boolean firstTime

gameOver

private boolean gameOver
Constructor Detail

AnimationGrid

public AnimationGrid(java.awt.Container container,
                     Grid grid)
Constructs a new animation grid inside the container based on the objects in grid.

Parameters:
container - a Container keeps track of the image draw order
grid - the Grid containing the objects to draw
Method Detail

drawFrame

public void drawFrame(java.awt.Graphics g)
Is called each time the frame changes. This routine should be overridden in any subclass of this class. It is responsible for drawing one frame of the animation. The frame is drawn to the graphics context g. The parameters width and height give the size of the drawing area. drawFrame() should begin by filling the drawing area with a background color (as is done in this version of drawFrame). It should then draw the contents of the frame. The routine can call getFrameNumber() to determine which frame it is supposed to draw. It can call getElapsedTime() to find out how long the animation has been running, in milliseconds. The functions getWidth() and getHeight() tell the applet's size. Note that this routine should not take a long time to execute! This version of this routine simple displays the frame number and elapsed time in each frame.

Parameters:
g - the Graphics component to use

drawGrid

private void drawGrid(java.awt.Graphics g)
in charge of drawing the grid and all the elements in the grid. Goes through and calls draw for each type of Obj in the grid.

Parameters:
g - the Graphics component to use

drawBomb

private void drawBomb(java.awt.Graphics g,
                      int x,
                      int y,
                      Bomb bomb)
Draws the bomb at grid cell (x,y).

Parameters:
g - the Graphics component to use
x - x-coordinate at which to draw the Wall
y - y-coordinate at which to draw the Wall
bomb - the Bomb to draw

drawPlayer

private void drawPlayer(java.awt.Graphics g,
                        int x,
                        int y,
                        Player p)
Draws Player p at location (x,y).

Parameters:
g - the Graphics component to use
x - x-coordinate at which to draw the Wall
y - x-coordinate at which to draw the Wall
p - the Player to draw

drawFire

private void drawFire(java.awt.Graphics g,
                      int x,
                      int y,
                      Fire fire)
Draws Fire fire at location (x,y).

Parameters:
g - the Graphics component to use
x - x-coordinate at which to draw the Wall
y - y-coordinate at which to draw the Wall
fire - the Fire to draw

drawPowerUp

private void drawPowerUp(java.awt.Graphics g,
                         int x,
                         int y,
                         PowerUp powerUp)
Draws PowerUp powerUp at location (x,y).

Parameters:
g - the Graphics component to use
x - x-coordinate at which to draw the Wall
y - y-coordinate at which to draw the Wall
powerUp - the PowerUp to draw

drawBox

private void drawBox(java.awt.Graphics g,
                     int x,
                     int y,
                     Box box)
Draws Box box at location (x,y).

Parameters:
g - the Graphics component to use
x - x-coordinate at which to draw the Wall
y - y-coordinate at which to draw the Wall
box - the Box to draw

drawWall

private void drawWall(java.awt.Graphics g,
                      int x,
                      int y,
                      Wall wall)
Draws Wall wall at location (x,y).

Parameters:
g - the Graphics component to use
x - x-coordinate at which to draw the Wall
y - y-coordinate at which to draw the Wall
wall - the Wall to draw

getFrameNumber

public int getFrameNumber()
Get the current frame number. The frame number will be incremented each time a new frame is to be drawn. The first frame number is 0. (If frameCount is greater than zero, and if frameNumber is greater than or equal to frameCount, then frameNumber returns to 0.)

Returns:
the frame number

setFrameNumber

public void setFrameNumber(int frameNumber)
Set the current frame number. This is the value returned by getFrameNumber(). Any value less than 0 is changed to 0.

Parameters:
frameNumber - frame number

getWidth

public int getWidth()
Returns the width of the applet, in pixels.

Overrides:
getWidth in class javax.swing.JComponent
Returns:
width of the applet, in pixels

getHeight

public int getHeight()
Returns the height of the applet, in pixels.

Overrides:
getHeight in class javax.swing.JComponent
Returns:
height of the applet, in pixels

getElapsedTime

public long getElapsedTime()
Return the total number of milliseconds that the animation has been running (not including the time when the applet is suspended by the system)

Returns:
total number of milliseconds the animation has been running

setFrameCount

public void setFrameCount(int max)
If you want your animation to loop through a set of frames over and over, you should call this routine to set the frameCount to the number of frames in the animation. Frames will be numbered from 0 to frameCount - 1. If you specify a value <= 0, the frameNumber will increase indefinitely without ever returning to zero. The default value of frameCount is -1, meaning that by default frameNumber does NOT loop.

Parameters:
max - frame number at which to loop the animation

setMillisecondsPerFrame

public void setMillisecondsPerFrame(int time)
Set the APPROXIMATE number of milliseconds to be used for each frame. For example, set time = 1000 if you want each frame to be displayed for about a second. The time is only approximate, and the actual display time will probably be a bit longer. The default value of 100 is reasonable. A value of 50 will give smoother animations on computers that are fast enough to draw than many frames per second. The value of time must be 10 or greater. If a value less than 10 is passed, it will be changed to 10. Do not put too much faith in the this value. It is only an approximation. If you want to know exactly how long the animation has been running, use getElapsedTime() instead of getFrameNumber().

Parameters:
time - approximate number of milliseconds to be used for each frame

paintComponent

public void paintComponent(java.awt.Graphics g)
Draws the components of the board.

Overrides:
paintComponent in class javax.swing.JComponent
Parameters:
g - Graphics component to use

start

public void start()
Called by the system when the applet is first started or restarted after being stopped. This routine starts or restarts the timer that runs the animation.


stop

public void stop()
Called by the system to suspend the applet. Stops the timer.


actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)
Repaints the frame each time it changes.

Specified by:
actionPerformed in interface java.awt.event.ActionListener

gameOver

public void gameOver()
Draws the Game Over image.