You are on page 1of 10

Package javax.microedition.lcdui.

game
i. The Game API package provides a series of classes that enable the development of rich gaming content for wireless devices.
ii. Wireless devices have minimal processing power, so much of the API is intended to improve performance by minimizing the
amount of work done in Java; this approach also has the added benefit of reducing application size.
iii. The API's are structured to provide considerable freedom when implementing them, thereby permitting the extensive use of
native code, hardware acceleration and device-specific image data formats as needed.
iv. The API uses the standard low-level graphics classes from MIDP (Graphics, Image, etc.) so that the high-level Game API
classes can be used in conjunction with graphics primitives. For example, it would be possible to render a complex background
using the Game API and then render something on top of it using graphics primitives such as drawLine, etc.
v. Methods that modify the state of Layer, LayerManager, Sprite, and TiledLayer objects generally do not have any immediately
visible side effects. Instead, this state is merely stored within the object and is used during subsequent calls to the paint()
method. This approach is suitable for gaming applications where there is a game cycle within which objects' states are updated,
and where the entire screen is redrawn at the end of every game cycle.
vi. The API is comprised of five classes:

Class Summary
GameCanvas The GameCanvas class provides the basis for a game user interface.
Layer A Layer is an abstract class representing a visual element of a game.
LayerManager The LayerManager manages a series of Layers.
Sprite A Sprite is a basic visual element that can be rendered with one of several frames stored in an Image;
different frames can be shown to animate the Sprite.
TiledLayer A TiledLayer is a visual element composed of a grid of cells that can be filled with a set of tile
images.

Class GameCanvas
i. Declaration:
public abstract class GameCanvas extends Canvas
ii. The GameCanvas class provides the basis 'screen' functionality for a game user interface. In addition to the features inherited
from Canvas (commands, input events, etc.) it also provides game-specific capabilities such as an off-screen graphics buffer,
synchronous graphics flushing and the ability to query key status.
iii. A dedicated buffer is created for each GameCanvas instance. Since a unique buffer is provided for each GameCanvas instance,
it is preferable to re-use a single GameCanvas instance in the interests of minimizing heap usage.
iv. The developer can assume that the contents of this buffer are modified only by calls to the Graphics object(s) obtained from
the GameCanvas instance; the contents are not modified by external sources such as other MIDlets or system-level
notifications.
v. The buffer is initially filled with white pixels.
vi. The buffer's size is set to the maximum dimensions of the GameCanvas. However, the area that may be flushed is limited by
the current dimensions of the GameCanvas (as influenced by the presence of a Ticker, Commands, etc.) when the flush is
requested. The current dimensions of the GameCanvas may be obtained by calling getWidth and getHeight.
vii. A game may provide its own thread to run the game loop. A typical loop will check for input, implement the game logic, and
then render the updated user interface. The following code illustrates the structure of a typcial game loop:
// Get the Graphics object for the off-screen buffer
Graphics g = getGraphics();
while (true) {
// Check user input and update positions if necessary
int keyState = getKeyStates();
if ((keyState & LEFT_PRESSED) != 0) {
sprite.move(-1, 0);
}
else if ((keyState & RIGHT_PRESSED) != 0) {
sprite.move(1, 0);
}

// Clear the background to white


g.setColor(0xFFFFFF);
g.fillRect(0,0,getWidth(), getHeight());

// Draw the Sprite


sprite.paint(g);
// Flush the off-screen buffer
flushGraphics();

1
Field Summary
static int DOWN_PRESSED
The bit representing the DOWN key.
static int FIRE_PRESSED
The bit representing the FIRE key.
static int GAME_A_PRESSED
The bit representing the GAME_A key (may not be supported on all devices).
static int GAME_B_PRESSED
The bit representing the GAME_B key (may not be supported on all devices).
static int GAME_C_PRESSED
The bit representing the GAME_C key (may not be supported on all devices).
static int GAME_D_PRESSED
The bit representing the GAME_D key (may not be supported on all devices).
static int LEFT_PRESSED
The bit representing the LEFT key.
static int RIGHT_PRESSED
The bit representing the RIGHT key.
static int UP_PRESSED
The bit representing the UP key.

Constructor Summary
protected GameCanvas(boolean suppressKeyEvents)
Creates a new instance of a GameCanvas.

Method Summary
void flushGraphics()
Flushes the off-screen buffer to the display.
void flushGraphics(int x, int y, int width, int height)
Flushes the specified region of the off-screen buffer to the display.
protected Graphics getGraphics()
Obtains the Graphics object for rendering a GameCanvas.
int getKeyStates()
Gets the states of the physical game keys.
void paint(Graphics g)
Paints this GameCanvas.

Class Layer
i. Declaration:
public abstract class Layer extends Object
ii. The Layer class represents a visual element in a game such as a Sprite or a TiledLayer. This abstract class forms the basis for
the Layer framework and provides basic attributes such as location, size, and visibility.
iii. Each Layer has position (in terms of the upper-left corner of its visual bounds), width, height, and can be made visible or
invisible. Layer subclasses must implement a paint(Graphics) method so that they can be rendered.
iv. The Layer's (x,y) position is always interpreted relative to the coordinate system of the Graphics object that is passed to the
Layer's paint() method. This coordinate system is referred to as the painter's coordinate system. The initial location of a Layer
is (0,0).

Method Summary
int getHeight()
Gets the current height of this layer, in pixels.
int getWidth()
Gets the current width of this layer, in pixels.
int getX()
Gets the horizontal position of this Layer's upper-left corner in the painter's coordinate system.
int getY()
Gets the vertical position of this Layer's upper-left corner in the painter's coordinate system.

2
boolean isVisible()
Gets the visibility of this Layer.
void move(int dx, int dy)
Moves this Layer by the specified horizontal and vertical distances.
abstract void paint(Graphics g)
Paints this Layer if it is visible.
void setPosition(int x, int y)
Sets this Layer's position such that its upper-left corner is located at (x,y) in the painter's
coordinate system.
void setVisible(boolean visible)
Sets the visibility of this Layer.

LayerManager
i. Declaration:
public class LayerManager extends Object
ii. The LayerManager manages a series of Layers. The LayerManager simplifies the process of rendering the Layers that have
been added to it by automatically rendering the correct regions of each Layer in the appropriate order.
iii. The LayerManager maintains an ordered list to which Layers can be appended, inserted and removed. A Layer's index
correlates to its z-order; the layer at index 0 is closest to the user while a the Layer with the highest index is furthest away from
the user.
iv. The indices are always contiguous; that is, if a Layer is removed, the indices of subsequent Layers will be adjusted to maintain
continuity.
v. The LayerManager class provides several features that control how the game's Layers are rendered on the screen.
vi. The view window controls the size of the visible region and its position relative to the LayerManager's coordinate system.
Changing the position of the view window enables effects such as scrolling or panning the user's view. For example, to scroll to
the right, simply move the view window's location to the right. The size of the view window controls how large the user's view
will be, and is usually fixed at a size that is appropriate for the device's screen.
vii. In this example, the view window is set to 85 x 85 pixels and is located at (52, 11) in the LayerManager's coordinate system.
The Layers appear at their respective positions relative to the LayerManager's origin.

viii. The paint(Graphics, int, int) method includes an (x,y) location that controls where the view window is rendered
relative to the screen. Changing these parameters does not change the contents of the view window, it simply changes the
location where the view window is drawn. Note that this location is relative to the origin of the Graphics object, and thus it is
subject to the translation attributes of the Graphics object.
ix. For example, if a game uses the top of the screen to display the current score, the view window may be rendered at (17, 17) to
provide enough space for the score.
Constructor Summary
LayerManager()
Creates a new LayerManager.

Method Summary
void append(Layer l)
Appends a Layer to this LayerManager.
Layer getLayerAt(int index)
Gets the Layer with the specified index.
int getSize()
Gets the number of Layers in this LayerManager.

3
void insert(Layer l, int index)
Inserts a new Layer in this LayerManager at the specified index.
void paint(Graphics g, int x, int y)
Renders the LayerManager's current view window at the specified location.
void remove(Layer l)
Removes the specified Layer from this LayerManager.
void setViewWindow(int x, int y, int width, int height)
Sets the view window on the LayerManager.

TiledLayer
i. Declaration:
public class TiledLayer extends Layer
ii. A TiledLayer is a visual element composed of a grid of cells that can be filled with a set of tile images. This class allows
large virtual layers to be created without the need for an extremely large Image. This technique is commonly used in 2D
gaming platforms to create very large scrolling backgrounds,
iii. Tiles
 The tiles used to fill the TiledLayer's cells are provided in a single Image object which may be mutable or immutable. The
Image is broken up into a series of equally-sized tiles; the tile size is specified along with the Image.
 As shown in the figure below, the same tile set can be stored in several different arrangements depending on what is the
most convenient for the game developer.

 Each tile is assigned a unique index number. The tile located in the upper-left corner of the Image is assigned an index of 1.
The remaining tiles are then numbered consecutively in row-major order (indices are assigned across the first row, then the
second row, and so on).
 These tiles are regarded as static tiles because there is a fixed link between the tile and the image data associated with it. A
static tile set is created when the TiledLayer is instantiated; it can also be updated at any time using
the setStaticTileSet(javax.microedition.lcdui.Image, int, int) method.
 In addition to the static tile set, the developer can also define several animated tiles. An animated tile is a virtual tile that is
dynamically associated with a static tile; the appearance of an animated tile will be that of the static tile that it is currently
associated with.
 Animated tiles allow the developer to change the appearance of a group of cells very easily. With the group of cells all filled
with the animated tile, the appearance of the entire group can be changed by simply changing the static tile associated with
the animated tile. This technique is very useful for animating large repeating areas without having to explicitly change the
contents of numerous cells such as areas of water.
 Animated tiles are created using the createAnimatedTile(int) method, which returns the index to be used for the new
animated tile. The animated tile indices are always negative and consecutive, beginning with -1. Once created, the static tile
associated with an animated tile can be changed using the setAnimatedTile(int, int) method.
iv. Cells
 The TiledLayer's grid is made up of equally sized cells; the number of rows and columns in the grid are specified in the
constructor, and the physical size of the cells is defined by the size of the tiles.

4
 The contents of each cell is specified by means of a tile index; a positive tile index refers to a static tile, and a negative tile
index refers to an animated tile. A tile index of 0 indicates that the cell is empty; an empty cell is fully transparent and
nothing is drawn in that area by the TiledLayer. By default, all cells contain tile index 0.
 The contents of cells may be changed using setCell(int, int, int) and fillCells(int, int, int, int,
int). Several cells may contain the same tile; however, a single cell cannot contain more than one tile. The following
example illustrates how a simple background can be created using a TiledLayer.

 In this example, the area of water is filled with an animated tile having an index of -1, which is initially associated with
static tile 5. The entire area of water may be animated by simply changing the associated static tile using
setAnimatedTile(-1, 7).

v. Rendering a TiledLayer
 A TiledLayer can be rendered by manually calling its paint method; it can also be rendered automatically using a
LayerManager object.
 The paint method will attempt to render the entire TiledLayer subject to the clip region of the Graphics object; the upper
left corner of the TiledLayer is rendered at its current (x,y) position relative to the Graphics object's origin. The rendered
region may be controlled by setting the clip region of the Graphics object accordingly.

Constructor Summary
TiledLayer(int columns, int rows, Image image, int tileWidth, int tileHeight)
Creates a new TiledLayer.

Method Summary
int createAnimatedTile(int staticTileIndex)
Creates a new animated tile and returns the index that refers to the new animated tile.
void fillCells(int col, int row, int numCols, int numRows, int tileIndex)
Fills a region cells with the specific tile.
int getAnimatedTile(int animatedTileIndex)
Gets the tile referenced by an animated tile.
int getCell(int col, int row)
Gets the contents of a cell.
int getCellHeight()
Gets the height of a single cell, in pixels.
int getCellWidth()
Gets the width of a single cell, in pixels.
int getColumns()
Gets the number of columns in the TiledLayer grid.
int getRows()
Gets the number of rows in the TiledLayer grid.
void paint(Graphics g)
Draws the TiledLayer.
void setAnimatedTile(int animatedTileIndex, int staticTileIndex)
Associates an animated tile with the specified static tile.

5
void setCell(int col, int row, int tileIndex)
Sets the contents of a cell.
void setStaticTileSet(Image image, int tileWidth, int tileHeight)
Change the static tile set.

Class Sprite
i. Declaration:
public class Sprite extends Layer

ii. A Sprite is basic animated Layer that can display one of several graphical frames. The frames are all of equal size and are
provided by a single Image object. In addition to animating the frames sequentially, a custom sequence can also be set to
animation the frames in an arbitrary manner.
iii. The Sprite class also provides various transformations (flip and rotation) and collision detection methods that simplify the
implementation of a game's logic.
iv. As with all Layer subclasses, a Sprite's location can be changed and it can also be made visible or invisible.
v. Sprite Frames
 The raw frames used to render a Sprite are provided in a single Image object, which may be mutable or immutable.
 If more than one frame is used, the Image is broken up into a series of equally-sized frames of a specified width and height.
As shown in the figure below, the same set of frames may be stored in several different arrangements depending on what is
the most convenient for the game developer.

 Each frame is assigned a unique index number. The frame located in the upper-left corner of the Image is assigned an index
of 0. The remaining frames are then numbered consecutively in row-major order (indices are assigned across the first row,
then the second row, and so on). The method getRawFrameCount() returns the total number of raw frames.
vi. Frame Sequence
 A Sprite's frame sequence defines an ordered list of frames to be displayed. The default frame sequence mirrors the list of
available frames, so there is a direct mapping between the sequence index and the corresponding frame index.
 This also means that the length of the default frame sequence is equal to the number of raw frames. For example, if a Sprite
has 4 frames, its default frame sequence is {0, 1, 2, 3}.
 The developer must manually switch the current frame in the frame sequence. This may be accomplished by
calling setFrame(int), prevFrame(), or nextFrame().
 Note that these methods always operate on the sequence index, they do not operate on frame indices; however, if the default
frame sequence is used, then the sequence indices and the frame indices are interchangeable.
 If desired, an arbitrary frame sequence may be defined for a Sprite. The frame sequence must contain at least one element,
and each element must reference a valid frame index.
 By defining a new frame sequence, the developer can conveniently display the Sprite's frames in any order desired; frames
may be repeated, omitted, shown in reverse order, etc.

6
 For example, the diagram below shows how a special frame sequence might be used to animate a mosquito. The frame
sequence is designed so that the mosquito flaps its wings three times and then pauses for a moment before the cycle is
repeated.

 By calling nextFrame() each time the display is updated, the resulting animation.
vii. Reference Pixel
 Being a subclass of Layer, Sprite inherits various methods for setting and retrieving its location such
as setPosition(x,y), getX(), and getY(). These methods all define position in terms of the upper-left corner of the
Sprite's visual bounds.
 However, in some cases, it is more convenient to define the Sprite's position in terms of an arbitrary pixel within its frame,
especially if transforms are applied to the Sprite.
 Therefore, Sprite includes the concept of a reference pixel. The reference pixel is defined by specifying its location in the
Sprite's untransformed frame using defineReferencePixel(x,y).
 By default, the reference pixel is defined to be the pixel at (0,0) in the frame. If desired, the reference pixel may be defined
outside of the frame's bounds.
 In this example, the reference pixel is defined to be the pixel that the monkey appears to be hanging from

7
 getRefPixelX() and getRefPixelY() can be used to query the location of the reference pixel in the painter's coordinate
system.
 The developer can also use setRefPixelPosition(x,y) to position the Sprite so that reference pixel appears at a
specific location in the painter's coordinate system. These methods automatically account for any transforms applied to the
Sprite.
 In this example, the reference pixel's position is set to a point at the end of a tree branch; the Sprite's location changes so that
the reference pixel appears at this point and the monkey appears to be hanging from the branch:

viii. Sprite Transforms


 Various transforms can be applied to a Sprite. The available transforms include rotations in multiples of 90 degrees, and
mirrored (about the vertical axis) versions of each of the rotations. A Sprite's transform is set by
calling setTransform(transform).
 When a transform is applied, the Sprite is automatically repositioned such that the reference pixel appears stationary in the
painter's coordinate system. Thus, the reference pixel effectively becomes the center of the transform operation.
 Since the reference pixel does not move, the values returned by getRefPixelX() and getRefPixelY() remain the same;
however, the values returned by getX() and getY() may change to reflect the movement of the Sprite's upper-left corner.
 Referring to the monkey example once again, the position of the reference pixel remains at (48, 22) when a 90 degree
rotation is applied, thereby making it appear as if the monkey is swinging from the branch.
ix. Sprite Drawing
 Sprites can be drawn at any time using the paint(Graphics) method. The Sprite will be drawn on the Graphics object
according to the current state information maintained by the Sprite (i.e. position, frame, visibility).
 Erasing the Sprite is always the responsibility of code outside the Sprite class.
 Sprites can be implemented using whatever techniques a manufacturers wishes to use (e.g hardware acceleration may be
used for all Sprites, for certain sizes of Sprites, or not at all).
 For some platforms, certain Sprite sizes may be more efficient than others; manufacturers may choose to provide developers
with information about device-specific characteristics such as these.

8
Field Summary
static int TRANS_MIRROR
Causes the Sprite to appear reflected about its vertical center.
static int TRANS_MIRROR_ROT180
Causes the Sprite to appear reflected about its vertical center and then rotated clockwise by 180
degrees.
static int TRANS_MIRROR_ROT270
Causes the Sprite to appear reflected about its vertical center and then rotated clockwise by 270
degrees.
static int TRANS_MIRROR_ROT90
Causes the Sprite to appear reflected about its vertical center and then rotated clockwise by 90
degrees.
static int TRANS_NONE
No transform is applied to the Sprite.
static int TRANS_ROT180
Causes the Sprite to appear rotated clockwise by 180 degrees.
static int TRANS_ROT270
Causes the Sprite to appear rotated clockwise by 270 degrees.
static int TRANS_ROT90
Causes the Sprite to appear rotated clockwise by 90 degrees.

Constructor Summary

9
Sprite(Image image)
Creates a new non-animated Sprite using the provided Image.
Sprite(Image image, int frameWidth, int frameHeight)
Creates a new animated Sprite using frames contained in the provided Image.
Sprite(Sprite s)
Creates a new Sprite from another Sprite.

Method Summary
boolean collidesWith(Image image, int x, int y, boolean pixelLevel)
Checks for a collision between this Sprite and the specified Image with its upper left corner at the
specified location.
boolean collidesWith(Sprite s, boolean pixelLevel)
Checks for a collision between this Sprite and the specified Sprite.
boolean collidesWith(TiledLayer t, boolean pixelLevel)
Checks for a collision between this Sprite and the specified TiledLayer.
void defineCollisionRectangle(int x, int y, int width, int height)
Defines the Sprite's bounding rectangle that is used for collision detection purposes.
void defineReferencePixel(int x, int y)
Defines the reference pixel for this Sprite.
int getFrame()
Gets the current index in the frame sequence.
int getFrameSequenceLength()
Gets the number of elements in the frame sequence.
int getRawFrameCount()
Gets the number of raw frames for this Sprite.
int getRefPixelX()
Gets the horizontal position of this Sprite's reference pixel in the painter's coordinate system.
int getRefPixelY()
Gets the vertical position of this Sprite's reference pixel in the painter's coordinate system.
void nextFrame()
Selects the next frame in the frame sequence.
void paint(Graphics g)
Draws the Sprite.
void prevFrame()
Selects the previous frame in the frame sequence.
void setFrame(int sequenceIndex)
Selects the current frame in the frame sequence.
void setFrameSequence(int[] sequence)
Set the frame sequence for this Sprite.
void setImage(Image img, int frameWidth, int frameHeight)
Changes the Image containing the Sprite's frames.
void setRefPixelPosition(int x, int y)
Sets this Sprite's position such that its reference pixel is located at (x,y) in the painter's coordinate
system.
void setTransform(int transform)
Sets the transform for this Sprite.

10