jgame
Class JGEngine

java.lang.Object
  extended byjava.awt.Component
      extended byjava.awt.Container
          extended byjava.awt.Panel
              extended byjava.applet.Applet
                  extended byjgame.JGEngine
All Implemented Interfaces:
javax.accessibility.Accessible, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable

public abstract class JGEngine
extends java.applet.Applet

Contains the main functionality of the game engine. Subclass it to write your own game. The engine can be run as both an applet and an application. To run as an application, have your main() construct an instance of your subclass. Then call initEngine(), which will open a window, and initialise. To run as an applet, ensure that your subclass has a parameterless constructor which enables the applet viewer to create it as an applet. Within this constructor, you call initEngineApplet() to initialise.

Upon initialisation, the engine will create a new thread in which all game action will run. First it calls initGame() in your subclass. Here, you can define any initialisation code, such as variable initialisation and image loading. Then, the engine will start producing frames. Each frame it will call doFrame() in your subclass, where you can call engine functions to move the game objects, check collisions, and everything else you want to do in a frame. Then, it will draw the current frame on the screen, after which it calls paintFrame(), where you can do any customised drawing on the frame, such as status messages. The engine enables you to specify states that the game may be in, say, the title screen state or the in-game state. When a state is set, the engine will try to call additional doFramestate() and paintFramestate() methods, where you can handle the game action for that specific state. Multple states may be set at once, resulting in multiple method calls each frame.

The engine manages a list of sprite objects, and a matrix of equal-sized tiles. Its primary way to draw graphics is images. Images may be loaded from Gifs, JPegs, or PNGs (PNGs not in java 1.2), which may contain either single images, or regularly spaced arrays or matrices of images (i.e. sprite sheets, we will call them image maps). An image is identified by a unique name, and is defined bythe image file it comes from, the index within that file in case the file is an image map, and any flip and rotate actions that are to be be done on the file image to arrive at the final image. Animations may be defined in terms of sequences of images. Image maps, images, and animations can be defined by calling resp. defineImageMap, defineImage, or defineAnimation, or the definitions can be loaded from a text-file table file using defineImages().

Objects are of the class JGObject; see this class for more information. Objects are identified within the engine by unique String identifiers. Creating a new object with the same identifier as an old object will replace the old one. Objects are drawn on the screen in lexical order. The main methods for handling objects are moveObjects(), checkCollision(), and checkBGCollision().

Tiles can be used to define a background that the sprite objects can interact with, using a set of shorthands for reading, writing, and colliding with tiles. Tiles are uniquely identified by a short string (1-4 characters). Tiles may be transparent; a decorative background image can be displayed behind the tiles.

Collision is done by assigning collision IDs (cids) to both objects and tiles. A cid is basically a bit string (usually, one allocates 1 bit per basic object or tile type). Collision is done by specifying that a certain set of object types should be notified of collision with a certain set of object or tile types. Such a set is specified by a bit mask, which matches a cid when cid&mask != 0. JGObject defines collision methods (hit and hit_bg)which can then be implemented to handle the collisions. Objects have two bounding boxes: one for object-object collision (the "regular" bounding box), and one for object-tile collision (the tile bounding box). The two bounding boxes are defined by the image (typically, you want these bounding boxes to approximate the shape of each individual image). Both can be overridden separately. Often, you want to set the tile bbox to a constant value, such as equal to the size of 1 tile.

The engine supports transparent on the fly scaling. This means that you can code your game for a specific "virtual" screen size, and have it scale to any other screen size by simply supplying the desired "real" screen size at startup. Applets will scale to the size as given by the width and height fields in the HTML code. The scale factor will in no way affect the behaviour of the game (except performance-wise), but the graphics may look a bit blocky or jaggy, as the engine uses a simple scaling algorithm to ensure good performance. Currently, the engine supports keyboard input only. Mouse input will be added later. The state of the keyboard is maintained in a keymap, which can be read by getKey().

See Also:
Serialized Form

Field Summary
static int KeyAlt
           
static int KeyCtrl
           
static int KeyDown
           
static int KeyLeft
           
static int KeyRight
           
static int KeyShift
           
static int KeyUp
           
 
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
JGEngine()
          Construct engine, but do not initialise it yet.
 
Method Summary
 void addGameState(java.lang.String state)
          Add the given state to the game's existing state.
 boolean and(int value, int mask)
          A Boolean AND shorthand to use for collision; returns (value&mask) != 0.
 void checkBGCollision(int tileid, int objid)
          Calls all bg colliders of objects that match objid that collide with tiles that match tileid.
 int checkBGCollision(java.awt.Rectangle r)
          Check collision of tiles within given rectangle, return the OR of all cids found.
 void checkCollision(int srcid, int dstid)
          Calls all colliders of objects that match dstid that collide with objects that match srcid.
 void clearBG(java.lang.String filltilename)
          Fill the background with the given tile.
 void clearGameState()
          Set the game's main state to none.
 void clearKey(int key)
          Set the key status of a key to released.
 int countObjects(java.lang.String prefix, int cidmask)
          Count how many objects there are with both the given name prefix and have colid&cidmask != 0.
 void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed)
           
 void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed, int increment)
           
 void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed, int increment, boolean pingpong)
           
 void defineImage(java.lang.String imgname, java.lang.String tilename, int collisionid, java.lang.String imgfile, boolean is_transparent, java.lang.String img_op, int top, int left, int width, int height)
          Define new sprite/tile image.
 void defineImage(java.lang.String imgname, java.lang.String tilename, int collisionid, java.lang.String imgmap, int mapidx, boolean is_transparent, java.lang.String img_op, int top, int left, int width, int height)
          Define new image from map.
 void defineImageMap(java.lang.String mapname, java.lang.String imgurl, int xofs, int yofs, int tilex, int tiley, int skipx, int skipy)
          Define image map, a large image containing a number of smaller images to use for sprites or fonts.
 void defineImages(java.lang.String filename)
          Load a set of imagemap, image, and animation definitions from a file.
 void destroy()
          Destroy function for deinitialising the engine properly.
 void doFrame()
          Is called every frame.
 void drawImage(int x, int y, java.lang.String imgname)
          Draw image with given ID
 void drawImageString(java.lang.String string, int x, int y, java.lang.String imgmap, int char_offset, int spacing)
          Draws a single line of text using an image map as font; text alignment is always top left.
 void drawString(java.lang.String str, int x, int y, int align)
          draws string so that (x,y) is the topleft coordinate (align=-1), the top middle coordinate (align=0), or the top right coordinate (align=1).
 boolean existsObject(java.lang.String index)
          Get object if it exists, null if not.
 int getBGTileCid(int xidx, int yidx)
          Get cid of tile at given tile index position.
 int getBGTileCid(java.awt.Point center, int xofs, int yofs)
          Get the tile cid of the point that is (xofs,yofs) from the tile index coordinate center.
 int getBGTileCid(java.awt.Rectangle tiler)
          Get the OR of the cids at the tile indexes given by tiler
 int getBGTileCidAtCoord(double x, double y)
          Get collision Id of the tile at given pixel coordinates.
 java.lang.String getBGTileString(int xidx, int yidx)
          get string id of tile at given index position
 java.lang.String getBGTileString(java.awt.Point center, int xofs, int yofs)
          Get the tile string of the point that is (xofs,yofs) from the tile index coordinate center.
 java.lang.String getBGTileStringAtCoord(double x, double y)
          Get collision Id of the tile at given pixel coordinates.
 java.awt.Graphics getBufferGraphics()
          Get the graphics context for drawing on the buffer during a paintFrame().
 java.net.URL getFullPath(java.lang.String subpath)
          Add base URL of the current environment to the given file path; this will result in a URL that both applications and applets can load from.
 java.awt.Rectangle getImageBBox(java.lang.String imgname)
          Gets the collision bounding box of an image.
 boolean getKey(int key)
          Get the key status of the given key.
 double getMinScaleFactor()
          Get minimum of the x and y scale factors
 JGObject getObject(java.lang.String index)
          Get object if it exists, null if not.
 java.awt.Point getTileIndex(double x, double y)
          Get tile index of the tile the coordinate is on.
 java.awt.Rectangle getTileSpan(java.awt.Rectangle r)
          Get tile index range of all tiles overlapping given rectangle of pixel coordinates.
 double getXScaleFactor()
          Get scale factor of real screen width wrt virtual screen width
 double getYScaleFactor()
          Get scale factor of real screen height wrt virtual screen height
 boolean inGameState(java.lang.String state)
          Check if game is in given state.
 void init()
          Initialise engine; don't call directly.
 void initEngine(int nrtilesx, int nrtilesy, int tilex, int tiley, java.awt.Color fgcolor, java.awt.Color bgcolor, java.awt.Font msgfont, int width, int height)
          Init engine as application.
 void initEngineApplet(int nrtilesx, int nrtilesy, int tilex, int tiley, java.awt.Color fgcolor, java.awt.Color bgcolor, java.awt.Font msgfont)
          Init engine as applet; call this in your engine constructor.
abstract  void initGame()
          Override to define your own initialisations.
 boolean isXAligned(double x, double margin)
          Returns true if x falls within margin of the tile snap grid.
 boolean isYAligned(double y, double margin)
          Returns true if y falls within margin of the tile snap grid.
 void moveObjects()
          Call all move() methods of all registered objects.
 void moveObjects(java.lang.String prefix, int cidmask)
          Call the move() methods of those objects matching the given name prefix and collision id mask.
 void paintFrame()
          Is called when the engine's default screen painting is finished, and custom painting actions may be carried out.
 int pfHeight()
          Get the virtual height in pixels (not the scaled screen height)
 int pfTileHeight()
          Get the tile height in (virtual) pixels.
 int pfTilesX()
          Get the number of tiles in X direction
 int pfTilesY()
          Get the number of tiles in Y direction
 int pfTileWidth()
          Get the tile width in (virtual) pixels.
 int pfWidth()
          Get the virtual width in pixels (not the scaled screen width)
 double random(double min, double max)
           
 double random(double min, double max, double interval)
           
 void removeObjects(java.lang.String prefix, int cidmask)
          Remove all objects which have the given name prefix and/or match the given cidmask.
 void setBGColor(java.awt.Color bgcol)
          Set global background colour.
 void setBGImage(java.lang.String bgimg)
          Set image to display behind transparent tiles.
 void setBGTile(int x, int y, java.lang.String tilename)
          Define a single tile.
 void setBGTiles(int xofs, int yofs, java.lang.String[] tilemap)
          Set a block of tiles according to the chars in the nxm char array tilemap.
 void setBGTilesMulti(int xofs, int yofs, java.lang.String[] tilemap)
          Set a block of tiles according to the tile names in the nxm element array tilemap.
static void setBoundingBoxDebug(boolean enabled)
           
 void setColor(java.awt.Color fgcol)
          Set global foreground colour, used for printing text and status messages.
 void setColorsFont(java.awt.Color fgcolor, java.awt.Color bgcolor, java.awt.Font msgfont)
          Set foreground and background colour and font in one go; passing null means ignore.
 void setFont(java.awt.Font msgfont)
          Set font for printing text and status messages.
 void setFrameRate(double fps, double maxframeskip)
          Set frame rate in frames per second, and maximum number of frames that may be skipped before displaying a frame again.
 void setGameState(java.lang.String state)
          Set the game's main state.
 void setKey(int key)
          Set the key status of a key to pressed.
 void snapToGrid(java.awt.Point p, int gridsnapx, int gridsnapy)
          Snap p to grid in case p is close enough to the grid lines.
 double snapToGridX(double x, double gridsnapx)
          Snap to grid, double version.
 double snapToGridY(double y, double gridsnapy)
          Snap to grid, double version.
 void start()
          Signal that the engine should start running
 void stop()
          signal that the engine should stop running and wait
 
Methods inherited from class java.applet.Applet
getAccessibleContext, getAppletContext, getAppletInfo, getAudioClip, getAudioClip, getCodeBase, getDocumentBase, getImage, getImage, getLocale, getParameter, getParameterInfo, isActive, newAudioClip, play, play, resize, resize, setStub, showStatus
 
Methods inherited from class java.awt.Panel
addNotify
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getListeners, getMaximumSize, getMinimumSize, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, remove, remove, removeAll, removeContainerListener, removeNotify, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, update, validate
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, dispatchEvent, enable, enable, enableInputMethods, getBackground, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isOpaque, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocusInWindow, reshape, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

KeyUp

public static final int KeyUp
See Also:
Constant Field Values

KeyDown

public static final int KeyDown
See Also:
Constant Field Values

KeyLeft

public static final int KeyLeft
See Also:
Constant Field Values

KeyRight

public static final int KeyRight
See Also:
Constant Field Values

KeyShift

public static final int KeyShift
See Also:
Constant Field Values

KeyCtrl

public static final int KeyCtrl
See Also:
Constant Field Values

KeyAlt

public static final int KeyAlt
See Also:
Constant Field Values
Constructor Detail

JGEngine

public JGEngine()
Construct engine, but do not initialise it yet. Call initEngine or initEngineApplet to initialise the engine.

Method Detail

setBoundingBoxDebug

public static void setBoundingBoxDebug(boolean enabled)

defineAnimation

public void defineAnimation(java.lang.String id,
                            java.lang.String[] frames,
                            double speed)

defineAnimation

public void defineAnimation(java.lang.String id,
                            java.lang.String[] frames,
                            double speed,
                            int increment)

defineAnimation

public void defineAnimation(java.lang.String id,
                            java.lang.String[] frames,
                            double speed,
                            int increment,
                            boolean pingpong)

initEngineApplet

public void initEngineApplet(int nrtilesx,
                             int nrtilesy,
                             int tilex,
                             int tiley,
                             java.awt.Color fgcolor,
                             java.awt.Color bgcolor,
                             java.awt.Font msgfont)
Init engine as applet; call this in your engine constructor. Applet init() will start the game.

Parameters:
nrtilesx - nr of tiles horizontally
nrtilesy - nr of tiles vertically
tilex - width of one tile
tiley - height of one tile
fgcolor - pen/text colour, null for default white
bgcolor - background colour, null for default black
msgfont - font for messages and text drawing, null for default

initEngine

public void initEngine(int nrtilesx,
                       int nrtilesy,
                       int tilex,
                       int tiley,
                       java.awt.Color fgcolor,
                       java.awt.Color bgcolor,
                       java.awt.Font msgfont,
                       int width,
                       int height)
Init engine as application.

Parameters:
nrtilesx - nr of tiles horizontally
nrtilesy - nr of tiles vertically
tilex - width of one tile
tiley - height of one tile
fgcolor - pen/text colour, null for default white
bgcolor - background colour, null for default black
msgfont - font for messages and text drawing, null for default
width - real screen width, 0 = use screen size
height - real screen height, 0 = use screen size

setColorsFont

public void setColorsFont(java.awt.Color fgcolor,
                          java.awt.Color bgcolor,
                          java.awt.Font msgfont)
Set foreground and background colour and font in one go; passing null means ignore.


pfWidth

public int pfWidth()
Get the virtual width in pixels (not the scaled screen width)


pfHeight

public int pfHeight()
Get the virtual height in pixels (not the scaled screen height)


pfTilesX

public int pfTilesX()
Get the number of tiles in X direction


pfTilesY

public int pfTilesY()
Get the number of tiles in Y direction


pfTileWidth

public int pfTileWidth()
Get the tile width in (virtual) pixels.


pfTileHeight

public int pfTileHeight()
Get the tile height in (virtual) pixels.


getFullPath

public java.net.URL getFullPath(java.lang.String subpath)
Add base URL of the current environment to the given file path; this will result in a URL that both applications and applets can load from.

Parameters:
subpath - relative path, null if error

init

public void init()
Initialise engine; don't call directly. This is supposed to be called by the applet viewer or the initer.


initGame

public abstract void initGame()
Override to define your own initialisations. This method is called after calling initEngine() or initEngineApplet()..


start

public void start()
Signal that the engine should start running


stop

public void stop()
signal that the engine should stop running and wait


destroy

public void destroy()
Destroy function for deinitialising the engine properly. In particular, this is called by the applet viewer to dispose the applet.


setFrameRate

public void setFrameRate(double fps,
                         double maxframeskip)
Set frame rate in frames per second, and maximum number of frames that may be skipped before displaying a frame again.

Parameters:
fps - frames per second, useful range 2...80
maxframeskip - max successive frames to skip, useful range 0..10

setBGColor

public void setBGColor(java.awt.Color bgcol)
Set global background colour.


setBGImage

public void setBGImage(java.lang.String bgimg)
Set image to display behind transparent tiles. Image size must be a multiple of the tile size. Passing null turns off background image; the background colour will be used instead.

Parameters:
bgimg - image name, null=turn off background image

setColor

public void setColor(java.awt.Color fgcol)
Set global foreground colour, used for printing text and status messages.


setFont

public void setFont(java.awt.Font msgfont)
Set font for printing text and status messages.


setGameState

public void setGameState(java.lang.String state)
Set the game's main state. Methods with the names doFrame<state> and paintFrame<state> will be called in addition to doFrame() and paintFrame().


addGameState

public void addGameState(java.lang.String state)
Add the given state to the game's existing state. The methods doFrame<state> and paintFrame<state> will be called in addition to the methods of any states already set.


clearGameState

public void clearGameState()
Set the game's main state to none. Only doFrame() and paintFrame() will be called each frame.


inGameState

public boolean inGameState(java.lang.String state)
Check if game is in given state.


doFrame

public void doFrame()
Is called every frame. Override to define frame action. Default is do nothing.


paintFrame

public void paintFrame()
Is called when the engine's default screen painting is finished, and custom painting actions may be carried out. Can be used to display status information or special graphics. Default is do nothing.


getBufferGraphics

public java.awt.Graphics getBufferGraphics()
Get the graphics context for drawing on the buffer during a paintFrame(). Returns null when not inside paintFrame.


getXScaleFactor

public double getXScaleFactor()
Get scale factor of real screen width wrt virtual screen width


getYScaleFactor

public double getYScaleFactor()
Get scale factor of real screen height wrt virtual screen height


getMinScaleFactor

public double getMinScaleFactor()
Get minimum of the x and y scale factors


drawImage

public void drawImage(int x,
                      int y,
                      java.lang.String imgname)
Draw image with given ID


drawString

public void drawString(java.lang.String str,
                       int x,
                       int y,
                       int align)
draws string so that (x,y) is the topleft coordinate (align=-1), the top middle coordinate (align=0), or the top right coordinate (align=1).

Parameters:
align - text alignment, -1 = left, 0=center, 1=right

drawImageString

public void drawImageString(java.lang.String string,
                            int x,
                            int y,
                            java.lang.String imgmap,
                            int char_offset,
                            int spacing)
Draws a single line of text using an image map as font; text alignment is always top left.

Parameters:
imgmap - name of image map
char_offset - ASCII code of first image of image map
spacing - number of pixels to skip between letters

getKey

public boolean getKey(int key)
Get the key status of the given key.


clearKey

public void clearKey(int key)
Set the key status of a key to released.


setKey

public void setKey(int key)
Set the key status of a key to pressed.


defineImageMap

public void defineImageMap(java.lang.String mapname,
                           java.lang.String imgurl,
                           int xofs,
                           int yofs,
                           int tilex,
                           int tiley,
                           int skipx,
                           int skipy)
Define image map, a large image containing a number of smaller images to use for sprites or fonts. The images must be in a regularly spaced matrix. One may define multiple image maps with the same image but different matrix specs.

Parameters:
mapname - id of image map
imgurl - url/path of map image
xofs - x offset of first image
yofs - y offset of first image
tilex - width of an image
tiley - height of an image
skipx - nr of pixels to skip between successive images
skipy - nr of pixels to skip between successive images vertically.

defineImage

public void defineImage(java.lang.String imgname,
                        java.lang.String tilename,
                        int collisionid,
                        java.lang.String imgfile,
                        boolean is_transparent,
                        java.lang.String img_op,
                        int top,
                        int left,
                        int width,
                        int height)
Define new sprite/tile image.

Parameters:
imgname - image id
tilename - tile id (1-4 characters)
collisionid - cid to use for tile collision matching
imgfile - filespec relative to baseurl; "null" means no file
is_transparent - signal transparency for tile operations
top - collision bounding box dimensions
left - collision bounding box dimensions
width - collision bounding box dimensions
height - collision bounding box dimensions

defineImage

public void defineImage(java.lang.String imgname,
                        java.lang.String tilename,
                        int collisionid,
                        java.lang.String imgmap,
                        int mapidx,
                        boolean is_transparent,
                        java.lang.String img_op,
                        int top,
                        int left,
                        int width,
                        int height)
Define new image from map.

Parameters:
imgname - image id
tilename - tile id (1-4 characters)
collisionid - cid to use for tile collision matching
imgmap - id of image map
mapidx - index of image in map, 0=first
is_transparent - signal transparency for tile operations
top - collision bounding box dimensions
left - collision bounding box dimensions
width - collision bounding box dimensions
height - collision bounding box dimensions

defineImages

public void defineImages(java.lang.String filename)
Load a set of imagemap, image, and animation definitions from a file. The file contains one image / imagemap / animation definition on each line, with the fields separated by one or more tabs. Lines not matching the required # of fields are ignored. The fields have the same order as in defineImage, defineImageMap, defineAnimation.


getImageBBox

public java.awt.Rectangle getImageBBox(java.lang.String imgname)
Gets the collision bounding box of an image.


clearBG

public void clearBG(java.lang.String filltilename)
Fill the background with the given tile.

Parameters:
filltilename - null means use background colour

setBGTile

public void setBGTile(int x,
                      int y,
                      java.lang.String tilename)
Define a single tile.


setBGTiles

public void setBGTiles(int xofs,
                       int yofs,
                       java.lang.String[] tilemap)
Set a block of tiles according to the chars in the nxm char array tilemap.


setBGTilesMulti

public void setBGTilesMulti(int xofs,
                            int yofs,
                            java.lang.String[] tilemap)
Set a block of tiles according to the tile names in the nxm element array tilemap. Tile names in each line are separated by spaces.


getBGTileCidAtCoord

public int getBGTileCidAtCoord(double x,
                               double y)
Get collision Id of the tile at given pixel coordinates.


getBGTileCid

public int getBGTileCid(int xidx,
                        int yidx)
Get cid of tile at given tile index position.


getBGTileCid

public int getBGTileCid(java.awt.Point center,
                        int xofs,
                        int yofs)
Get the tile cid of the point that is (xofs,yofs) from the tile index coordinate center.


getBGTileStringAtCoord

public java.lang.String getBGTileStringAtCoord(double x,
                                               double y)
Get collision Id of the tile at given pixel coordinates.


getBGTileString

public java.lang.String getBGTileString(int xidx,
                                        int yidx)
get string id of tile at given index position


getBGTileString

public java.lang.String getBGTileString(java.awt.Point center,
                                        int xofs,
                                        int yofs)
Get the tile string of the point that is (xofs,yofs) from the tile index coordinate center.


getBGTileCid

public int getBGTileCid(java.awt.Rectangle tiler)
Get the OR of the cids at the tile indexes given by tiler


existsObject

public boolean existsObject(java.lang.String index)
Get object if it exists, null if not.


getObject

public JGObject getObject(java.lang.String index)
Get object if it exists, null if not.


removeObjects

public void removeObjects(java.lang.String prefix,
                          int cidmask)
Remove all objects which have the given name prefix and/or match the given cidmask. The actual matching and removal is done after the current moveObjects or check*Collision ends, or immediately if done from within the main doFrame loop. It also removes any matching objects which are pending to be added the next frame.

Parameters:
cidmask - collision id mask, 0 means ignore
prefix - ID prefix, null means ignore

countObjects

public int countObjects(java.lang.String prefix,
                        int cidmask)
Count how many objects there are with both the given name prefix and have colid&cidmask != 0. Either criterion can be left out.

Parameters:
cidmask - collision id mask, 0 means ignore
prefix - ID prefix, null means ignore

moveObjects

public void moveObjects(java.lang.String prefix,
                        int cidmask)
Call the move() methods of those objects matching the given name prefix and collision id mask.

Parameters:
cidmask - collision id mask, 0 means ignore
prefix - ID prefix, null means ignore

moveObjects

public void moveObjects()
Call all move() methods of all registered objects.


checkCollision

public void checkCollision(int srcid,
                           int dstid)
Calls all colliders of objects that match dstid that collide with objects that match srcid.


checkBGCollision

public int checkBGCollision(java.awt.Rectangle r)
Check collision of tiles within given rectangle, return the OR of all cids found.


checkBGCollision

public void checkBGCollision(int tileid,
                             int objid)
Calls all bg colliders of objects that match objid that collide with tiles that match tileid.


and

public boolean and(int value,
                   int mask)
A Boolean AND shorthand to use for collision; returns (value&mask) != 0.


random

public double random(double min,
                     double max)

random

public double random(double min,
                     double max,
                     double interval)

getTileSpan

public java.awt.Rectangle getTileSpan(java.awt.Rectangle r)
Get tile index range of all tiles overlapping given rectangle of pixel coordinates.

Returns:
tile indices

getTileIndex

public java.awt.Point getTileIndex(double x,
                                   double y)
Get tile index of the tile the coordinate is on.


snapToGridX

public double snapToGridX(double x,
                          double gridsnapx)
Snap to grid, double version. Epsilon is added to the gridsnap value, so that isXAligned(x,margin) always implies that snapToGridX(x,margin) will snap.

Parameters:
x - position to snap
gridsnapx - snap margin, 0.0 means no snap

snapToGridY

public double snapToGridY(double y,
                          double gridsnapy)
Snap to grid, double version. Epsilon is added to the gridsnap value. 0.0 means no snap


snapToGrid

public void snapToGrid(java.awt.Point p,
                       int gridsnapx,
                       int gridsnapy)
Snap p to grid in case p is close enough to the grid lines. Note: this function only handles integers so it should not be used to snap an object position.


isXAligned

public boolean isXAligned(double x,
                          double margin)
Returns true if x falls within margin of the tile snap grid. Epsilon is added to the margin, so that isXAligned(1.000..., 1.000...) always returns true.


isYAligned

public boolean isYAligned(double y,
                          double margin)
Returns true if y falls within margin of the tile snap grid. Epsilon is added to the margin, so that isYAligned(1.000..., 1.000...) always returns true.