ch.aplu.jgamegrid
Class GameGrid

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Canvas
          extended by ch.aplu.jgamegrid.GameGrid
All Implemented Interfaces:
GGActListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible
Direct Known Subclasses:
CardGame

public class GameGrid
extends java.awt.Canvas
implements GGActListener

Class to create a container where the actors live in. It is a two dimensional grid of cells. The size of cells can be specified (in pixel units = distance between two adjacent pixels) at GrameGrid's creation time, and is constant after creation. Simple scenarios may use large cells that entirely contain the representations of objects in a single cell. More elaborate scenarios may use smaller cells (down to a single pixel unit) to achieve fine-grained placement and smoother animation. The background of the game grid can be decorated with drawings or a background image.

The default constructor (parameterless) is used to create a canvas that can be embedded in your own frame window or applet. You may use a GUI builder because GameGrid is a Java bean. All other constructors embed the canvas in a simple frame window with or without a navigation bar containing 3 buttons (Run, Step, Reset) and a slider to select the simulation period.

GameGrid is derived from Canvas (a heavy weight component based on AWT) in order to use hardware based rendering enhancement (page flipping). In principle do not mix Swing and AWT components. For example you should not add a GameGrid in a JScrollPane (use the AWT container ScrollPane instead). (A GameGrid may be added to the content pane of a JFrame without harm.)

The cellSize is given in pixel units, e.g. the distance between adjacent pixels. The size in pixel units of the usable playground is width = nbHorzCells * cellSize horizontally and height = nbVertCells * cellSize vertically. Thus the playground contains nbHorzPixels = width + 1 pixels horizontally and nbVertPixels = height + 1 pixels vertically, with pixel indexes 0 <= i <= width (inclusive), 0 <= k <= height (inclusive) respectively.

For pixel accurate positioning be aware that an image that has the size m x n in pixel units contains m+1 pixels horizontally and n+1 pixels vertically. So the background image must have nbVertPixels horizontally and nbVerticalPixels vertically to fit exactly into the playground. (E.g. GameGrid(60, 50, 10) will need a background image with 601 x 501 pixels.)

To increase performance the automatic repainting of the graphics canvas is disabled. Repainting is done in every simulation cycle, when the window is moved or by calling refresh(). setWindowListener() registers a window listener that calls refresh() when the window is activated. The x- and y-coordinates for positioning actors are actually the cell index ranging from 0 <= x < nbHorzCells (exclusive) horizontally and 0 <= y < nbVertCells (exclusive) vertically. There image is automatically centered in the cell as accurate as possible.

The class design is inspired by the great Greenfoot programming environment (see www.greenfoot.org) and by an article about game programming in Java at www.cokeandcode.com/tutorials with thanks to the authors. The code is entirely rewritten and in my responsability.

A extended sound library is included that supports MP3.

Using a sound converter integrated in the native DLL soundtouch.dll (source from www.surina.net/soundtouch) you may change pitch and tempo independently. For the compilation you need the package ch.aplu.jaw and the native DLL soundtouch.dll must be found in the system path. It only works on Windows machines.

If a non-default constructor of GameGrid is used, all uncaught exceptions are handled by a GGExceptionHandler that shows the stack trace in a modal dialog box and terminates the application. This is useful for GUI-based applications where no console window is visible. To change this behavior, register a null GGExceptionHandler, override getStackTrace() or register your own GGExceptionHandler. For applets the Java standard exception handler is not modified because this would cause a security exception.

Key strokes may be reported by a GGKeyListener or by polling the keyboard using isKeyPressed() or kbhit(). Be aware that the game grid window must have the focus so that the keys are active. You may deny to give the focus to other components (e.g. to a text area or a second game grid in a GUI application) by calling setFocusable(false).

Methods that access/modify the internal data structure are made thread-safe. This does not mean that ALL methods are thread-safe.

Some library defaults of the GameGrid window can be modified by using a Java properties file gamegrid.properties. For more details consult gamegrid.properties file found in the distribution.

When the close button of the GameGrid window title bar is hit, System.exit(0) is executed that terminates the JVM, but you can modifiy this behavior by registering your own implementation of the ExitListener interface or by using the key ClosingMode in gamegrid.properties.

All Swing methods are executed by the Event Dispatch Thread (EDT), so all methods may be executed directly from any thread.

See Also:
Serialized Form

Nested Class Summary
static class GameGrid.ClosingMode
          Modes to determine what happens when the title bar close button is hit.
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.BaselineResizeBehavior
 
Field Summary
static GameGrid.ClosingMode AskOnClose
          ClosingMode AskOnClose.
 java.awt.Color bgColor
          The color of the background.
 java.lang.String bgImagePath
          Path of the background image.
 int bgImagePosX
          ULX of the background image with respect to playground.
 int bgImagePosY
          ULY of the background image with respect to playground.
static java.awt.Color BLACK
          Short for Color.BLACK.
static java.awt.Color BLUE
          Short for Color.BLUE.
 int cellSize
          Size of cells in pixels (square).
static java.awt.Color CYAN
          Short for Color.CYAN.
static java.awt.Color DARKGRAY
          Short for Color.DKGRAY.
static GameGrid.ClosingMode DisposeOnClose
          ClosingMode DisposeOnClose.
static java.awt.Color GRAY
          Short for Color.GRAY.
static java.awt.Color GREEN
          Short for Color.GREEN.
 java.awt.Color gridColor
          Color of the grid.
static java.awt.Color LIGHTGRAY
          Short for Color.LTGRAY.
static java.awt.Color MAGENTA
          Short for Color.MAGENTY.
static java.lang.Object monitor
          Object used for synchronizing access of methods accessing the sceen list.
 int nbHorzCells
          Number of horizonal cells.
static int nbRotSprites
          Number of rotated sprite images.
 int nbVertCells
          Number of vertical cells.
static GameGrid.ClosingMode NothingOnClose
          ClosingMode NothingOnClose.
static java.awt.Color PINK
          Short for Color.RED.
static java.awt.Color RED
          Short for Color.RED.
 int simulationPeriod
          Simulation period (in ms).
static GameGrid.ClosingMode TerminateOnClose
          ClosingMode TerminateOnClose.
static java.awt.Color TRANSPARENT
          Short for transparent color Color(0, 0, 0, 0) (black with alpha = 0).
static java.awt.Color WHITE
          Short for Color.WHITE.
static java.awt.Color YELLOW
          Short for Color.YELLOW.
 
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
GameGrid()
          Constructs the game playground with 10 by 10 cells (20 pixels wide).
GameGrid(boolean isNavigation)
          Constructs a game window including a playground of 10 by 10 cells (60 pixels wide) with possibly a navigation bar and a visible red grid but no background image.
GameGrid(int nbHorzCells, int nbVertCells)
          Constructs a game window with one pixel cell size including a playground with no navigation bar, no visible grid and no background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize)
          Constructs a game window including a playground with a navigation bar and no visible grid and no background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, boolean isNavigation)
          Constructs a game window including a playground with no visible grid and no background image, but possibly a navigation bar.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor)
          Constructs a game window including a playground with a navigation bar and a possibly a visible grid, but no background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor, boolean isNavigation)
          Constructs a game window including playground with possibly a navigation bar, possibly a visible grid and no background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor, java.lang.String bgImagePath)
          Constructs a game window including a playground with a navigation bar, possibly a visible grid and possibly a background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor, java.lang.String bgImagePath, boolean isNavigation)
          Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid and possibly a background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor, java.lang.String bgImagePath, boolean isNavigation, boolean undecorated)
          Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid, possibly a background image and possibly no decoration.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor, java.lang.String bgImagePath, boolean isNavigation, int nbRotSprites)
          Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid, and possibly a background image.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.awt.Color gridColor, java.lang.String bgImagePath, boolean isNavigation, int nbRotSprites, boolean undecorated)
          Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid, possibly a background image and and possibly no decoration.
GameGrid(int nbHorzCells, int nbVertCells, int cellSize, java.lang.String bgImagePath)
          Constructs a game window including a playground with a navigation bar and a possibly a background image, but no visible grid.
 
Method Summary
 void act()
          Empty method called in every simulation cycle after all actor act() calls.
 void actAll()
          Invokes all actor's act() methods in the order of the scene and draws the new game situation.
 void activate()
          Brings the game grid window to the front and request the focus.
 void addActListener(GGActListener listener)
          Registers the given GGActListener to get act() events.
 void addActor(Actor actor, Location location)
          Same as addActor(Actor actor, Location location, double direction) with direction = 0 (to east).
 void addActor(Actor actor, Location location, double direction)
          Adds a new actor at given starting position with given moving direction to the scene.
 void addActor(Actor actor, Location location, Location.CompassDirection compassDir)
          Same as addActor(Actor actor, Location location, double direction) with compass direction.
 void addActorNoRefresh(Actor actor, Location location)
          Same as addActor(Actor actor, Location location), but the game grid window is not refreshed automatically.
 void addActorNoRefresh(Actor actor, Location location, double direction)
          Same as addActor(Actor actor, Location location, double direction), but the game grid window is not refreshed automatically.
 void addExitListener(GGExitListener listener)
          Registers the given GGExitListener to get an event when the title bar close button is hit.
 void addKeyListener(GGKeyListener listener)
          Adds a GGKeyListener to get events when a key is pressed.
 void addKeyRepeatListener(GGKeyRepeatListener listener)
          Adds a GGKeyRepeatListener to get repeating events with default period (20 ms) when a key is pressed until the key is released.
 void addMouseListener(GGMouseListener listener, int mouseEventMask)
          Adds a GGMouseListener to get notifications from mouse events.
 void addNavigationListener(GGNavigationListener listener)
          Register a navigation listener to get notifications when the navigation panel is used.
 void addResetListener(GGResetListener listener)
          Registers the given GGResetListener to get events when the reset button is hit.
 void addStatusBar(int height)
          Adds a status window attached at the bottom of the game grid window (below the navigation bar, if available).
 void addWindowStateListener(GGWindowStateListener listener)
          Register a GGWindowStateListener that will report change of window location and iconification.
 GGTileMap createTileMap(int nbHorzTiles, int nbVertTiles, int tileWidth, int tileHeight)
          Creates/Replaces a TileMap with the specified number of horizontal and vertical tiles.
static void delay(long time)
          Delays execution for the given amount of time.
 void dispose()
          Stops the game thread, hides the game window, disposes the frame and calls Monitor.wakeUp().
static void disposeAll()
          Disposes the GameGrid instance.
 void doPause()
          Pauses the simulation cycling.
 void doReset()
          If still running, calls doPause() and restores actors to their initializing state.
 void doRun()
          Starts the simulation cycling.
 void doStep()
          Runs the the simulation loop once.
 java.util.ArrayList<Actor> getActors()
          Returns all actors that are part of the game grid.
 java.util.ArrayList<Actor> getActors(java.lang.Class clazz)
          Returns all actors of the specified class that are part of the game grid.
 java.util.ArrayList<Actor> getActorsAt(Location location)
          Returns all actors at the given location that are part of the game grid.
 java.util.ArrayList<Actor> getActorsAt(Location location, java.lang.Class clazz)
          Returns all actors of given type at given location that are part of the game grid.
 java.awt.Dimension getAreaSize()
          Returns the size of the occupied area (the frame window including navigation and status bar, if available).
 GGBackground getBg()
          Returns a reference to the background of the game grid.
 java.awt.Color getBgColor()
          Returns the color of the background.
 java.lang.String getBgImagePath()
          Returns to path to the background image file.
 java.awt.Point getBgImagePos()
          Returns the x-y-coordinates of the upper left vertex of the background image with respect to the playground pixel coordinates.
 int getBgImagePosX()
          Returns the x-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.
 int getBgImagePosY()
          Returns the y-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.
 int getCellSize()
          Returns the size of a cell (in pixels).
static GameGrid.ClosingMode getClosingMode()
          Returns the closing mode read from the gamegrid.properties file.
 java.util.ArrayList<Location> getDiagonalLocations(Location location, boolean up)
          Returns a list of all grid locations that are on the diagonal line through the given location.
 int getDoubleClickDelay()
          Returns the current double-click delay.
 java.util.ArrayList<Location> getEmptyLocations()
          Returns a list of all locations not occupied by actors.
 javax.swing.JFrame getFrame()
          Returns the JFrame reference of the surrounding window.
 java.awt.Color getGridColor()
          Returns the color of the grid.
 java.awt.image.BufferedImage getImage()
          Returns the BufferedImage of the current GameGrid window including the background and all actors.
 char getKeyChar()
          Returns the character of the last key pressed and removes it from the one-key buffer.
 int getKeyCharWait()
          Waits until a key is pressed and then returns the character of the last key pressed and removes it from the one-key buffer.
 int getKeyCode()
          Returns the key code of the last key pressed and removes it from the one-key buffer.
 int getKeyCodeWait()
          Waits until a key is pressed and then eeturns the key code of the last key pressed and removes it from the one-key buffer.
 int getKeyModifiers()
          Returns the key modifier of the last key pressed.
 java.lang.String getKeyModifiersText()
          Returns the key modifier as text of the last key pressed.
 java.util.ArrayList<Location> getLineLocations(Location loc1, Location loc2, boolean interjacent)
          Returns a list of cell grid locations whose cell centers are exactly on the the line through the centers of loc1 and loc1.
 Location getMouseLocation()
          Returns the cell location of the cell under the mouse pointer or null, if the game grid is not visible or obscured by another window.
 int getNbCycles()
          Returns the number of simulation cycles since last reset.
 int getNbHorzCells()
          Returns the horizontal number of cells.
 int getNbHorzPix()
          Returns the horizontal number of pixels of the playground.
 int getNbVertCells()
          Returns the vertical number of cells.
 int getNbVertPix()
          Returns the vertical number of pixels of the playground.
 int getNumberOfActors()
          Returns total number of actors in the scene.
 int getNumberOfActors(java.lang.Class clazz)
          Returns number of actors of specified class.
 int getNumberOfActorsAt(Location location)
          Returns number of actors at specified location.
 int getNumberOfActorsAt(Location location, java.lang.Class clazz)
          Returns number of actors of specified class at specified location.
 java.util.ArrayList<Location> getOccupiedLocations()
          Returns a list of all locations occupied by actors.
 Actor getOneActor(java.lang.Class clazz)
          Returns the actor of the specified class that is part of the game grid and is on top in the paint order.
 Actor getOneActorAt(Location location)
          Returns the actor at the specified location that is part of the game grid and is on top in the paint order.
 Actor getOneActorAt(Location location, java.lang.Class clazz)
          Returns the actor of the specified class at the specified location that is part of the game grid and is on top in the paint order.
 java.util.ArrayList<Actor> getPaintOrderList()
          Returns a list with actor references in the order they are painted.
 java.util.ArrayList<Actor> getPaintOrderList(java.lang.Class clazz)
          Returns a list with actor references of the given class in the order they are painted.
 GGPanel getPanel()
          Returns a reference to the GGPanel with current settings.
 GGPanel getPanel(double xmin, double xmax, double ymin, double ymax)
          Sets the coordinate system in GGPanel to given range and returns a reference to the GGPanel of the game grid.
 int getPgHeight()
          Returns the height (vertical size) of the playground in pixel units.
 int getPgWidth()
          Returns the width (horizontal size) of the playground in pixel units.
 java.awt.Point getPosition()
          Returns the the location in screen coordiantes of game grid window.
 java.util.ArrayList<java.lang.Integer> getPressedKeyCodes()
          Returns a list of the key codes of all keys currently pressed
 double getRandomDirection()
          Returns a random direction 0..360 degrees.
 Location getRandomEmptyLocation()
          Returns an empty random location within the game grid.
 Location getRandomLocation()
          Returns a random location within the game grid.
 int getSimulationPeriod()
          Returns the current simulation period.
 void getStackTrace(java.lang.String s)
          Implementation of the GGExceptionHandler's event method called when an uncaught exception is thrown.
 GGTileMap getTileMap()
          Returns the reference to the GGTileMap.
 java.util.ArrayList<Actor> getTouchedActors(java.lang.Class clazz)
          Returns a list with actor references of all actors of the given class whose touched area (of type IMAGE, RECTANGLE or CIRCLE) intersects with the current mouse cursor location.
static java.lang.String getVersion()
          Returns current version information.
 void hide()
          Hides the game grid, but does not destroy it.
 boolean isActorColliding(Actor a1, Actor a2)
          Checks if the two given actors are colliding.
 boolean isAtBorder(Location location)
          Returns true, if the given cell location is at the grid border.
static boolean isDisposed()
          Returns true if closing mode DisposeOnClose is selected and the close button was hit.
 boolean isEmpty(Location location)
          Returns true, if there is no actor at specified location.
 boolean isInGrid(Location location)
          Returns true, if the given cell location is within the grid.
 boolean isKeyPressed(int keyCode)
          Returns true if the key with the given key code is currently pressed.
 boolean isPaused()
          Returns true, if the game is paused
 boolean isRunning()
          Returns true, if the game is running.
 boolean isShown()
          Returns the state if visibilty of the game grid window.
 boolean isTileColliding(Actor a, Location location)
          Checks if the given actor and the tile at the given tile location are colliding.
 boolean isUndecorated()
          Returns true, if the window is undecorated (no title bar and no borders).
 boolean kbhit()
          Returns true, if a key was press since the last call to getKeyChar() or getKeyCode().
 void paint(java.awt.Graphics g)
          For internal use only (overrides Canvas.paint() to get paint notifications).
 SoundPlayer playLoop(GGSound sound)
          Play continously a distributed sound sample with maximum volume using the default sound device.
 SoundPlayer playLoop(java.lang.Object obj, GGSound sound)
          Play continously a distributed sound sample with maximum volume using the default sound device.
 SoundPlayer playLoop(java.lang.Object obj, java.lang.String audioPathname)
          Play continuously a sound sample from a JAR resource of the specified object with maximum volume using the default sound device.
 SoundPlayer playLoop(java.lang.String audioPathname)
          Play continuously a sound sample with maximum volume using the default sound device using the current class loader to load the resource.
 SoundPlayerExt playLoopExt(java.lang.Object obj, java.lang.String audioPathname)
          Same as playLoop(obj, audioPathname) but supports MP3.
 SoundPlayerExt playLoopExt(java.lang.String audioPathname)
          Same as playLoop(audioPathname) but supports MP3.
 SoundPlayer playSound(GGSound sound)
          Plays a distributed sound sample with maximum volume using the default sound device.
 SoundPlayer playSound(java.lang.Object obj, GGSound sound)
          Play a distributed sound sample with maximum volume using the default sound device.
 SoundPlayer playSound(java.lang.Object obj, java.lang.String audioPathname)
          Play a sound sample from a JAR resource of the specified object with maximum volume using the default sound device.
 SoundPlayer playSound(java.lang.String audioPathname)
          Play a sound sample from given audio file with maximum volume using the default sound device using the current class loader to load the resource.
 SoundPlayerExt playSoundExt(java.lang.Object obj, java.lang.String audioPathname)
          Same as playSound(obj, audioPathname) but supports MP3.
 SoundPlayerExt playSoundExt(java.lang.String audioPathname)
          Same as playSound(audioPathname) but supports MP3.
 void refresh()
          Refreshs the current game situation (repaint background, tiles, actors).
 boolean removeActor(Actor actor)
          Removes the given actor from the scene, so that act() is not called any more.
 int removeActors(java.lang.Class clazz)
          Removes all actors from the specified class, so that act() is not called any more.
 int removeActorsAt(Location location)
          Removes all actors at the specified location, so that act() is not called any more.
 int removeActorsAt(Location location, java.lang.Class clazz)
          Removes all actors from the specified class at the specified location, so that act() is not called any more.
 int removeAllActors()
          Removes all actors from the scene, so that act() is not called any more.
 void removeKeyListener(GGKeyListener listener)
          Removes a previously registered GGKeyListener.
 void removeKeyRepeatListener(GGKeyRepeatListener listener)
          Removes a previously registered GGKeyRepeatListener.
 boolean removeMouseListener(GGMouseListener listener)
          Removes the given mouse listener from the list of registered mouse listeners.
 void reset()
          Empty method called when the reset button is hit or doReset() is called.
 Actor reverseSceneOrder(java.util.ArrayList<Actor> actors)
          Reverses the order of the given actor list in the corresponding scene list.
 void setActEnabled(boolean enable)
          Enables/disables the simulation cycle momentarily.
 void setActOrder(java.lang.Class... classes)
          Set the act order of objects in the scene.
 void setActorOnBottom(Actor actor)
          Puts the given actor at first place in the corresponding scene list, in order to act last and to be drawn on the bottom of other actors of the same class.
 void setActorOnTop(Actor actor)
          Puts the given actor at last place in the corresponding scene list, in order to act first and to be drawn on top of other actors of the same class.
 void setBgColor(java.awt.Color color)
          Sets the color of the background.
 void setBgColor(int r, int g, int b)
          Sets the color of the background.
 void setBgImagePath(java.lang.String bgImagePath)
          Sets the path to the background image file.
 void setBgImagePos(java.awt.Point point)
          Sets the x-y-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.
 void setBgImagePosX(int x)
          Sets the x-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.
 void setBgImagePosY(int y)
          Sets the y-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.
 void setCellSize(int cellSize)
          Sets the size of a cell.
static void setClosingMode(GameGrid.ClosingMode closingMode)
          Sets the closing mode that determines what happens when the title bar close button is hit.
 void setDoubleClickDelay(int delay)
          Sets the time delay the system uses to distinct click and double-click mouse events.
 void setGridColor(java.awt.Color color)
          Sets the color of the grid and reconstructs the background.
 int setKeyRepeatPeriod(int keyRepeatPeriod)
          Sets the time between two successive key repeat events.
 void setMouseEnabled(boolean enabled)
          Enable/disable all mouse event callbacks.
 void setNbHorzCells(int nbHorzCells)
          Sets the horizontal number of cells.
 void setNbVertCells(int nbVertCells)
          Sets the vertical number of cells.
 void setPaintOrder(java.lang.Class... classes)
          Sets the paint order of objects in the game grid.
 void setPosition(int ulx, int uly)
          Move the location of the game grid window to the given screen position.
 void setSceneOrder(java.util.ArrayList<Actor> actors)
          Sets the act and paint order of the actors in the given list by rearraging their scene list to the order in the given list.
 void setSimulationPeriod(int millisec)
          Sets the period of the simulation loop.
 void setStatusText(java.lang.String text)
          Replaces the text in the status bar by the given text using the default font and text color of JOptionPane.
 void setStatusText(java.lang.String text, java.awt.Font font, java.awt.Color color)
          Replaces the text in the status bar by the given text using the given font and text color.
 void setTitle(java.lang.String text)
          Set the title in the window's title bar.
 Actor shiftSceneOrder(java.util.ArrayList<Actor> actors, boolean forward)
          Shifts (rolls) the actors of the given actor list in the corresponding scene list forward or backward.
 void show()
          Shows the game grid after initialisation or when hided.
 void showStatusBar(boolean show)
          Shows or hides the status bar.
 void stopGameThread()
          Stops the game thread to avoid any CPU consumption.
 Location toLocation(int x, int y)
          Returns the location (cell indices) of the cell where the point with given coordinates resides.
 Location toLocation(java.awt.Point pt)
          Returns the location (cell indices) of the cell where the given point resides.
 Location toLocationInGrid(int x, int y)
          Returns the location (cell indices) of the cell where the point with given coordinates resides.
 Location toLocationInGrid(java.awt.Point pt)
          Returns the location (cell indices) of the cell where the given point resides.
 java.awt.Point toPoint(Location location)
          Returns the x-y-coordinates of the center of the cell with given location (cell indices).
 
Methods inherited from class java.awt.Canvas
addNotify, createBufferStrategy, createBufferStrategy, getAccessibleContext, getBufferStrategy, update
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, bounds, checkImage, checkImage, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, deliverEvent, disable, dispatchEvent, doLayout, enable, enable, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAlignmentX, getAlignmentY, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentAt, getComponentAt, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeys, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getMaximumSize, getMinimumSize, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, invalidate, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusCycleRoot, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, layout, list, list, list, list, list, locate, location, lostFocus, minimumSize, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, preferredSize, prepareImage, prepareImage, print, printAll, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocusInWindow, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeys, setFocusTraversalKeysEnabled, setFont, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setSize, setSize, setVisible, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle, validate
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

TerminateOnClose

public static final GameGrid.ClosingMode TerminateOnClose
ClosingMode TerminateOnClose.


AskOnClose

public static final GameGrid.ClosingMode AskOnClose
ClosingMode AskOnClose.


DisposeOnClose

public static final GameGrid.ClosingMode DisposeOnClose
ClosingMode DisposeOnClose.


NothingOnClose

public static final GameGrid.ClosingMode NothingOnClose
ClosingMode NothingOnClose.


TRANSPARENT

public static final java.awt.Color TRANSPARENT
Short for transparent color Color(0, 0, 0, 0) (black with alpha = 0).


BLACK

public static final java.awt.Color BLACK
Short for Color.BLACK.


BLUE

public static final java.awt.Color BLUE
Short for Color.BLUE.


CYAN

public static final java.awt.Color CYAN
Short for Color.CYAN.


DARKGRAY

public static final java.awt.Color DARKGRAY
Short for Color.DKGRAY.


GRAY

public static final java.awt.Color GRAY
Short for Color.GRAY.


GREEN

public static final java.awt.Color GREEN
Short for Color.GREEN.


LIGHTGRAY

public static final java.awt.Color LIGHTGRAY
Short for Color.LTGRAY.


MAGENTA

public static final java.awt.Color MAGENTA
Short for Color.MAGENTY.


PINK

public static final java.awt.Color PINK
Short for Color.RED.


RED

public static final java.awt.Color RED
Short for Color.RED.


WHITE

public static final java.awt.Color WHITE
Short for Color.WHITE.


YELLOW

public static final java.awt.Color YELLOW
Short for Color.YELLOW.


gridColor

public java.awt.Color gridColor
Color of the grid. Default: Color.red Property for bean support.


nbHorzCells

public int nbHorzCells
Number of horizonal cells. Default: 10 Property for bean support.


nbVertCells

public int nbVertCells
Number of vertical cells. Default: 10 Property for bean support.


cellSize

public int cellSize
Size of cells in pixels (square). Default: 20 Property for bean support.


bgImagePath

public java.lang.String bgImagePath
Path of the background image. Default: null Property for bean support.


bgImagePosX

public int bgImagePosX
ULX of the background image with respect to playground. Default: 0 Property for bean support.


bgImagePosY

public int bgImagePosY
ULY of the background image with respect to playground. Default: 0 Property for bean support.


bgColor

public java.awt.Color bgColor
The color of the background. Default: black Property for bean support.


simulationPeriod

public int simulationPeriod
Simulation period (in ms). Default: 200 Property for bean support.


nbRotSprites

public static int nbRotSprites
Number of rotated sprite images. Default: 60 Property for bean support.


monitor

public static final java.lang.Object monitor
Object used for synchronizing access of methods accessing the sceen list.

Constructor Detail

GameGrid

public GameGrid()
Constructs the game playground with 10 by 10 cells (20 pixels wide). No grid is drawn (gridColor = null) and no surrounding frame window is created. Only to be used for a embedded playground in a user defined frame window or an applet.


GameGrid

public GameGrid(boolean isNavigation)
Constructs a game window including a playground of 10 by 10 cells (60 pixels wide) with possibly a navigation bar and a visible red grid but no background image.

Parameters:
isNavigation - if true, a navigation bar is shown

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize)
Constructs a game window including a playground with a navigation bar and no visible grid and no background image. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixelUnits) of the cell

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells)
Constructs a game window with one pixel cell size including a playground with no navigation bar, no visible grid and no background image.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                boolean isNavigation)
Constructs a game window including a playground with no visible grid and no background image, but possibly a navigation bar. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
isNavigation - if true, a navigation bar is shown

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.lang.String bgImagePath)
Constructs a game window including a playground with a navigation bar and a possibly a background image, but no visible grid. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
bgImagePath - the path or URL to a background image (if null, no background image)

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor)
Constructs a game window including a playground with a navigation bar and a possibly a visible grid, but no background image. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor,
                java.lang.String bgImagePath)
Constructs a game window including a playground with a navigation bar, possibly a visible grid and possibly a background image. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)
bgImagePath - the path or URL to a background image (if null, no background image)

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor,
                boolean isNavigation)
Constructs a game window including playground with possibly a navigation bar, possibly a visible grid and no background image. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)
isNavigation - if true, a navigation bar is shown

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor,
                java.lang.String bgImagePath,
                boolean isNavigation)
Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid and possibly a background image. The cellSize is given in pixel units, e.g. the distance between adjacent pixels.
From the given background image path the image file is searched in the following order:
- if application is packed into a jar archive, relative to the root of the jar archive
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory
- if filename starts with http://, from the given URL
- imagePath prefixed with _ and searched relative to the root of the jar archive (used for sprite library distribution)

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)
bgImagePath - the path to a background image (if null, no background image)
isNavigation - if true, a navigation bar is shown

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor,
                java.lang.String bgImagePath,
                boolean isNavigation,
                boolean undecorated)
Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid, possibly a background image and possibly no decoration. The cellSize is given in pixel units, e.g. the distance between adjacent pixels. The last parameter is the number of rotated sprite images (default: 60). See the Actor class for more information.
From the given background image path the image file is searched in the following order:
- if application is packed into a jar archive, relative to the root of the jar archive
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory
- if filename starts with http://, from the given URL
- imagePath prefixed with _ and searched relative to the root of the jar archive (used for sprite library distribution)

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)
bgImagePath - the path to a background image (if null, no background image)
isNavigation - if true, a navigation bar is shown
undecorated - if true, the window has no title bar and no borders

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor,
                java.lang.String bgImagePath,
                boolean isNavigation,
                int nbRotSprites)
Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid, and possibly a background image. The cellSize is given in pixel units, e.g. the distance between adjacent pixels. The last parameter is the number of rotated sprite images (default: 60). See the Actor class for more information.
From the given background image path the image file is searched in the following order:
- if application is packed into a jar archive, relative to the root of the jar archive
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory
- if filename starts with http://, from the given URL
- imagePath prefixed with _ and searched relative to the root of the jar archive (used for sprite library distribution)

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)
bgImagePath - the path to a background image (if null, no background image)
isNavigation - if true, a navigation bar is shown
nbRotSprites - the number of preloaded rotated sprite images for all actors (default: 60). Be aware that if you change this parameter, your actors must be created AFTER the GameGrid constructor terminates, because the actor's creation process uses this parameter

GameGrid

public GameGrid(int nbHorzCells,
                int nbVertCells,
                int cellSize,
                java.awt.Color gridColor,
                java.lang.String bgImagePath,
                boolean isNavigation,
                int nbRotSprites,
                boolean undecorated)
Constructs a game window including a playground with possibly a navigation bar, possibly a visible grid, possibly a background image and and possibly no decoration. (This is the most general constructor.) The cellSize is given in pixel units, e.g. the distance between adjacent pixels. The last parameter is the number of rotated sprite images (default: 60). See the Actor class for more information.
From the given background image path the image file is searched in the following order:
- if application is packed into a jar archive, relative to the root of the jar archive
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory
- if filename starts with http://, from the given URL
- imagePath prefixed with _ and searched relative to the root of the jar archive (used for sprite library distribution)

Parameters:
nbHorzCells - the number of horizontal cells
nbVertCells - the number of vertical cells
cellSize - the side length (in pixel units) of the cell
gridColor - the color of the grid (if null, no grid is shown)
bgImagePath - the path to a background image (if null, no background image)
isNavigation - if true, a navigation bar is shown
nbRotSprites - the number of preloaded rotated sprite images for all actors (default: 60). Be aware that if you change this parameter, your actors must be created AFTER the GameGrid constructor terminates, because the actor's creation process uses this parameter
undecorated - if true, the window has no title bar and no borders
See Also:
Actor
Method Detail

getBgImagePath

public java.lang.String getBgImagePath()
Returns to path to the background image file.

Returns:
Path to image file

setBgImagePath

public void setBgImagePath(java.lang.String bgImagePath)
Sets the path to the background image file.

Parameters:
bgImagePath - the path to the image file; if null, no background image is assumed

getBgImagePosX

public int getBgImagePosX()
Returns the x-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.

Returns:
the ULX of the background image

setBgImagePosX

public void setBgImagePosX(int x)
Sets the x-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates. The background is redrawn by calling GGBackground.clear().

Parameters:
x - the ULX of the background image

getBgImagePosY

public int getBgImagePosY()
Returns the y-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates.

Returns:
the ULY of the background image

setBgImagePosY

public void setBgImagePosY(int y)
Sets the y-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates. The background is redrawn by calling GGBackground.clear().

Parameters:
y - the ULY of the background image

getBgImagePos

public java.awt.Point getBgImagePos()
Returns the x-y-coordinates of the upper left vertex of the background image with respect to the playground pixel coordinates.

Returns:
the ULX/ULY of the background image

setBgImagePos

public void setBgImagePos(java.awt.Point point)
Sets the x-y-coordinate of the upper left vertex of the background image with respect to the playground pixel coordinates. The background is redrawn by calling GGBackground.clear().

Parameters:
point - the ULX/ULY of the background image

getBgColor

public java.awt.Color getBgColor()
Returns the color of the background.

Returns:
the background color

setBgColor

public void setBgColor(java.awt.Color color)
Sets the color of the background. The background is automatically redrawn using the given color.

Parameters:
color - the background color. Alpha channel ignored

setBgColor

public void setBgColor(int r,
                       int g,
                       int b)
Sets the color of the background. The background is automatically redrawn using the given color.

Parameters:
r - the red value of the color RGB
g - the green value of the color RGB
b - the blue value of the color RGB

getNbHorzCells

public int getNbHorzCells()
Returns the horizontal number of cells.

Returns:
the number of cells in horizontal direction

setNbHorzCells

public void setNbHorzCells(int nbHorzCells)
Sets the horizontal number of cells.

Parameters:
nbHorzCells - the number of cells in horizontal direction

getNbVertCells

public int getNbVertCells()
Returns the vertical number of cells.

Returns:
the number of cells in horizontal direction

setNbVertCells

public void setNbVertCells(int nbVertCells)
Sets the vertical number of cells.

Parameters:
nbVertCells - the number of cells in vertical direction

getGridColor

public java.awt.Color getGridColor()
Returns the color of the grid.

Returns:
the grid color; null, if no grid is defined

setGridColor

public void setGridColor(java.awt.Color color)
Sets the color of the grid and reconstructs the background.

Parameters:
color - the grid color; null, if no grid is desired

getNbHorzPix

public int getNbHorzPix()
Returns the horizontal number of pixels of the playground.

Returns:
the number of pixels of the playground in horizontal direction.

getNbVertPix

public int getNbVertPix()
Returns the vertical number of pixels of the playground.

Returns:
the number of pixels of the playground in vertical direction.

getPgWidth

public int getPgWidth()
Returns the width (horizontal size) of the playground in pixel units. The number of pixels in the horizontal direction is width + 1.

Returns:
the horizontal size of the playground in pixel units.

getPgHeight

public int getPgHeight()
Returns the height (vertical size) of the playground in pixel units. The number of pixels in the vertical direction is height + 1.

Returns:
the vertical size of the playground in pixel units.

getCellSize

public int getCellSize()
Returns the size of a cell (in pixels).

Returns:
the size of a cell

setCellSize

public void setCellSize(int cellSize)
Sets the size of a cell. Cells are squares.

Parameters:
cellSize - the length of the cell side in pixel units.

getBg

public GGBackground getBg()
Returns a reference to the background of the game grid.

Returns:
a reference to the GGBackground object

getPanel

public GGPanel getPanel()
Returns a reference to the GGPanel with current settings.

Returns:
a reference to the GGPanel object

getPanel

public GGPanel getPanel(double xmin,
                        double xmax,
                        double ymin,
                        double ymax)
Sets the coordinate system in GGPanel to given range and returns a reference to the GGPanel of the game grid.

Returns:
a reference to the GGPanel object

addActorNoRefresh

public void addActorNoRefresh(Actor actor,
                              Location location)
Same as addActor(Actor actor, Location location), but the game grid window is not refreshed automatically. This can be useful to avoid flickering when adding many actors at once.

Parameters:
actor - the actor to be added at the end of the scene list
location - the location of the actor (cell indices, value copy)

addActorNoRefresh

public void addActorNoRefresh(Actor actor,
                              Location location,
                              double direction)
Same as addActor(Actor actor, Location location, double direction), but the game grid window is not refreshed automatically.

Keep in mind that when using addActor(), the game grid is refreshed automatically, so that the action becomes immediately visible. The rendering of the game grid takes some time and it may be preferable to use addActorNoRefresh() if you add many actors at the same time and to avoid flickering. After that you may render the game grid manually by calling refresh(). (The game grid is also refreshed automatically in every simulation cycle.)

Parameters:
actor - the actor to be added at the end of the scene list
location - the location of the actor (cell indices, value copy)
direction - the direction (clockwise in degrees, 0 to east)

addActor

public void addActor(Actor actor,
                     Location location,
                     double direction)
Adds a new actor at given starting position with given moving direction to the scene. If the actor is already part of the scene, it must be removed from the scene before adding it again, because actors added to the scene should not be duplicated. The starting location and direction are saved and may be retrieved later. The actor reset notification is called in order an initialisation may be done.

More than one actor may be added at the same location and the location may be outside the visible game grid to hide the actor when added to the scene.

The image center is centered at the given location. For even image pixel width or height, the center is half pixel width to the left or resp. to the top. The default act and paint order is given by the order the actor are added, but all actors of the same class are bundled together. Actors added last will act and be painted first, but this default order may be modified. See setActOrder() and setPaintOrder() for more information.

After adding the actor to the scene, the game grid is refreshed automatically, so that the action becomes visible. The rendering of the game grid takes some time and it may be preferable to use addActorNoRefresh() if you add many actors at the same time and to avoid flickering. After that you may render the game grid manually by calling refresh(). (The game grid is also refreshed automatically in every simulation cycle.)

Parameters:
actor - the actor to be added at the end of the scene list
location - the location of the actor (cell indices, value copy)
direction - the direction (clockwise in degrees, 0 to east)

addActor

public void addActor(Actor actor,
                     Location location)
Same as addActor(Actor actor, Location location, double direction) with direction = 0 (to east).

Parameters:
actor - the actor to be added at the end of the scene list
location - the location of the actor (cell indices, value copy)

addActor

public void addActor(Actor actor,
                     Location location,
                     Location.CompassDirection compassDir)
Same as addActor(Actor actor, Location location, double direction) with compass direction.

Parameters:
actor - the actor to be added at the end of the scene list
location - the location of the actor (cell indices)
compassDir - the compass direction

getImage

public java.awt.image.BufferedImage getImage()
Returns the BufferedImage of the current GameGrid window including the background and all actors.

Returns:
the current GameGrid window

refresh

public void refresh()
Refreshs the current game situation (repaint background, tiles, actors). Refresh is automatically done in each simulation cycle. Manual refresh should be used with care, because it may interfere with the automatic refresh causing flickering.


actAll

public void actAll()
Invokes all actor's act() methods in the order of the scene and draws the new game situation. Corresponds to the next simulation act.


setActOrder

public void setActOrder(java.lang.Class... classes)
Set the act order of objects in the scene. Act order is specified by class: objects of one class will always act before objects of some other class. The default act order is determined by the order the actor's classes are added to the game grid: last entry will act first. The act order of objects of the same class (called a scene)is given by the default act order: last entry will act first. This order within a class can be changed with setActorOnTop(), setSceneOrder(), shiftSceneOrder(), reverseSceneOrder().
Objects of classes listed first in the specified parameter list will act before any objects of classes listed later.

Objects of classes not listed will act after all objects whose classes have been specified.

Parameters:
classes - the classes in desired act order

setPaintOrder

public void setPaintOrder(java.lang.Class... classes)
Sets the paint order of objects in the game grid. Paint order is specified by class: objects of one class will always be painted on top of objects of some other class. The default paint order is determined by the order the actor's classes are added to the game grid: last entry will be on top of first. The paint order of objects of the same class (called a scene) is given by the default paint order: last entry will be on top. This order can be changed with setActorOnTop(), setSceneOrder(), shiftSceneOrder, reverseSceneOrder().
Objects of classes listed first in the parameter list will appear on top of all objects of classes listed later.

Objects of classes not listed will appear below the objects whose classes have been specified.

At least one actor of the specified class has to be part of the scene, unless the paint order of this class is not modified.

Parameters:
classes - the classes in desired paint order

delay

public static void delay(long time)
Delays execution for the given amount of time.

Parameters:
time - the delay time (in ms)

doRun

public void doRun()
Starts the simulation cycling. Same as if the 'Run' button is pressed.


doPause

public void doPause()
Pauses the simulation cycling. Same as if the 'Pause' button is pressed.


doStep

public void doStep()
Runs the the simulation loop once. Same as if the 'Step' button is pressed.


doReset

public void doReset()
If still running, calls doPause() and restores actors to their initializing state. The initializing state includes: starting location, starting direction, starting sprite id (set before adding actor to game grid), no horizontal or vertical mirroring, collision enabled, but collision type not changed. All actor's and the GameGrid's reset() methods are called. Then the game grid is refreshed.

Same as if the 'Reset' button is pressed. This method is not called automatically when the game grid is created.


getFrame

public javax.swing.JFrame getFrame()
Returns the JFrame reference of the surrounding window.

Returns:
the JFrame reference; null, if no JFrame is used.

getSimulationPeriod

public int getSimulationPeriod()
Returns the current simulation period.

Returns:
the simulation period (in ms; 0, if slider knob is set to minimum period)

setSimulationPeriod

public void setSimulationPeriod(int millisec)
Sets the period of the simulation loop. If there is too much to do in one period, the period may be exceeded. The default simulaton period is 200 ms. If the navigation bar is shown, the slider knob is set to the new value.

Parameters:
millisec - the period of the simulation loop (in milliseconds)

kbhit

public boolean kbhit()
Returns true, if a key was press since the last call to getKeyChar() or getKeyCode(). The key is not removed from the one-key buffer. If a key is continously held down, after an initial delay, successive kbhit() = true are reported

Returns:
true, if a key was pressed and not yet consumed

getKeyChar

public char getKeyChar()
Returns the character of the last key pressed and removes it from the one-key buffer. If a second key is pressed while another key is held down the method returns the character of the second key.

Returns:
the charactor corresponding to the last key pressed, KeyEvent.CHAR_UNDEFINED if no key was pressed

getKeyCharWait

public int getKeyCharWait()
Waits until a key is pressed and then returns the character of the last key pressed and removes it from the one-key buffer. If a second key is pressed while another key is held down the method returns the character of the second key. The wait loop yields with delay(10). If the GameGrid is disposed, quits the wait loop and returns KeyEvent.CHAR_UNDEFINED.

Returns:
the charactor corresponding to the last key pressed, KeyEvent.CHAR_UNDEFINED if no key was pressed

getKeyCode

public int getKeyCode()
Returns the key code of the last key pressed and removes it from the one-key buffer. If a second key is pressed while another key is held down the method returns the key code of the second key.

Returns:
the key code corresponding to the last key pressed, KeyEvent.CHAR_UNDEFINED if no key was pressed

getKeyCodeWait

public int getKeyCodeWait()
Waits until a key is pressed and then eeturns the key code of the last key pressed and removes it from the one-key buffer. If a second key is pressed while another key is held down the method returns the key code of the second key. The wait loop yields with delay(10). If the GameGrid is disposed, quits the wait loop and returns KeyEvent.CHAR_UNDEFINED.

Returns:
the key code corresponding to the last key pressed, KeyEvent.CHAR_UNDEFINED if no key was pressed

getKeyModifiers

public int getKeyModifiers()
Returns the key modifier of the last key pressed. The key is not removed from the one-key buffer.

Returns:
the key modifier

getKeyModifiersText

public java.lang.String getKeyModifiersText()
Returns the key modifier as text of the last key pressed. The key is not removed from the one-key buffer.

Returns:
the key modifier as string

isKeyPressed

public boolean isKeyPressed(int keyCode)
Returns true if the key with the given key code is currently pressed. If more than one key is pressed at the same time, the method returns true for each of their key code.

Parameters:
keyCode - the code of the key you are interested in (a constant defined in java.awt.event.KeyCode).
Returns:
true, if the key is currently pressed; otherwise false

addKeyListener

public void addKeyListener(GGKeyListener listener)
Adds a GGKeyListener to get events when a key is pressed. More than one KeyListener may be registered. They are called in the order they are added. Be aware that if the notification method keyPressed() returns true, the key is "consumed" and no following KeyListener will be notified.

Parameters:
listener - the GGKeyListener to register

removeKeyListener

public void removeKeyListener(GGKeyListener listener)
Removes a previously registered GGKeyListener.

Parameters:
listener - the GGKeyListener to remove

isInGrid

public boolean isInGrid(Location location)
Returns true, if the given cell location is within the grid.

Returns:
true, if the cell coordinates are within the grid; otherwise false

isAtBorder

public boolean isAtBorder(Location location)
Returns true, if the given cell location is at the grid border. Be aware that in one pixel games, the near border location is only 1 pixel from the border.

Returns:
true, if the cell coordinates are at the grid border

getOccupiedLocations

public java.util.ArrayList<Location> getOccupiedLocations()
Returns a list of all locations occupied by actors. Hidden actors are considered to be present.

Returns:
an ArrayList of all occupied locations

getEmptyLocations

public java.util.ArrayList<Location> getEmptyLocations()
Returns a list of all locations not occupied by actors. Hidden actors are considered to be present.

Returns:
an ArrayList of all occupied locations

getActors

public java.util.ArrayList<Actor> getActors()
Returns all actors that are part of the game grid. The returned list is ordered in the current paint order: subsequent actors in the list are painted on top of preceding actors. Hidden actors are considered to be present.

Returns:
an ArrayList that contains all actors

getActorsAt

public java.util.ArrayList<Actor> getActorsAt(Location location,
                                              java.lang.Class clazz)
Returns all actors of given type at given location that are part of the game grid. The returned list is ordered in the current paint order: subsequent actors in the list are painted on top of preceding actors. The list is empty if the location is unoccupied. The actor is considered to have the type of its superclasses too. Hidden actors are considered to be present.

Parameters:
location - the location of the cell
clazz - class type of the actors to be returned (e.g. Fish.class), if clazz is null, all actors are returned
Returns:
an ArrayList of actors

getActorsAt

public java.util.ArrayList<Actor> getActorsAt(Location location)
Returns all actors at the given location that are part of the game grid. The returned list is ordered in the current paint order: subsequent actors in the list are painted on top of preceding actors. The list is empty if the location is unoccupied. Hidden actors are considered to be present.

Returns:
an ArrayList of all actors at the given location

getActors

public java.util.ArrayList<Actor> getActors(java.lang.Class clazz)
Returns all actors of the specified class that are part of the game grid. The actor is considered to have the type of its superclasses too. The returned list is ordered in the current paint order: subsequent actors in the list are painted on top of preceding actors Hidden actors are considered to be present.

Parameters:
clazz - the class of the actors to look for, if null all actors are returned
Returns:
an ArrayList that contains actors of the given class

getOneActorAt

public Actor getOneActorAt(Location location,
                           java.lang.Class clazz)
Returns the actor of the specified class at the specified location that is part of the game grid and is on top in the paint order. The actor is considered to have the type of its superclasses too. Hidden actors are considered to be present.

Parameters:
location - the location of the cell
clazz - the class of the actors to look for, if null all actors are considered
Returns:
the most visible actor or null, if no actor is found

getOneActor

public Actor getOneActor(java.lang.Class clazz)
Returns the actor of the specified class that is part of the game grid and is on top in the paint order. The actor is considered to have the type of its superclasses too. Hidden actors are considered to be present.

Parameters:
clazz - the class of the actors to look for, if null all actors are considered
Returns:
the most visible actor or null, if no actor is found

getOneActorAt

public Actor getOneActorAt(Location location)
Returns the actor at the specified location that is part of the game grid and is on top in the paint order. Hidden actors are considered to be present.

Parameters:
location - the location of the cell
Returns:
the most visible actor or null, if no actor is found

getNumberOfActors

public int getNumberOfActors()
Returns total number of actors in the scene. Hidden actors are considered to be present.

Returns:
the total number of actors

getNumberOfActorsAt

public int getNumberOfActorsAt(Location location)
Returns number of actors at specified location. Hidden actors are considered to be present.

Returns:
the number of actors

getNumberOfActorsAt

public int getNumberOfActorsAt(Location location,
                               java.lang.Class clazz)
Returns number of actors of specified class at specified location. The actor is considered to have the type of its superclasses too. Hidden actors are considered to be present.

Returns:
the number of actors

getNumberOfActors

public int getNumberOfActors(java.lang.Class clazz)
Returns number of actors of specified class. The actor is considered to have the type of its superclasses too. Hidden actors are considered to be present.

Returns:
the number of actors

isEmpty

public boolean isEmpty(Location location)
Returns true, if there is no actor at specified location. Hidden actors are considered to be present.

Returns:
true, if number of actors of all classes at specified location is zero

removeActor

public boolean removeActor(Actor actor)
Removes the given actor from the scene, so that act() is not called any more. The visiblity is turned off (spriteId = -1) and a registered mouse, mouse touch or key listener is removed.

Be aware that clicking the reset button or calling reset() will not bring the actor to life.
If you want to reuse the removed actor, you may add it again to the game grid (the sprite with id = 0 is shown). Any mouse, mouse touch or key listener must be registered again. Instead of removing the actor, call hide() to make him invisible and show() to display him again.

The buffered image resources will not be released until the actor reference runs out of scope. Because actors use a lot of heap space, you should be careful to remove actors and deassign their reference when they are no more used (e.g. moves out of the visible game grid).

Parameters:
actor - the actor to be removed
Returns:
true, if the specified actor is found and removed

removeAllActors

public int removeAllActors()
Removes all actors from the scene, so that act() is not called any more. The visiblity is turned off and any registered mouse, mouse touch or key listeners are disabled. Be aware that clicking the reset button or calling reset() will not bring the actors to life.

Returns:
the number of removed actors

removeActors

public int removeActors(java.lang.Class clazz)
Removes all actors from the specified class, so that act() is not called any more. The visiblity is turned off and any registered mouse, mouse touch or key listeners are disabled. Be aware that clicking the reset button or calling reset() will not bring the actor to life.

Parameters:
clazz - class of the actors to be removed, if null all actors are removed
Returns:
the number of removed actors

removeActorsAt

public int removeActorsAt(Location location,
                          java.lang.Class clazz)
Removes all actors from the specified class at the specified location, so that act() is not called any more. The visiblity is turned off and any registered mouse, mouse touch or key listeners are disabled. Be aware that clicking the reset button or calling reset() will not bring the actors to life.

Parameters:
location - the location of the cell
clazz - class of the actors to be removed, if null all actors are removed
Returns:
the number of removed actors

removeActorsAt

public int removeActorsAt(Location location)
Removes all actors at the specified location, so that act() is not called any more. The visiblity is turned off and any registered mouse, mouse touch or key listeners are disabled. Be aware that clicking the reset button or calling reset() will not bring the actors to life.

Parameters:
location - the location of the cell
Returns:
the number of removed actors

getRandomLocation

public Location getRandomLocation()
Returns a random location within the game grid.

Returns:
a random location

getRandomDirection

public double getRandomDirection()
Returns a random direction 0..360 degrees.

Returns:
a random direction

getRandomEmptyLocation

public Location getRandomEmptyLocation()
Returns an empty random location within the game grid. An empty location is where are no actors. Be aware that this may take some time in a big game grid that is densely populated.

Returns:
an empty random location or null, if there is no empty location

isRunning

public boolean isRunning()
Returns true, if the game is running.

Returns:
true, if the game runs; false, if not yet started or paused

isPaused

public boolean isPaused()
Returns true, if the game is paused

Returns:
true, if the game was started and then paused; false, if not yet started or running

isActorColliding

public boolean isActorColliding(Actor a1,
                                Actor a2)
Checks if the two given actors are colliding.

Parameters:
a1 - the first actor
a2 - the second actor
Returns:
true, if the two actors are currently colliding; otherwise false

isTileColliding

public boolean isTileColliding(Actor a,
                               Location location)
Checks if the given actor and the tile at the given tile location are colliding.

Parameters:
a - the actor to check for collision
location - the tile location
Returns:
true, if the actor and the tile are currently colliding; false, if no collision or tile map not created

playSound

public SoundPlayer playSound(java.lang.Object obj,
                             GGSound sound)
Play a distributed sound sample with maximum volume using the default sound device. Deprecated: Use playSound(GGSound sound) instead.

playSound(GGSound sound)

Parameters:
sound - the named sound sample from the GGSound enumeration
obj - object whose class loader is used to load the resource

playSound

public SoundPlayer playSound(GGSound sound)
Plays a distributed sound sample with maximum volume using the default sound device. Specify the sound indices defined as class constants. The methods returns immediately. More than one sound may be played at the same time. The return value may be used for calling methods of the SoundPlayer class, e.g. setVolume().
To start playing immediately, play a dummy sound before.

Parameters:
sound - the named sound sample from the GGSound enumeration

playLoop

public SoundPlayer playLoop(java.lang.Object obj,
                            GGSound sound)
Play continously a distributed sound sample with maximum volume using the default sound device. Deprecated: Use playLoop(GGSound sound) instead.

playLoop(GGSound sound)

Parameters:
sound - the named sound sample from the GGSound enumeration
obj - object whose class loader is used to load the resource

playLoop

public SoundPlayer playLoop(GGSound sound)
Play continously a distributed sound sample with maximum volume using the default sound device. Specify the sound indices defined as class constants. The methods returns immediately. More than one sound may be played at the same time. The return value may be used for calling methods of the SoundPlayer class, e.g. stop().
To start playing immediately, play a dummy sound before.

Parameters:
sound - the named sound sample from the GGSound enumeration

playSound

public SoundPlayer playSound(java.lang.Object obj,
                             java.lang.String audioPathname)
Play a sound sample from a JAR resource of the specified object with maximum volume using the default sound device. The methods returns immediately. More than one sound may be played at the same time. The return value may be used for calling methods of the SoundPlayer class, e.g. setVolume(). Only WAV files are supported. For MP3 use playSoundExt().
To start playing immediately, play a dummy sound before.
From the given audioPathname the sound file is searched in the following order:
- if application is packed into a jar archive, relative to the root of the jar archive
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory

Parameters:
obj - object whose class loader is used to load the resource
audioPathname - path to the sound file

playSound

public SoundPlayer playSound(java.lang.String audioPathname)
Play a sound sample from given audio file with maximum volume using the default sound device using the current class loader to load the resource. The methods returns immediately. More than one sound may be played at the same time. The return value may be used for calling methods of the SoundPlayer class, e.g. setVolume(). Only WAV files are supported. For MP3 use playSoundExt().
To start playing immediately, play a dummy sound before.
From the given audioPathname the sound file is searched in the following order:
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory

Parameters:
audioPathname - path to the sound file

playLoop

public SoundPlayer playLoop(java.lang.Object obj,
                            java.lang.String audioPathname)
Play continuously a sound sample from a JAR resource of the specified object with maximum volume using the default sound device. The methods returns immediately. More than one sound may be played at the same time. The return value may be used for calling methods of the SoundPlayer class, e.g. stop(). Only WAV files are supported. For MP3 use playLoopExt().
To start playing immediately, play a dummy sound before.
If the audio file is not found in the JAR resource, it is searched in the following order:
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory

Parameters:
obj - object whose class loader is used to load the resource
audioPathname - path to the sound file

playLoop

public SoundPlayer playLoop(java.lang.String audioPathname)
Play continuously a sound sample with maximum volume using the default sound device using the current class loader to load the resource. The methods returns immediately. More than one sound may be played at the same time. The return value may be used for calling methods of the SoundPlayer class, e.g. stop(). From the given audioPathname the sound file is searched in the following order:
To start playing immediately, play a dummy sound before.
- if application is packed into a jar archive, relative to the root of the jar archive
- relative to the directory <userhome>/gamegrid/
- relative or absolute to current application directory

Parameters:
audioPathname - path to the sound file

playSoundExt

public SoundPlayerExt playSoundExt(java.lang.Object obj,
                                   java.lang.String audioPathname)
Same as playSound(obj, audioPathname) but supports MP3. The following JARs (or later versions) must be included in the project: - jl1.0.1.jar
- mp3spi1.9.4.jar
- tritonius_share.jar
Download from www.javazoom.net or www.sourceforge.net.
Download of redistribution from www.aplu.ch/mp3support.


playSoundExt

public SoundPlayerExt playSoundExt(java.lang.String audioPathname)
Same as playSound(audioPathname) but supports MP3. The following JARs (or later versions) must be included in the project: - jl1.0.1.jar
- mp3spi1.9.4.jar
- tritonius_share.jar
Download from www.javazoom.net or www.sourceforge.net.
Download of redistribution from www.aplu.ch/mp3support.


playLoopExt

public SoundPlayerExt playLoopExt(java.lang.Object obj,
                                  java.lang.String audioPathname)
Same as playLoop(obj, audioPathname) but supports MP3. The following JARs (or later versions) must be included in the project: - jl1.0.1.jar
- mp3spi1.9.4.jar
- tritonius_share.jar
Download from www.javazoom.net or www.sourceforge.net.
Download of redistribution from www.aplu.ch/mp3support.


playLoopExt

public SoundPlayerExt playLoopExt(java.lang.String audioPathname)
Same as playLoop(audioPathname) but supports MP3. The following JARs (or later versions) must be included in the project: - jl1.0.1.jar
- mp3spi1.9.4.jar
- tritonius_share.jar
Download from www.javazoom.net or www.sourceforge.net.
Download of redistribution from www.aplu.ch/mp3support.


removeMouseListener

public boolean removeMouseListener(GGMouseListener listener)
Removes the given mouse listener from the list of registered mouse listeners.

Parameters:
listener - the listener to remove
Returns:
true, if the listener is successfully removed; false, if the listener is not part of the mouse listener list

addMouseListener

public void addMouseListener(GGMouseListener listener,
                             int mouseEventMask)
Adds a GGMouseListener to get notifications from mouse events. More than one GGMouseListener may be registered. They are called in the order they are added. Be aware that if the notification method mouseEvent() returns true, the event is "consumed" and no following GGMouseistener will be notified. Only the events defined as OR-combination in the specified mask are notified. If the mouse was disabled, it is enabled now.

Parameters:
listener - the GGMouseListener to register
mouseEventMask - an OR-combinaton of constants defined in class GGMouse

setMouseEnabled

public void setMouseEnabled(boolean enabled)
Enable/disable all mouse event callbacks.

Parameters:
enabled - if true, the registered callbacks are enabled; otherwise disabled

toPoint

public java.awt.Point toPoint(Location location)
Returns the x-y-coordinates of the center of the cell with given location (cell indices).

Parameters:
location - the indices of the cell
Returns:
the x-y-coordinates (as point) of the cell's center.

toLocation

public Location toLocation(java.awt.Point pt)
Returns the location (cell indices) of the cell where the given point resides. If the point is outside the grid, returns the location with cell indices outside the valid range.

Parameters:
pt - a point of pixels coordinates
Returns:
the location of the cell (cell indices) where the point resides

toLocation

public Location toLocation(int x,
                           int y)
Returns the location (cell indices) of the cell where the point with given coordinates resides. If the point is outside the grid, returns the location with cell indices outside the valid range.

Parameters:
x - x-coordinate (in pixels)
y - y-coordinate (in pixels)
Returns:
the location of the cell (cell indices) where the point resides

toLocationInGrid

public Location toLocationInGrid(java.awt.Point pt)
Returns the location (cell indices) of the cell where the given point resides. If the point is outside the grid, returns the closest location within the grid.

Parameters:
pt - a point of pixels coordinates
Returns:
the location of the cell (cell indices) where the point resides

toLocationInGrid

public Location toLocationInGrid(int x,
                                 int y)
Returns the location (cell indices) of the cell where the point with given coordinates resides. Despite in a strict sense the pixels of the right and bottom border belongs to cells outside the visible cells, the location of the cooresponding visible border cell is returned. If the point is outside the grid, the closest location within the grid is returned.

Parameters:
x - x-coordinate (in pixels)
y - y-coordinate (in pixels)
Returns:
the location of the cell (cell indices) where the point resides

setActorOnTop

public void setActorOnTop(Actor actor)
Puts the given actor at last place in the corresponding scene list, in order to act first and to be drawn on top of other actors of the same class. If you want to change the paint order of actors in different actor classes, use GameGrid.setPaintOrder().

Parameters:
actor - the actor to put on top
See Also:
setPaintOrder(Class... classes)

setActorOnBottom

public void setActorOnBottom(Actor actor)
Puts the given actor at first place in the corresponding scene list, in order to act last and to be drawn on the bottom of other actors of the same class. If you want to change the paint order of actors in different actor classes, use GameGrid.setPaintOrder().

Parameters:
actor - the actor to put on the bottom
See Also:
setPaintOrder(Class... classes)

shiftSceneOrder

public Actor shiftSceneOrder(java.util.ArrayList<Actor> actors,
                             boolean forward)
Shifts (rolls) the actors of the given actor list in the corresponding scene list forward or backward. When shifting forward, the last element is reinserted at the beginning, when shifting backward, the first element is reinserted at the end. The scene list determines the act and paint order (act and paint order from first to last element. Last element is shown on top.) All actors must have the same type (determined by the first element of the list).

Parameters:
actors - a list of actors to shift
forward - if true, shifts to the right (forward); otherwise shifts to the left (backward)
Returns:
the actor put at top; null, if none of the actors is part of the scene list

reverseSceneOrder

public Actor reverseSceneOrder(java.util.ArrayList<Actor> actors)
Reverses the order of the given actor list in the corresponding scene list. The scene list determines the act and paint order (act and paint order from first to last element. Last element is shown on top.) All actors must have the same type (determined by the first element of the list).

Parameters:
actors - a list of actors to shift
Returns:
the actor put at top; null, if none of the actors is part of the scene list

setSceneOrder

public void setSceneOrder(java.util.ArrayList<Actor> actors)
Sets the act and paint order of the actors in the given list by rearraging their scene list to the order in the given list. (Actors will act and painted in the order of their scene list. Actors painted later will appear on top of actors painted before.) All actors must have the same type (determined by the first element of the list). Duplicated actors in the given list are ignored. To change the act or paint order of the actors class, use setActOrder() or setPaintOrder().

Parameters:
actors - a list of actors to rearrange

getPaintOrderList

public java.util.ArrayList<Actor> getPaintOrderList(java.lang.Class clazz)
Returns a list with actor references of the given class in the order they are painted. (Actors painted later will appear on top of actors painted before.)

Parameters:
clazz - the class of actors included in the list; if null, all actors are included
Returns:
a list of actor references

getPaintOrderList

public java.util.ArrayList<Actor> getPaintOrderList()
Returns a list with actor references in the order they are painted. (Actors painted later will appear on top of actors painted before.)

Returns:
a list of actor references

getTouchedActors

public java.util.ArrayList<Actor> getTouchedActors(java.lang.Class clazz)
Returns a list with actor references of all actors of the given class whose touched area (of type IMAGE, RECTANGLE or CIRCLE) intersects with the current mouse cursor location.

Parameters:
clazz - the class of actors checked for a touch. If null, all actors are checked.
Returns:
a list of actor references. (Empty, if no actors are touched)

stopGameThread

public void stopGameThread()
Stops the game thread to avoid any CPU consumption. The game thread cannot be restarted without creating new GameGrid instance.

Normally doPause() is used to stop a simulation, but then some minor CPU time is still consumed. Clicking the close button in the GameGrid title bar stops the game thread automatically.


paint

public void paint(java.awt.Graphics g)
For internal use only (overrides Canvas.paint() to get paint notifications).

Overrides:
paint in class java.awt.Canvas

addActListener

public void addActListener(GGActListener listener)
Registers the given GGActListener to get act() events. More than one listener may be registered.

Parameters:
listener - the GGActListener to register

createTileMap

public GGTileMap createTileMap(int nbHorzTiles,
                               int nbVertTiles,
                               int tileWidth,
                               int tileHeight)
Creates/Replaces a TileMap with the specified number of horizontal and vertical tiles. All tiles are invisible (images set to null).

Be aware that tileWidth and tileHeight are given in number of pixels, but the size of the tiles in pixel units is (tileWidth-1) x (tileHeight-1). If the tile map already exists, it is replaced by the new one. To remove a tile map, replace it with a tile map with nbHorzTiles = 0 and nbVertTiles = 0.

Parameters:
nbHorzTiles - the number of horizontal tiles
nbVertTiles - the number of vertical tiles
tileWidth - the width of each tile (in pixels)
tileHeight - the height of each tile (in pixels)

getTileMap

public GGTileMap getTileMap()
Returns the reference to the GGTileMap.

Returns:
a reference to the GGTileMap; null, if it is not yet created

getNbCycles

public int getNbCycles()
Returns the number of simulation cycles since last reset.

Returns:
the number of simulation cycles

act

public void act()
Empty method called in every simulation cycle after all actor act() calls. Override to get your own notification.

Specified by:
act in interface GGActListener

reset

public void reset()
Empty method called when the reset button is hit or doReset() is called. Override to get your own notification.


show

public void show()
Shows the game grid after initialisation or when hided. Only valid if a GameGrid frame window was created. When show() returns, there is no garantee that the window is already shown, because it is made visible by the Event Dispatch Thread (EDT). An eventually attached status bar becomes visible too.

Overrides:
show in class java.awt.Component

hide

public void hide()
Hides the game grid, but does not destroy it. When hide() returns, there is no garantee that the window is already hidden, because is is made invisible by the Even Dispatch Thread (EDT). An eventually attached status bar is hidden too.

Overrides:
hide in class java.awt.Component

setTitle

public void setTitle(java.lang.String text)
Set the title in the window's title bar. The JFrame.setTitle() method is requested to be executed by the Event Dispatch Thread, so after setTitle() returns, there is no garantee that the window title is already set.

Parameters:
text - the text to display

addNavigationListener

public void addNavigationListener(GGNavigationListener listener)
Register a navigation listener to get notifications when the navigation panel is used. Only valid if a GameGrid frame window was created.

Parameters:
listener - the GGNavigationListener to register

addResetListener

public void addResetListener(GGResetListener listener)
Registers the given GGResetListener to get events when the reset button is hit. Only valid if a GameGrid frame window was created. More than one listener may be registered.

Parameters:
listener - the GGActListener to register

addExitListener

public void addExitListener(GGExitListener listener)
Registers the given GGExitListener to get an event when the title bar close button is hit. The closing behavior selected by setClosingMode() is ignored.

Parameters:
listener - the GGActListener to register

getVersion

public static java.lang.String getVersion()
Returns current version information.

Returns:
a string with the current version of the JGameGrid library

getStackTrace

public void getStackTrace(java.lang.String s)
Implementation of the GGExceptionHandler's event method called when an uncaught exception is thrown. The stack trace is shown in a JOptionPane. Override to implement your own exception handling.

Parameters:
s - the stack trace information

setPosition

public void setPosition(int ulx,
                        int uly)
Move the location of the game grid window to the given screen position. If there is no frame, nothing happens. The JFrame.setLocation() call is requested to be executed by the Event Dispatch Thread, so after setPosition() returns, there is no garantee that the window is already at the requested position.

Parameters:
ulx - the upper left vertex x-coordinate of the window in pixels
uly - the upper left vertex y-coordinate of the window in pixels

getPosition

public java.awt.Point getPosition()
Returns the the location in screen coordiantes of game grid window.

Returns:
the upper left vertex of the window in pixels; null, if there is no frame

isUndecorated

public boolean isUndecorated()
Returns true, if the window is undecorated (no title bar and no borders).

Returns:
true, if undecorated; otherwise false.

addWindowStateListener

public void addWindowStateListener(GGWindowStateListener listener)
Register a GGWindowStateListener that will report change of window location and iconification. Useful to snap another game grid window (button bar, etc). If there is no frame, nothing happens.

Parameters:
listener - the GGFrameStateListener to register

activate

public void activate()
Brings the game grid window to the front and request the focus. If there is no frame, nothing happens.


addStatusBar

public void addStatusBar(int height)
Adds a status window attached at the bottom of the game grid window (below the navigation bar, if available). The window has no title bar, but a one pixel black border and the same width as the game grid. If there is no frame window, nothing happens. The status window becomes visible, even if the game grid window is not shown. If a status window was added before, it is replaced by the new one.

Parameters:
height - the height in pixels of the status window

setStatusText

public void setStatusText(java.lang.String text)
Replaces the text in the status bar by the given text using the default font and text color of JOptionPane. The text is left-justified, vertically-centered and may be multi-line (lines separated by newline character). If there is no status bar or no frame window, nothing happens.

Parameters:
text - the new text to show in the status bar

setStatusText

public void setStatusText(java.lang.String text,
                          java.awt.Font font,
                          java.awt.Color color)
Replaces the text in the status bar by the given text using the given font and text color. The text is left-justified, vertically-centered and may be multi-line (lines separated by newline character). If there is no status bar or no frame window, nothing happens.

Parameters:
text - the new text to show in the status bar
font - the text font
color - the text color

showStatusBar

public void showStatusBar(boolean show)
Shows or hides the status bar. If there is no status bar or no frame window, nothing happens.

Parameters:
show - if true, a hidden status bar is shown even if the game grid window is hidden; if false, the status bar is hidden and not shown until showStatusBar(true) is called.

getAreaSize

public java.awt.Dimension getAreaSize()
Returns the size of the occupied area (the frame window including navigation and status bar, if available).

Returns:
the size of the occupied area in pixels; width = 0 and height = 0, if there is no frame window

getMouseLocation

public Location getMouseLocation()
Returns the cell location of the cell under the mouse pointer or null, if the game grid is not visible or obscured by another window. To return the pixel coordinates of the mouse pointer use GameGrid.getMousePosition().

Returns:
the cell location currently under the mouse pointer; null if no cell is under the pointer

getDiagonalLocations

public java.util.ArrayList<Location> getDiagonalLocations(Location location,
                                                          boolean up)
Returns a list of all grid locations that are on the diagonal line through the given location.

Parameters:
location - the location where the diagonal line is fixed
up - if true, the increasing diagonal line (y = x + b) is used; otherwise the decreasing diagonal line (y = -x + b) is used
Returns:
an array list containing the diagonal locations within the game grid (sorted by increasing x-coordinates)

getLineLocations

public java.util.ArrayList<Location> getLineLocations(Location loc1,
                                                      Location loc2,
                                                      boolean interjacent)
Returns a list of cell grid locations whose cell centers are exactly on the the line through the centers of loc1 and loc1. If interjacent is true, only locations between loc1 and loc2 are included. If the locations are the same and interjacent is false, the only location is included.

Parameters:
loc1 - the location of the first cell
loc2 - the location of the second cell
interjacent - if true, only location between loc1 and loc2 are included
Returns:
a list of cell whose centers are exactly (close within 10E-6) on the line through the two cell centers

setActEnabled

public void setActEnabled(boolean enable)
Enables/disables the simulation cycle momentarily. The navigation buttons are not modified.

Parameters:
enable - if true, a running simulation cycle is interrupted; otherwise a running simulation cycles is reenabled

setDoubleClickDelay

public void setDoubleClickDelay(int delay)
Sets the time delay the system uses to distinct click and double-click mouse events. If set to 0, this delay is ignored and both events are generated. If delay is less than zero, the value from the desktop property "awt.multiClickInterval" is used (normally 500 ms). Most systems ignores delays less than 200 ms (treated as 0). Keep in mind that when you perform a single click, the click event is only reported after the double-click time. If the double-click is not registered by the mouse event mask, the delay is ignored.

Parameters:
delay - the double click delay time in milliseconds used when a double-click event is registered

getDoubleClickDelay

public int getDoubleClickDelay()
Returns the current double-click delay.

Returns:
the double-click delay (in milliseconds). 0 if double-click delay is disabled

isShown

public boolean isShown()
Returns the state if visibilty of the game grid window. Because show()/hide() delegates turning on/off the visibility to the Event Dispatch Thread (EDT) and return immediatetly, this method can be used the check if the action is done.

Returns:
true, if the window is visible; otherwise false

addKeyRepeatListener

public void addKeyRepeatListener(GGKeyRepeatListener listener)
Adds a GGKeyRepeatListener to get repeating events with default period (20 ms) when a key is pressed until the key is released. More than one GGKeyRepeatListener may be registered. They are called in the order they are added.

Parameters:
listener - the GGKeyRepeatListener to register

removeKeyRepeatListener

public void removeKeyRepeatListener(GGKeyRepeatListener listener)
Removes a previously registered GGKeyRepeatListener.

Parameters:
listener - the GGKeyRepeatListener to remove

setKeyRepeatPeriod

public int setKeyRepeatPeriod(int keyRepeatPeriod)
Sets the time between two successive key repeat events.

Parameters:
keyRepeatPeriod - the new key repeat period (in ms)
Returns:
the current key repeat period

getPressedKeyCodes

public java.util.ArrayList<java.lang.Integer> getPressedKeyCodes()
Returns a list of the key codes of all keys currently pressed

Returns:
a list of key codes of keys currently pressed

setClosingMode

public static void setClosingMode(GameGrid.ClosingMode closingMode)
Sets the closing mode that determines what happens when the title bar close button is hit. If a GGExitListener is registered, the closing behavior is determined by the notifyExit() callback. The given value overwrites the value read from the gamegrid.properties file.

Parameters:
closingMode - one of the items in enum GameGrid.ClosingMode

getClosingMode

public static GameGrid.ClosingMode getClosingMode()
Returns the closing mode read from the gamegrid.properties file.

Returns:
one of the items in enum ClosingMode

isDisposed

public static boolean isDisposed()
Returns true if closing mode DisposeOnClose is selected and the close button was hit.

Returns:
true, if the GameGrid window was disposed or released; otherwise false

dispose

public void dispose()
Stops the game thread, hides the game window, disposes the frame and calls Monitor.wakeUp().


disposeAll

public static void disposeAll()
Disposes the GameGrid instance.