|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectjava.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
jgame.JGEngine
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().
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 |
public static final int KeyUp
public static final int KeyDown
public static final int KeyLeft
public static final int KeyRight
public static final int KeyShift
public static final int KeyCtrl
public static final int KeyAlt
Constructor Detail |
public JGEngine()
Method Detail |
public static void setBoundingBoxDebug(boolean enabled)
public void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed)
public void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed, int increment)
public void defineAnimation(java.lang.String id, java.lang.String[] frames, double speed, int increment, boolean pingpong)
public void initEngineApplet(int nrtilesx, int nrtilesy, int tilex, int tiley, java.awt.Color fgcolor, java.awt.Color bgcolor, java.awt.Font msgfont)
nrtilesx
- nr of tiles horizontallynrtilesy
- nr of tiles verticallytilex
- width of one tiletiley
- height of one tilefgcolor
- pen/text colour, null for default whitebgcolor
- background colour, null for default blackmsgfont
- font for messages and text drawing, null for defaultpublic 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)
nrtilesx
- nr of tiles horizontallynrtilesy
- nr of tiles verticallytilex
- width of one tiletiley
- height of one tilefgcolor
- pen/text colour, null for default whitebgcolor
- background colour, null for default blackmsgfont
- font for messages and text drawing, null for defaultwidth
- real screen width, 0 = use screen sizeheight
- real screen height, 0 = use screen sizepublic void setColorsFont(java.awt.Color fgcolor, java.awt.Color bgcolor, java.awt.Font msgfont)
public int pfWidth()
public int pfHeight()
public int pfTilesX()
public int pfTilesY()
public int pfTileWidth()
public int pfTileHeight()
public java.net.URL getFullPath(java.lang.String subpath)
subpath
- relative path, null if errorpublic void init()
public abstract void initGame()
public void start()
public void stop()
public void destroy()
public void setFrameRate(double fps, double maxframeskip)
fps
- frames per second, useful range 2...80maxframeskip
- max successive frames to skip, useful range 0..10public void setBGColor(java.awt.Color bgcol)
public void setBGImage(java.lang.String bgimg)
bgimg
- image name, null=turn off background imagepublic void setColor(java.awt.Color fgcol)
public void setFont(java.awt.Font msgfont)
public void setGameState(java.lang.String state)
public void addGameState(java.lang.String state)
public void clearGameState()
public boolean inGameState(java.lang.String state)
public void doFrame()
public void paintFrame()
public java.awt.Graphics getBufferGraphics()
public double getXScaleFactor()
public double getYScaleFactor()
public double getMinScaleFactor()
public void drawImage(int x, int y, java.lang.String imgname)
public void drawString(java.lang.String str, int x, int y, int align)
align
- text alignment, -1 = left, 0=center, 1=rightpublic void drawImageString(java.lang.String string, int x, int y, java.lang.String imgmap, int char_offset, int spacing)
imgmap
- name of image mapchar_offset
- ASCII code of first image of image mapspacing
- number of pixels to skip between letterspublic boolean getKey(int key)
public void clearKey(int key)
public void setKey(int key)
public void defineImageMap(java.lang.String mapname, java.lang.String imgurl, int xofs, int yofs, int tilex, int tiley, int skipx, int skipy)
mapname
- id of image mapimgurl
- url/path of map imagexofs
- x offset of first imageyofs
- y offset of first imagetilex
- width of an imagetiley
- height of an imageskipx
- nr of pixels to skip between successive imagesskipy
- nr of pixels to skip between successive images vertically.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)
imgname
- image idtilename
- tile id (1-4 characters)collisionid
- cid to use for tile collision matchingimgfile
- filespec relative to baseurl; "null" means no fileis_transparent
- signal transparency for tile operationstop
- collision bounding box dimensionsleft
- collision bounding box dimensionswidth
- collision bounding box dimensionsheight
- collision bounding box dimensionspublic 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)
imgname
- image idtilename
- tile id (1-4 characters)collisionid
- cid to use for tile collision matchingimgmap
- id of image mapmapidx
- index of image in map, 0=firstis_transparent
- signal transparency for tile operationstop
- collision bounding box dimensionsleft
- collision bounding box dimensionswidth
- collision bounding box dimensionsheight
- collision bounding box dimensionspublic void defineImages(java.lang.String filename)
public java.awt.Rectangle getImageBBox(java.lang.String imgname)
public void clearBG(java.lang.String filltilename)
filltilename
- null means use background colourpublic void setBGTile(int x, int y, java.lang.String tilename)
public void setBGTiles(int xofs, int yofs, java.lang.String[] tilemap)
public void setBGTilesMulti(int xofs, int yofs, java.lang.String[] tilemap)
public int getBGTileCidAtCoord(double x, double y)
public int getBGTileCid(int xidx, int yidx)
public int getBGTileCid(java.awt.Point center, int xofs, int yofs)
public java.lang.String getBGTileStringAtCoord(double x, double y)
public java.lang.String getBGTileString(int xidx, int yidx)
public java.lang.String getBGTileString(java.awt.Point center, int xofs, int yofs)
public int getBGTileCid(java.awt.Rectangle tiler)
public boolean existsObject(java.lang.String index)
public JGObject getObject(java.lang.String index)
public void removeObjects(java.lang.String prefix, int cidmask)
cidmask
- collision id mask, 0 means ignoreprefix
- ID prefix, null means ignorepublic int countObjects(java.lang.String prefix, int cidmask)
cidmask
- collision id mask, 0 means ignoreprefix
- ID prefix, null means ignorepublic void moveObjects(java.lang.String prefix, int cidmask)
cidmask
- collision id mask, 0 means ignoreprefix
- ID prefix, null means ignorepublic void moveObjects()
public void checkCollision(int srcid, int dstid)
public int checkBGCollision(java.awt.Rectangle r)
public void checkBGCollision(int tileid, int objid)
public boolean and(int value, int mask)
public double random(double min, double max)
public double random(double min, double max, double interval)
public java.awt.Rectangle getTileSpan(java.awt.Rectangle r)
public java.awt.Point getTileIndex(double x, double y)
public double snapToGridX(double x, double gridsnapx)
x
- position to snapgridsnapx
- snap margin, 0.0 means no snappublic double snapToGridY(double y, double gridsnapy)
public void snapToGrid(java.awt.Point p, int gridsnapx, int gridsnapy)
public boolean isXAligned(double x, double margin)
public boolean isYAligned(double y, double margin)
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |