• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Scmad Chapter07
 

Scmad Chapter07

on

  • 1,694 views

Chapter 07 - MIDP Util and Game API

Chapter 07 - MIDP Util and Game API
This material is only for studies purposes

Statistics

Views

Total Views
1,694
Views on SlideShare
1,671
Embed Views
23

Actions

Likes
0
Downloads
48
Comments
0

5 Embeds 23

http://www.mobideia.com 10
http://mobideia.blogspot.com 5
http://scmad.wordpress.com 3
http://mobideia.blogspot.com.br 3
http://webcache.googleusercontent.com 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Scmad Chapter07 Scmad Chapter07 Presentation Transcript

  • By Marcel Caraciolo http://mobideia.blogspot.com Chapter 07– MIDP: Timers and GameCanvas SCMAD Certification 45mm 61mm
  • Agenda
    • MIDP - Util
      • Timers
      • User Interface API Classes
      • MIDP Classes
    • MIDP – Game API
      • Game User Interface
      • GameCanvas
      • Sprite
      • Layer
      • TiledLayer
      • LayerManager
  • MIDP: java.util.Timer
    • Timer: Registers an event to be executed at a specific time
    • on a different Thread
    • It can be scheduled to run:
      • After some time ( schedule(task,delay) )
      • At a specific time ( schedule(task,time) )
      • After some time, then on a regular interval ( schedule(task,delay,period) )
      • At a specific time, then on a regular interval ( schedule(task,firstTime,period) )
    • Every timer has a single Thread for all its executions, so if
    • an event execution time is greater than the interval time,
    • then the next execution is impacted
  • MIDP: java.util.Timer
    • It may be canceled with cancel()
    • Execution can be:
      • Fixed-delay: Scheduled with schedule(). The ‘n+1’ run is done “period” milliseconds after the beginning of “n” execution (delay on the beginning of an execution influences all the next, and the frequency is changed). Useful for animations and real-time user interaction.
      • Fixed-rate: Scheduled with scheduleAtFixedRate(). Executed is done according to the first one. A delay will make the next events run on a greater schedule to “catch up”.
  • MIDP: java.util.TimerTask
    • Task to be run by a Timer (similar to Thread’s Runnable)
    • You must code the run() abstract method
    • May call cancel() to stop its own timer (will cancel after the following executions, does not influence on its own execution).
  • Timer and TimerTask Example
  • Timer and TimerTask Example
  • MIDP: Font
    • Represents fonts and acts as a factory
    • Static methods:
      • getFont(specifierFont): Returns a font based on the specifier parameter : FONT_INPUT_TEXT (font for input labels) or FONT_STATIC_TEXT (font for labels)
      • getDefaultFont (): Default font system
      • getFont(face,style,size) : factory method:
        • face: FACE_SYSTEM, FACE_MONOSPACE,
        • FACE_PROPORTIONAL
        • style: STYLE_PLAIN, STYLE_BOLD, STYLE_ITALIC,
        • STYLE_UNDERLINED
        • size: SIZE_SMALL, SIZE_MEDIUM, SIZE_LARGE
  • MIDP: Font
    • Instance methods:
      • getHeight(): Height of the font
      • getBaselinePosition(): Distance between top and
      • baseline
      • stringWidth(string): Width of the specifier string
  • MIDP: Image
    • Represents an image and works as a factory:
      • Images are either mutable or immutable, depending on how they were created. Immutable images are usually loaded from binary resources. Mutable images are created black and drawn programmatically. If a mutable image is added to a resource (e.g. an alert or an image item) , a “Snapshot” from the image at this moment is used.
      • Mutable images do not support transparency
      • PNG standard and its transparency must be supported. Additional formats may be supported.
      • You can perform a programmatic double-buffering by creating a mutable image and painting to it first and later painting this image to a canvas.
  • MIDP: Image
    • Static methods:
      • createImage(width,height): Creates a mutable image to be drawn
      • by the application.
      • createImage(Image): Creates a immutable image from any other
      • createImage(name): Creates an image from a specified resource (using getResourceAsStream to resolve the name)
      • createImage(byte[]image_data,imageOffset,imageLength):
      • Creates an image from the byte array.
  • MIDP: Image
    • Static methods:
      • createImage(image,x,y,w,h,transform): Creates an image by “framing” the original and then applying the transformations. Transformations are defined by Sprite.TRANS_* (GAME_API)
      • createImage(inputStream): Creates an image from the stream
      • createRGBImage(rgb[], w, h, processAlpha): Creates an image from the int array on the 0xAARRGGBB format ( AA: transparency)
  • Notes about classes and methods
    • Static methods:
      • Class.getResourceAsStream() may be used to load resources on the jar file, as long these resources are not Java classes.
      • Calling System.exit() throws a SecurityException since the MIDlet life cycle is controlled by the device. Termination requests from the application are made through MIDlet.notifyDestroyed()
    • Instance methods:
      • display.callSerially() executes a code on the user interface thread.
      • It’s really used since UI operations are thread-safe
      • display.getBestImageWidth/Height(imageType): Calculates the size of images shown on LIST_ELEMENT(list) , CHOICE_GROUP_ELEMENT (choice) and ALERT ( alert)
  • Notes about classes and methods
    • Instance methods:
      • display.getBorderStyle(highlighted): Returns the border style ( SOLID/DOTTED) used by the widgets when the element is selected or not.
      • display.getColor(colorSpecifier): Return the color of some part of a component on the platform. You use the following specifiers:
        • COLOR_BACKGROUND, COLOR_FOREGROUND
        • COLOR_HIGHLIGHTED_BACKGROUND
        • COLOR_HIGHLIGHTED_FOREGROUND
        • COLOR_BORDER, COLOR_HIGHLIGHTED_BORDER
  • Notes about classes and methods
    • Instance methods:
      • display.numAlphaLevels(): Number of transparency levels supported. Devices shall support at least two levels (totally transparent and totally opaque)
    • Exceptions and most exceptions have only two
    • constructors: A non-args constructor and one with string
    • (message) parameter
    • Exceptions are not “nested”
  • Game User Interface
    • Based on low level API. All features from low-level API are present on Game API
    • Classes at javax.microedition.lcdui.game package
  • GameCanvas
    • Extends Canvas. It has the same features with additional features to create real-time games
    • Regular Canvas is based on user-interface events.
    • GameCanvas is based on the game loop:
      • Check inputs
      • Execute logic according to inputs and game state
      • Render outputs
  • GameCanvas
    • GameLoop is expected to execute at a constant rate, and does not depend on user input.
    • Differently from the regular canvas, a GameCanvas has its own buffer. Its Graphics may be used at any moment, not only inside paint() method.
    • Defines no abstract methods, but defines the “(boolean suppressKeyEvents)” constructor. When suppressKeyEvents is true, keyPressed , keyReleased, and keyRepeated methods are not called. This may increase performance.
  • GameCanvas: Methods
    • getGraphics(): Return a graphics to paint on this canvas. Operations on this graphics are not shown until flushGraphics is called. A new instance of graphics is created EVERY TIME this method is called, so this call shall not be placed inside the game loop (it shall be called only once, outside the game loop, and reused for every loop).
    • flushGraphics() and flushGraphics(x,y,w,h): Sends the offscreen buffer to be displayed. Blocks until the operation is finished. When the parameters are informed, only the defined area is painted.
  • GameCanvas: Methods
    • getKeyStates(): Returns an integer (bit mask) with all keys that were pressed since the last time the method was called. This method is expected to be called at every loop. Each bit represents a pressed key. To check if it was pressed, you use the following code:
  • Utility Classes for Graphics
  • Sprite
    • Game elements (usually game characters)
    • Allows showing a sequence of images (to animate the character), transformations (rotating, mirroring), changing the position and collision detection.
  • Sprite
    • Sprite(image,frameWidth,frameHeight): Creates a Sprite from an image. A single image defines a whole frame sequence. Each frame will have a specified size (all frames have the same size). The image width must be multiple of the frameWidth and the same must be true for the frameHeight. Frames may be organized in vertical, horizontal, or in “grid” ordering. Initially the sprite is visible, at (0,0) position, with default framesequence (0,1,2…). On the attached sample (sprite.png), frames are organized as below (the last position (5) is not used by the game):
    • 0 1 2
    • 3 4 5
  • Sprite
    • Sprite(image): Same as calling Sprite (image, image.getWidth(), image.getHeight()). Creates a Sprite with a single frame, with the frame size
    • Sprite(sprite): Duplicates the sprite.
  • Sprite: methods
    • paint(Graphics): Renders the current frame on the informed Graphics based on its position and state.
    • defineReferencePixel(x,y): Defines a reference point by which TRANSFORMATIONS will be based on when applied to the frame. This point may be placed outside the area frame’s area. By default it’s (0,0).
    • setRefPixel(x,y): Place the frame by its REFERENCE POINT at (x,y).
  • setRefPixelPosition example
  • Sprite: methods
    • setFrameSequence(sequence[]): Defines the frame sequence which will be used when animating the sprite. Default is (0,1,2,…).
    • nextFrame(), prevFrame(): Switches to the next or previous frame. The frame list is circular (i.e. when nextFrame is called at the last frame the index returns to the first).
    • setFrame(sequenceIndex): Set i as current frame. The sequence index, not the frame index shall be used.
    • getFrameSequenceLength(): Frame sequence length.
    • getRawFrameCount(): Number of frames available on the sprite.
  • Sprite: setFrame(int sequenceIndex)
  • Sprite: methods
    • setTransform(transform): Applies a transformation.
      • TRANS_NONE : Does nothing
      • TRANS_ROT90 : Rotates 90 degrees clockwise
      • TRANS_ROT180 : Rotates 180 degrees clockwise
      • TRANS_ROT270 : Rotates 270 degrees clockwise
      • TRANS_MIRROR : Mirrors on the vertical axis
      • TRANS_MIRROR_ROT90: Mirrors and then rotates
      • TRANS_MIRROR_ROT180 : Mirrors and then rotates
      • TRANS_MIRROR_ROT270: Mirrors and then rotates
    • Transformations are based on the reference point. They
    • are not acumulative and cannot be combined (e.g. calling
    • TRANS_ROT90 twice will not rotate the object with 180
    • degrees, but only with 90).
  • setTransform Example
  • Sprite: methods
    • collidesWith(sprite,pixelLevel),
    • collidesWith(tiledLayer, pixelLevel),
    • collidesWith(image,x,y,pixelLevel)
      • Checks a collision between two objects. When pixelLevel is used, the objects will only colide if opaque pixels collide (which is much slower than checking rectangle collisions). Collisions only happen if both objects are visible. A collision can be checked between two sprites, between a sprite and a tiledLayer, and between a sprite and any image at (x,y).
  • Sprite: methods
    • defineCollisionRectangle(x,y,width,height):
      • Defines the rectangle where collisions are considered. By default, it covers the whole frame size. For instance, if you have a jet that leaves some fog, the collision rectangle shall comprehend only the plane itself, and not the fog. Transformations applied to the sprite are also applied to the collision rectangle.
  • Sprite: Collisions
  • Layer
    • Sprite extends Layer
    • Layer are “objects placed on the game screen”:
      • They all have position and size
      • Can be hidden
      • Can be painted on a graphics
    • A Layer’s position is always considered from the object’s upper left corner. For Sprites a reference point is also defined to customize transformations and positioning.
  • Layer
    • setPosition: Defines the layer position
    • move(dx,dy): Moves the position
    • getX(), getY(): Gets the position
    • getWidth(), getHeight(): Gets the size
    • setVisible(visible): Visits objects are rendered and collide. Invisible objects are not rendered and do not collide.
    • paint(Graphics): Renders the layer on a graphics, if the layer is visible.
  • TiledLayer
    • It extends Layer
    • Defines a grid where frames are applied (like wall tiles): Useful for maps and backgrounds.
    • .Constructor: TiledLayer(columns,rows,image,tileWidth,tileHeight): Creates a grid with (columns x rows) tiles, and define frames with image/tileWidth/tileHeight. The same logic used to define frames for Sprites is used here. Every cell has the same size, which is the same as the tile’s size ( tileWidth, tileHeight).
  • TiledLayer
  • TiledLayer
    • After the object is created, all its cells are blank. Tiles are set with setCell () and fillCells ()
    • Like with Sprites, each frame has an index, but the indexes start at 1, while the Sprites they begin at 0. This is done because cells may be blank (setting 0 as index) and tiles can be animated (using negative indexes).
    • A tile may be static or animated. A static cell is set calling setCell with the tile’s index (positive value). Animated tiles are created by calling createAnimateTile , which returns the animated tile index. Indexes start with -1, and the indexes decreases as tiles are created. Updating the animated tile must be done manually by calling setAnimatedTile
  • TiledLayer: Methods
    • setCell(col,row, tileIndex): Places a tile on a cell. If it’s greater than zero, a static cell is used. If it’s smaller than zero, an animated tile is used. If it’s zero, the cell is left blank.
    • fillCells(col,row,numCols,numRows,tileIndex): Similar to setCell, but fills a cell area
    • getCellWidth(), getCellHeight(): Gets the tile size
    • getColumns(), getRows(): Gets the grid size
    • paint(Graphics): Renders the grid on the graphics, on the position inherited from the Layer.
  • TiledLayer: Methods
    • createAnimatedTile(staticTileIndex): Creates an animated tile and sets its first index to be shown.
    • setAnimatedTile(animatedTileIndex,staticTileIndex): Updates the frame on an animated tile previously created
    • getAnimatedTile(animatedTileIndex) :Returns which static tile is currently associated with the animated tile
    • setStaticTileSet(image,tileWidth, tileHeight): Changes the tile image. Similar to creating a new tiled layer with the same grid size
  • TiledLayer: Methods
  • LayerManager
    • Controls a list of layers (sprite and tiled layers). Simplifies the rendering process controlling the sequence of objects that will be rendered. Elements are organized on a list. Smaller indexes are closer to the user, and append() adds to the END of the list.
    • Besides the layer list, it has a view window (x,y,w,h). It defines a window over which rendering is applied. This may be used to perform scrolling. (x,y) defines the rendering origin while the width and height define the window size.
    • A layer can not be placed twice on the same manager. When a item is re-inserted, it’s first removed and then set to the defined position.
  • LayerManager: Methods
    • append(layer): Puts an object on the last position (i.e. most far from the user).
    • insert(layer,index): Inserts an object at ‘index’ position. The following objects are “pushed back”
    • getLayerAt(index): Returns the object at the specified position
    • getSize(): Returns the number of layers
  • LayerManager: Methods
    • remove(layer): Removes a layer
    • setViewWindow(x,y,width,height): Defines the region from the “whole scenery” that will be rendered
    • paint(graphics,x,y): Renders all screen, on the correct sequence over the graphics. The (x,y) parameters define where the manager will be rendered on the graphics.
  • LayerManager: Example
  • Example Codes
    • Some examples and MIDlets samples are available for reference and studying at this link:
      • http://www.dsc.upe.br/~mpc/chapter7.rar
    • The source codes include:
      • BGameMIDllet
      • GameMIDlet
      • LayerManagerMIDlet
  • Future Work
    • Next Chapter:
      • MIDP – RMS
        • Record Management System
        • Record Store
        • RecordListener
        • RecordEnumeration
        • RecordComparator
        • RecordFilter
        • Exceptions
  • References
    • ALVES F. Eduardo. SCMAD Study Guide,
    • 27/04/2008.
    • JAKL Andreas, Java Platform, Micro Edition Part
    • 01 slides, 12/2007.
    • Sun Certification Mobile Application Developer
    • Website: [http://www.sun.com/training/certification/java/scmad.xml].