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
Direct Known Subclasses:
StdGame

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 first try to call start<state>() once at the beginning of the next frame. Then it will try to call additional doFrame<state>() and paintFrame<state>() methods every frame, where you can handle the game action for that specific state. Multple states may be set simultaneously, resulting in multiple method calls for 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 by the 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 sprite bounding box, or simply bounding box), and one for object-tile collision (the tile bounding box). The two bounding boxes may be dependent on the image (typically, you want these bounding boxes to approximate the shape of each individual image). For this purpose, you can define a collision bounding box with each image definition. This image bounding box is the default bounding box used by the object, but both sprite bbox and tile bbox 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 arbitrary runtime scaling of the playfield. 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 translucency-free scaling algorithm to ensure good performance.

The engine supports keyboard and mouse input. The state of the keyboard is maintained in a keymap, which can be read by getKey. The mouse can be read using getMouseButton and getMouseX/Y. The mouse buttons also have special keycodes.

Upon initialisation, the engine shows an initialisation screen with a progress bar that reflects progress on the current graphics table being loaded. A splash image can be displayed during the init screen, by defining an image called splash_image. As soon as this image is defined, it is displayed above the progress message. Typically, one defines splash_image at the beginning of the graphics table, so that it displays as soon as possible during the init screen.

See Also:
Serialized Form

Field Summary
static int KeyAlt
           
static int KeyCtrl
           
static int KeyDown
          Keycode of cursor key.
static int KeyLeft
          Keycode of cursor key.
static int KeyMouse1
          Keymap equivalent of mouse button.
static int KeyMouse2
          Keymap equivalent of mouse button.
static int KeyMouse3
          Keymap equivalent of mouse button.
static int KeyRight
          Keycode of cursor key.
static int KeyShift
           
static int KeyUp
          Keycode of cursor key.
 
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 on the next frame.
 boolean and(int value, int mask)
          A Boolean AND shorthand to use for collision; returns (value&mask) != 0.
 void andBGTileCid(int x, int y, int and_mask)
          Modify the cid of a single tile by ORing a bit mask, leaving the actual tile.
 void checkBGCollision(int tilecid, int objcid)
          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 srccid, int dstcid)
          Calls all colliders of objects that match dstid that collide with objects that match srcid.
 void clearGameState()
          Set the game's main state to none, on the next frame.
 void clearKey(int key)
          Set the key status of a key to released.
 void clearMouseButton(int nr)
          Set state of button 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.
 int countTiles(int tilecidmask)
          Count number of tiles with given mask.
 void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed)
          Define new animation sequence.
 void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed, boolean pingpong)
          Define new animation sequence.
 void defineGraphics(java.lang.String filename)
          Load a set of imagemap, image, and animation definitions from a file.
 void defineImage(java.lang.String imgname, java.lang.String tilename, int collisionid, java.lang.String imgmap, int mapidx, java.lang.String img_op)
          Define new sprite/tile image from map, with collision bounding box equal to the image's dimensions.
 void defineImage(java.lang.String imgname, java.lang.String tilename, int collisionid, java.lang.String imgmap, int mapidx, java.lang.String img_op, int top, int left, int width, int height)
          Define new sprite/tile image from map.
 void defineImage(java.lang.String imgname, java.lang.String tilename, int collisionid, java.lang.String imgfile, java.lang.String img_op)
          Define new sprite/tile image with collision bounding box equal to the image's dimensions.
 void defineImage(java.lang.String imgname, java.lang.String tilename, int collisionid, java.lang.String imgfile, java.lang.String img_op, int top, int left, int width, int height)
          Define new sprite/tile image.
 void defineImageMap(java.lang.String mapname, java.lang.String imgfile, 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 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, int align, java.lang.String imgmap, int char_offset, int spacing)
          Draws a single line of text using an image map as font; text alignment is same as drawString.
 void drawLine(int x1, int y1, int x2, int y2)
           
 void drawLine(int x1, int y1, int x2, int y2, double thickness, java.awt.Color color)
           
 void drawOval(int x, int y, int width, int height, boolean filled, boolean centered)
           
 void drawOval(int x, int y, int width, int height, boolean filled, boolean centered, double thickness, java.awt.Color color)
           
 void drawRect(int x, int y, int width, int height, boolean filled, boolean centered)
           
 void drawRect(int x, int y, int width, int height, boolean filled, boolean centered, double thickness, java.awt.Color color)
           
 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).
 void drawString(java.lang.String str, int x, int y, int align, java.awt.Font font, java.awt.Color color)
          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)
          Check if object exists.
 void fillBG(java.lang.String filltilename)
          Fill the background with the given tile.
 int getBGTileCid(int xidx, int yidx)
          Get collision id 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 getBGTileStr(int xidx, int yidx)
          get string id of tile at given index position
 java.lang.String getBGTileStr(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 getBGTileStrAtCoord(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.Image getImage(java.lang.String imgname)
          Gets (scaled) image directly.
 java.awt.Rectangle getImageBBox(java.lang.String imgname)
          Gets the collision bounding box of an image.
 java.awt.Dimension getImageSize(java.lang.String imgname)
          Gets (non-scaled) image's physical size directly.
 boolean getKey(int key)
          Get the key status of the given key.
 java.lang.String getKeyDesc(int key)
          Get a printable string describing the key.
 double getMinScaleFactor()
          Get minimum of the x and y scale factors
 boolean getMouseButton(int nr)
          Get state of button.
 boolean getMouseInside()
          Check if mouse is inside game window
 java.awt.Point getMousePos()
          Get current mouse position
 int getMouseX()
          Get current mouse X position
 int getMouseY()
          Get current mouse Y position
 JGObject getObject(java.lang.String index)
          Get object if it exists, null if not.
 java.awt.Point getTileCoord(int tilex, int tiley)
          Get pixel coordinate corresponding to the top left of the tile at the given index
 java.awt.Point getTileCoord(java.awt.Point tileidx)
          Get pixel coordinate corresponding to the top left of the tile at the given index
 java.awt.Point getTileIndex(double x, double y)
          Get tile index of the tile the coordinate is on.
 java.awt.Rectangle getTiles(java.awt.Rectangle r)
          Get tile index range of all tiles overlapping given rectangle of pixel coordinates.
 double getXAlignOfs(double x)
          Returns the difference between position and the closest tile-aligned position.
 double getXScaleFactor()
          Get scale factor of real screen width wrt virtual screen width
 double getYAlignOfs(double y)
          Returns the difference between position and the closest tile-aligned position.
 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.
 boolean inGameStateNextFrame(java.lang.String state)
          Check if game will be in given state the next frame.
 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 the 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 orBGTileCid(int x, int y, int or_mask)
          Modify the cid of a single tile by ORing a bit mask, leaving the actual tile.
 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)
          A floating-point random number between min and max
 double random(double min, double max, double interval)
          Generates discrete random number between min and max inclusive, with steps of interval.
 int random(int min, int max, int interval)
          Generates discrete random number between min and max inclusive, with steps of interval, integer version.
 void removeAllTimers()
          Remove all JGTimers still ticking in the system.
 void removeGameState(java.lang.String state)
          Remove the given state from the game's existing state on the next frame.
 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, which is displayed behind transparent tiles if no BGImage is defined.
 void setBGImage(java.lang.String bgimg)
          Set image to display behind transparent tiles.
 void setBGTile(int x, int y, java.lang.String tilename)
          Set a single tile.
 void setBGTile(java.awt.Point tileidx, java.lang.String tilename)
          Set a single tile.
 void setBGTileCid(int x, int y, int value)
          Set the cid of a single tile to the given value, leaving the actual tile.
 void setBGTiles(int xofs, int yofs, java.lang.String[] tilemap)
          Set a block of tiles according to the single-letter tile names in the nxm character array tilemap.
 void setBGTileSettings(java.lang.String out_of_bounds_tile, int out_of_bounds_cid, int preserve_cids)
          Define background tile settings.
 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)
          Show bounding boxes around the objects: the image bounding box, the tile span, and the center tiles (getCenterTiles).
 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 setCursor(java.awt.Cursor cursor)
          Set mouse cursor, null means hide cursor
 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 on the next frame.
 void setKey(int key)
          Set the key status of a key to pressed.
 void setMouseButton(int nr)
          Set state of button to pressed.
 void setStroke(double thickness)
          Set the line thickness
 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 startAllAnim()
          Start automatic animation in case it was stopped.
 void stop()
          signal that the engine should stop running and wait.
 void stopAllAnim()
          Stop automatic animation of all objects.
 void wakeUpOnKey(int key)
          Make engine call start() when a key is pressed.
 
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, 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
Keycode of cursor key.

See Also:
Constant Field Values

KeyDown

public static final int KeyDown
Keycode of cursor key.

See Also:
Constant Field Values

KeyLeft

public static final int KeyLeft
Keycode of cursor key.

See Also:
Constant Field Values

KeyRight

public static final int KeyRight
Keycode of cursor key.

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

KeyMouse1

public static final int KeyMouse1
Keymap equivalent of mouse button.

See Also:
Constant Field Values

KeyMouse2

public static final int KeyMouse2
Keymap equivalent of mouse button.

See Also:
Constant Field Values

KeyMouse3

public static final int KeyMouse3
Keymap equivalent of mouse button.

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)
Show bounding boxes around the objects: the image bounding box, the tile span, and the center tiles (getCenterTiles).


defineAnimation

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

Parameters:
id - the name by which the animation is known
frames - an array of image names that should be played in sequence
speed - the sequence speed: the number of animation steps per frame

defineAnimation

public void defineAnimation(java.lang.String id,
                            java.lang.String[] frames,
                            double speed,
                            boolean pingpong)
Define new animation sequence.

Parameters:
id - the name by which the animation is known
frames - an array of image names that should be played in sequence
speed - the sequence speed: the number of animation steps per frame
pingpong - true=play the images in forward order, then in reverse

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 by the game thread after initEngine() or initEngineApplet() was called.


start

public void start()
Signal that the engine should start running. May be called by the web browser.


stop

public void stop()
signal that the engine should stop running and wait. May be called by the web browser.


wakeUpOnKey

public void wakeUpOnKey(int key)
Make engine call start() when a key is pressed. This can be used to determine a start criterion when halting the engine from within using stop().

Parameters:
key - keycode to wake up on, -1=any key or mouse, 0=none

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. Default is 35 frames per second, with a maxframeskip of 4.

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, which is displayed behind transparent tiles if no BGImage is defined.


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.


setCursor

public void setCursor(java.awt.Cursor cursor)
Set mouse cursor, null means hide cursor


removeAllTimers

public void removeAllTimers()
Remove all JGTimers still ticking in the system.


setGameState

public void setGameState(java.lang.String state)
Set the game's main state on the next frame. Methods with the names doFrame<state> and paintFrame<state> will be called in addition to doFrame() and paintFrame(). Before the next frame, start<state> is called once. Note that setGameState may actually set a state that's already set, in which case start<state> is not called. Also, if the setGameState is superseded by another setGameState within the same frame, the first setGameState is ignored.


addGameState

public void addGameState(java.lang.String state)
Add the given state to the game's existing state on the next frame. The methods doFrame<state> and paintFrame<state> will be called in addition to the methods of any states already set. Before the next frame, start<state> is called once. Note that addGameState may actually set a state that's already set, in which case start<state> is not called.


removeGameState

public void removeGameState(java.lang.String state)
Remove the given state from the game's existing state on the next frame.


clearGameState

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


inGameState

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


inGameStateNextFrame

public boolean inGameStateNextFrame(java.lang.String state)
Check if game will be in given state the next frame.


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


setStroke

public void setStroke(double thickness)
Set the line thickness


drawLine

public void drawLine(int x1,
                     int y1,
                     int x2,
                     int y2,
                     double thickness,
                     java.awt.Color color)

drawLine

public void drawLine(int x1,
                     int y1,
                     int x2,
                     int y2)

drawRect

public void drawRect(int x,
                     int y,
                     int width,
                     int height,
                     boolean filled,
                     boolean centered,
                     double thickness,
                     java.awt.Color color)
Parameters:
centered - indicates (x,y) is center instead of topleft.

drawRect

public void drawRect(int x,
                     int y,
                     int width,
                     int height,
                     boolean filled,
                     boolean centered)
Parameters:
centered - indicates (x,y) is center instead of topleft.

drawOval

public void drawOval(int x,
                     int y,
                     int width,
                     int height,
                     boolean filled,
                     boolean centered,
                     double thickness,
                     java.awt.Color color)
Parameters:
centered - indicates (x,y) is center instead of topleft.

drawOval

public void drawOval(int x,
                     int y,
                     int width,
                     int height,
                     boolean filled,
                     boolean centered)
Parameters:
centered - indicates (x,y) is center instead of topleft.

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). Use current font and colour.

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

drawString

public void drawString(java.lang.String str,
                       int x,
                       int y,
                       int align,
                       java.awt.Font font,
                       java.awt.Color color)
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). Use given font and colour; filling in null for either means ignore.

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

drawImageString

public void drawImageString(java.lang.String string,
                            int x,
                            int y,
                            int align,
                            java.lang.String imgmap,
                            int char_offset,
                            int spacing)
Draws a single line of text using an image map as font; text alignment is same as drawString. Typically, an image font only defines the ASCII character range 32-96. In this case, set char_offset to 32, and use only the uppercase letters.

Parameters:
align - text alignment, -1=left, 0=center, 1=right
imgmap - name of image map
char_offset - ASCII code of first image of image map
spacing - number of pixels to skip between letters

getMousePos

public java.awt.Point getMousePos()
Get current mouse position


getMouseX

public int getMouseX()
Get current mouse X position


getMouseY

public int getMouseY()
Get current mouse Y position


getMouseButton

public boolean getMouseButton(int nr)
Get state of button.

Parameters:
nr - 1=button 1 ... 3 = button 3
Returns:
true=pressed, false=released

clearMouseButton

public void clearMouseButton(int nr)
Set state of button to released.

Parameters:
nr - 1=button 1 ... 3 = button 3

setMouseButton

public void setMouseButton(int nr)
Set state of button to pressed.

Parameters:
nr - 1=button 1 ... 3 = button 3

getMouseInside

public boolean getMouseInside()
Check if mouse is inside game window


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.


getKeyDesc

public java.lang.String getKeyDesc(int key)
Get a printable string describing the key.


defineImageMap

public void defineImageMap(java.lang.String mapname,
                           java.lang.String imgfile,
                           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
imgfile - filespec relative to baseurl
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,
                        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
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 imgfile,
                        java.lang.String img_op)
Define new sprite/tile image with collision bounding box equal to the image's dimensions.

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

defineImage

public void defineImage(java.lang.String imgname,
                        java.lang.String tilename,
                        int collisionid,
                        java.lang.String imgmap,
                        int mapidx,
                        java.lang.String img_op,
                        int top,
                        int left,
                        int width,
                        int height)
Define new sprite/tile 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
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,
                        java.lang.String img_op)
Define new sprite/tile image from map, with collision bounding box equal to the image's dimensions.

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

defineGraphics

public void defineGraphics(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 number of fields are ignored. The fields have the same order as in defineImage, defineImageMap, and defineAnimation. For example:

defineImage("mytile", "#", 1,"gfx/myimage.gif", "-");

is equivalent to the following line in the table:

mytile     #     1     gfx/myimage.gif     -

with the whitespace between the fields consisting of one or more tabs. The defineAnimation methods take an array of names as the second argument. This is represented in table format as the names separated by semicolon ';' characters. So:

defineAnimation("anim",new String[]{"frame0","frame1",...},0.5);

is equivalent to:

anim     frame0;frame1;...     0.5


getImage

public java.awt.Image getImage(java.lang.String imgname)
Gets (scaled) image directly. Is usually not necessary.


getImageSize

public java.awt.Dimension getImageSize(java.lang.String imgname)
Gets (non-scaled) image's physical size directly.


getImageBBox

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


setBGTileSettings

public void setBGTileSettings(java.lang.String out_of_bounds_tile,
                              int out_of_bounds_cid,
                              int preserve_cids)
Define background tile settings. Default is setBGCidSettings("",0,0).

Parameters:
out_of_bounds_tile - tile string to use outside of screen bounds
out_of_bounds_cid - cid to use outside of screen boundaries
preserve_cids - cid mask to preserve when setting tiles

fillBG

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

Parameters:
filltilename - null means use background colour

setBGTileCid

public void setBGTileCid(int x,
                         int y,
                         int value)
Set the cid of a single tile to the given value, leaving the actual tile.


orBGTileCid

public void orBGTileCid(int x,
                        int y,
                        int or_mask)
Modify the cid of a single tile by ORing a bit mask, leaving the actual tile.


andBGTileCid

public void andBGTileCid(int x,
                         int y,
                         int and_mask)
Modify the cid of a single tile by ORing a bit mask, leaving the actual tile.


setBGTile

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


setBGTile

public void setBGTile(java.awt.Point tileidx,
                      java.lang.String tilename)
Set a single tile.


setBGTiles

public void setBGTiles(int xofs,
                       int yofs,
                       java.lang.String[] tilemap)
Set a block of tiles according to the single-letter tile names in the nxm character 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. The tile names may be multiple characters. Each String in the tilemap consists of a list of tile names separated by spaces. So: "x aa ab abc" stands for a sequence of four tiles, "x", "aa", "ab", and "abc".


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 collision id 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.


getBGTileStrAtCoord

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


getBGTileStr

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


getBGTileStr

public java.lang.String getBGTileStr(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


countTiles

public int countTiles(int tilecidmask)
Count number of tiles with given mask. Actually searches all tiles, so it's inefficient and should be used sparingly (such as, determine the number of something at the beginning of a game).


existsObject

public boolean existsObject(java.lang.String index)
Check if object exists.


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. Actually searches the object array, so it may be inefficient.

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 the move() methods of all registered objects.


startAllAnim

public void startAllAnim()
Start automatic animation in case it was stopped.


stopAllAnim

public void stopAllAnim()
Stop automatic animation of all objects.


checkCollision

public void checkCollision(int srccid,
                           int dstcid)
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 tilecid,
                             int objcid)
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)
A floating-point random number between min and max


random

public double random(double min,
                     double max,
                     double interval)
Generates discrete random number between min and max inclusive, with steps of interval. Epsilon is added to max to ensure there are no rounding error problems with the interval. So, random(0.0, 4.2, 2.1) generates either 0.0, 2.1, or 4.2 with uniform probabilities. If max is halfway between interval steps, max is treated as exclusive. So, random(0.0,5.0,2.1) generates 0.0, 2.1, 4.2 with uniform probabilities. If you need integer ranges, be sure to use the integer version to avoid rounding problems.


random

public int random(int min,
                  int max,
                  int interval)
Generates discrete random number between min and max inclusive, with steps of interval, integer version. If max is halfway between two interval steps, it is treated as exclusive.


getTiles

public java.awt.Rectangle getTiles(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.


getTileCoord

public java.awt.Point getTileCoord(int tilex,
                                   int tiley)
Get pixel coordinate corresponding to the top left of the tile at the given index


getTileCoord

public java.awt.Point getTileCoord(java.awt.Point tileidx)
Get pixel coordinate corresponding to the top left of the tile at the given index


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.0000, 1.0000) 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.0000, 1.0000) always returns true.


getXAlignOfs

public double getXAlignOfs(double x)
Returns the difference between position and the closest tile-aligned position.


getYAlignOfs

public double getYAlignOfs(double y)
Returns the difference between position and the closest tile-aligned position.