j2me_07_2

34
LẬP TRÌNH J2ME CHO THIẾT BỊ DI LẬP TRÌNH J2ME CHO THIẾT BỊ DI ĐỘNG ĐỘNG PHẦN 2 PHẦN 2 No love no life

Upload: sdfg

Post on 11-Nov-2015

3 views

Category:

Documents


0 download

DESCRIPTION

abc

TRANSCRIPT

  • No love no lifeLP TRNH J2ME CHO THIT B DI NGPHN 2

  • 3.Cc thnh phn giao din mc thp ca ng dng MIDP Cc hm API cp cao cho ta to ra giao din cc ng dng theo chun, cc hm API cp thp cho ta th hin cc tng ca mnh. Canvas v Graphics l 2 lp chnh ca cc hm API cp thp. Bn lm tt c cc cng vic bng tay. Canvas l mt khung v m ngi pht trin v ln thit b trnh by v x l s kin. Lp Graphics cung cp cc cng c v nh drawRoundRect() v drawString() Lp Canvas:cung cp mt khung v to giao din ty bin ngi dng. a s cc phng thc trong lp ny x l s kin, v nh v chui ln thit b hin th. Trong phn ny s bao gm cc mc: H thng ta To i tng Canvas V ln trn i tng Canvas X l cc s kin hnh ng X l cc s kin phm nhn X l s kin hnh ng ca Game X l s kin con tr

  • H thng trc ta , to mt i tng Canvas H ta cho lp Canvas: tm ta l im tri trn ca thit b. Tr x tng dn v phi, tr y tng dn khi xung di. dy bt v l mt im nh.Cc phng thc sau y s gip xc nh chiu rng v chiu cao ca canvas: int getWidth(): xc nh chiu rng ca canvas int getHeight (): xc nh chiu cao ca canvasu tin to ra mt lp tha k t lp Canvas class TestCanvas extends Canvas implements CommandListener { private Command cmdExit; ... display = Display.getDisplay(this); cmdExit = new Command("Exit", Command.EXIT, 1); addCommand(cmdExit); setCommandListener(this); ... protected void paint(Graphics g) { // Draw onto the canvas g.setColor(255, 255, 255); // Set background color to white g.fillRect(0, 0, getWidth(), getHeight()); // Fill the entire canvas } } TestCanvas canvas = new TestCanvas(this);Phng thc paint ca lp Canvas cho php bn v cc hnh dng, v nh, xut chui

  • S kin hnh ng Mt Canvas c th x l cc Command. Chng ta c th x l cc s kin Command trn thnh phn Canvas cung cch nh cc thnh phn khcM phm Trng hp x l cc hnh ng ca cc phm mm, mt Canvas c th truy cp n 12 m phm. Nhng m ny c m bo lun lun c trn bt k cc thit b MIDP no KEY_NUM0 KEY_NUM1 KEY_NUM2 KEY_NUM3 KEY_NUM4 KEY_NUM5 KEY_NUM6 KEY_NUM7 KEY_NUM8 KEY_NUM9 KEY_STAR KEY_POUND Nm phng thc x l cc m phm l: void keyPressed(int keyCode); void keyReleased(int keyCode); void keyRepeat(int keyCode);String getKeyName(int keyCode);V du sau: Xu ly cac phim, viet ra ma phim KeyEvents, viet ra dung ham getKeyname() - KeyCodes

  • Cc hnh ng trong x l cc tr chi MIDP thng c s dng to cc tr chi trn nn Java. Cc hng s sau c nh ngha x l cc s kin c lin quan n tr chi trong MIDP UP DOWN LEFT RIGHT FIRE GAME_A GAME_B GAME_C GAME_D n gin th cc gi tr ny c nh x thnh cc phm mi tn ch hng ca thit b, nhng khng phi tt c cc thit b di ng u c nhng gi tr ny. Nu mt thit b di ng thiu cc phm mi tn th cc hnh ng ca tr chi s c nh x vo cc nt bm, v d phm tri c nh x vo phm s 2, phm phi c nh x vo phm s 5, v c tip tc nh th.

  • Xc nh cc hnh ng ca tr chi on m sau m t cch xc nh cc hnh ng ca tr chi gi cc phng thc thch hp da trn cc hnh ng xy raprotected void keyPressed(int keyCode) { int gameAction = getGameAction(keyCode); switch(gameAction) { case UP: mMessage = "UP"; break; case DOWN: mMessage = "DOWN"; break; case LEFT: mMessage = "LEFT"; break; case RIGHT: mMessage = "RIGHT"; break; case FIRE: mMessage = "FIRE"; break; case GAME_A: mMessage = "GAME_A"; break; case GAME_B: mMessage = "GAME_B"; break; case GAME_C: mMessage = "GAME_C"; break; case GAME_D: mMessage = "GAME_D"; break; default: mMessage = ""; break; } }V d: hin th cc phm x l s kin - KeyMIDlet

  • Lp Graphics Chng ta s dng i tng Graphics v ln mt Canvas. boolean isColor(); //thit b c h tr hin th mu khng? int numColors(); //gi xc nh s mu Mc nh (DefaultColorPhone) l 4096 colors (0x1000)isColor=true; colorCount=0x1000; Cc phng thc ly v mu v thit lp mu:void setColor(int RGB); //t mu hin thi qua gi tr RGB void setColor(int red, int green, int blue); // t mu, cc gi tr red,green.. t 0-255 int getColor(); // tr v mu hin thi int getBlueComponent(); // tr v thnh phn mu xanh da tri ca mu hin thi 0-255 int getGreenComponent();// tr v thnh phn mu lc ca mu hin thi 0-255 int getRedComponent(); // tr v thnh phn mu ca mu hin thi 0-255 void setGrayScale(int value); // t mc xmint getGrayScale(); //tr v gi tr xm t 0-255 V d: BLACK=0; WHITE=0xffffff; RED=0xf96868; GREY=0xc6c6c6; LT_GREY=0xe5e3e3; Hay int red = 0, green = 128, blue = 255;Sau t mu: g.setColor(WHITE); hoc g.setColor(red, green, blue);

  • V cung v hnh ch nht Chn nt khi v ng thng, cung v hnh ch nht trn thit b hin th. int getStrokeStyle(); //tr v kiu nt v void setStrokeStyle(int style); // t kiu nt v Hai kiu nt v c nh ngha trong lp Graphics l nt chm, v nt lin g.setStrokeStyle(Graphics.DOTTED); g.setStrokeStyle(Graphics.SOLID);V cung:void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle);void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle);g.drawArc(10, 10, 100, 100, 0, 150); on m trn yu cu v mt cung, cung ny c bao bi mt hnh ch nht c ta im tri trn l (10, 10), chiu rng v chiu di l 100, gc bt u l 0, gc kt thc l 150. V d: VeCungCanvasV hnh ch nhtvoid drawRect(int x, int y, int width, int height);// void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); void fillRect(int x, int y, int width, int height); void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); Hnh ch nht c 4 gc l trn th bn phi xc nh ng knh theo chiu ngang(arcWidth) v ng knh theo chiu dc(arcHeight). V d: VeHinhChuNhat

  • Font ch Cc phng thc dng ca lp Font: Font getFont(int face, int style, int size); Font getFont(int fontSpecifier); Font getDefaultFont(); Mt s thuc tnh ca lp Font FACE_SYSTEM FACE_MONOSPACE FACE_PROPORTIONAL STYLE_PLAIN STYLE_BOLD STYLE_ITALIC STYLE_UNDERLINED SIZE_SMALL SIZE_MEDIUM SIZE_LARGECc tham s kiu dng c th c kt hp thng qua ton t hay. V d Font font = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD | Font.STYLE_ITALIC, Font.SIZE_MEDIUM); Sau khi bn c mt tham chiu n mt i tng Font, bn c th truy vn n xc nh thng tin ca cc thuc tich ca n. V d: FontChuDonGian

  • im neo xc nh ta x, y ca chui k t c hin th, th im neo cho php bn ch ra v tr mun t ta x, y trn hnh ch nht bao quanh chui k t Chiu ngang LEFT (Bn tri) HCENTER (Chnh gia ca chiu ngang) RIGHT (Bn phi) Chiu dc TOP ( trn) BASELINE (ng thng c s) BOTTOM ( di) S dng im neo phi ch ra ta x, y ca hnh ch nht bao quanh. g.drawString("developerWorks", 0, 0 , Graphics.TOP | Graphics.LEFT);

  • V cc chui k t void drawChar(char character, int x, int y, int anchor); void drawChars(char[] data, int offset, int length, int x, int y, int anchor); void drawString(String str, int x, int y, int anchor);protected void paint(Graphics g) { // Get center of display int xcenter = getWidth() / 2, ycenter = getHeight() / 2; // Choose a font g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALICS, Font.SIZE_MEDIUM)); // Specify the center of the text (bounding box) using the anchor point g.drawString("developerWorks", xcenter, ycenter, Graphics.BASELINE | Graphics.HCENTER); }V d: thay doi Font chu FontChu1Dch chuyn i tng Ve2

  • Cc lp Game trong MIDP 2Vi MIDP 2 th c thm 5 lp:GameCanvas Sprite Layer LayerManager TiledLayerCc lp ny tm trong gi: java.microedition.lcdui.gameChng ta khng dng trc tip lp Layer, v thc cht y l lp tru tng dng trong cc lp Spite, LayerManager v TiledLayer.Lp GameCanvas: khng phi i thc hin keyPressed() v ta c phng thc getKeysState(). C k thut gi l double bufferingbn c th thc hin v off-screen bufferkhi vic copy t buffer ti cc canvas nhanh hn nhiu. C th s dng Graphic t gi hm getGraphics(). flushGraphics() gii phng GraphicsV d ta c vic di chuyn ch x dng GameCanvas ExampleGameCanvas

  • Lp SpriteTrong Game th ho lm nn thnh cng rt ln. Hu ht cc i tng ho c phn loi nh cc dng c bit ca ho gi l cc Sprite. Mt Sprite c th l bullet, monster, enemies, keys v doors v mt vi ci g Cc Sprite c nhn nhiu ln l cc graphic ng, cc graphic ng ny c to nn t cng mt Sprite nhng nhn t cc gc khc nhau. y l mt b Sprite:

    Sprite ConstructorC 3 hm khi to vi lp Sprite Sprite (Image image); // To ra khung Sprite n, khng ng Sprite (Sprite sprite); //To ra Sprite mi t mt Sprite Sprite (Image image,int frameWidth, int frameHeight); //To ra Sprite ng vi t 2 frame tr ln, frameWidth v frameHeight l rng v chiu cao ca 1 Sprite

    Ta c tng rng l 160 pixels, rng ca 1 frame l 32 pixels, chiu cao l 32pixels. Ta c frameWidth v frameHeight l ging nhau cho 1b Sprite (cc Sprite khc th khc nhau). Cc Graphic th bao gm cc Sprite m rng v chiu cao l hng s, v s cc pixel th lin quan n s mu: nu 1pixel l 8-bit, 16-bit, 24-bit th 28=256, 216=65536 mu

  • Sprite Collision, Display Sprite SequenceSprite Collision:collidesWith(Image image, int x, int y, boolean pixelLevel);collidesWith(Sprite sprite, boolean pixelLevel);collidesWidth(TiledLayer tiledLayer, Boolean pixelLevel);Kim tra ng thng qua v tr gc tri trn ca SpriteSprite Sequence:getFrameSequenceLength();//s phn t trong 1dygetFrame();//ch s hin thi ca frame trong dynextFrame();// ch ti frame tip theoprevFrame();// ch ti frame trcsetFrame(int sequenceIndex);//t frame hin thi

  • Sprite TransformsSprite Transforms: bin dng c th to Sprite nh quay, ly i xng setTransform(inttransform); TRANS_NONE0 TRANS_MIRROR_ROT180 1 TRANS_MIRROR 2 TRANS_ROT180 3 TRANS_MIRROR_ROT270 4 TRANS_ROT90 5 TRANS_ROT270 6 TRANS_MIRROR_ROT907 V d: ExampleGameSprite

  • Lp LayerManagerLayerManager qun l cc lp Graphic, th t ca cc lp ging nh chiu th 3 (trc z). Th t 0 l lp gn ngi dng nht.Thm 1 lp : append(Layer layer);private Sprite playerSprite; private Sprite backgroundSprite;private LayerManager layerManager;Image playerImage = Image.createImage("/transparent.png"); playerSprite = new Sprite (playerImage,32,32); Image backgroundImage = Image.createImage("/background.png");backgroundSprite = new Sprite(backgroundImage); layerManager = new LayerManager(); layerManager.append(playerSprite); layerManager.append(backgroundSprite);remove(Layer layer);// loi b mt lpinsert(Layer layer, int index);// thm 1 lppaint(Graphics g, int x, int y); //mun hin th 1 lpV d : ExampleLayerManager

  • LayerManager and Scrolling Backgroundi lc mn hnh nn ln hn mn hnh hin th, lc chng ta phi cun mn hnh. C th cun sang tri, sang phi, ln trn xung di.im bt u l (50,20), ta c th to ra im ng n cun trn mn hnh.if ((keyStates & LEFT_PRESSED) != 0) {if (scnX - 1 > 0) scnX--;}if ((keyStates & RIGHT_PRESSED) != 0) {if (scnX + 1 + 140 < backgroundImage.getWidth()) scnX++;}if ((keyStates & UP_PRESSED)!=0){if (scnY-1>0) scnY--;}if ((keyStates & DOWN_PRESSED)!=0){if (scnY+1+140
  • Lp TiledLayerMt TiledLayer l mt li cc chia ra t 1 nh.V d hnh bn c chia thnh 6 vng, ta ch ra cc Tiled c 32x32 pixel. To nn 1 lp TiledLayer, mi 1 tile ny c nh s (bt u t 1). nh s t tri sang phi ri t trn xung di, TiledLayer(int columns, int rows, Image image, int tileWidth, int tileHeight);C s hng, ct v nh cn chia. rng v cao ca tile setCell(int col, int row, int tileIndex);//t tile vo bc nh v tr col,row v ly nh c tileIndex ( trn l t 1,2,6) getCell(int col, int row);//tr v index ca cell, nu cell l empty tr v 0 getCellHeight();//tr v chiu cao ca mt cell (pixel) getCellWidth(); getColumns();//tr v s ct ca TileLayer getRows(); Ging nh cc Game khc, ta cng gi trc tip hm paint() hay dng LayerManagerlayerManager.paint(g,0,0);

  • V d TiledLayerprivate LayerManager layerManager;private TiledLayer tiledBackground; tiledBackground = initBackground();layerManager = new LayerManager();layerManager.append(tiledBackground);private TiledLayer initBackground() throws Exception { Image tileImages = Image.createImage("/tiles.png"); TiledLayer tiledLayer = new TiledLayer(8,9,tileImages,32,32);int[] map = { 5, 1, 1, 4, 1, 1, 1, 1, 5, 1, 3, 1, 1, 3, 1, 1, 5, 1, 2, 1, 1, 2, 1, 1, 5, 1, 2, 3, 1, 2, 1, 1, 5, 1, 4, 2, 1, 2, 1, 1, 5, 1, 1, 4, 1, 2, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, }; V d : ExampleTiledLayerfor (int i=0; i < map.length; i++) { int column = i % 8; int row = (i - column) / 8; tiledLayer.setCell(column,row,map[i]); } return tiledLayer; }

  • Animated Cells (1)Animated Cell l tp hp ng ca cc Tile tnh. Cc Animated Tile l cc ch s m.int createAnimatedTile(int staticTileIndex);To ra Animated Tile tr v ch s m (-1,-2..)setAnimatedtile(int animatedTileIndex, int staticTileIndex); kt hp Animated Tile vi stattic tileTo nn: private TiledLayer initBackground() throws Exception { Image tileImages = Image.createImage("/tiles.png"); TiledLayer tiledLayer = new TiledLayer(8,9,tileImages,32,32); int[] map = { 5, 1, 1, 4, 1, 1, 1, 1, 5, 1, 3, 1, 1, 3, 1, 1, 5, 1, 2, 1, 1, 2, 1, 1, 5, 1, 2, 3, 1, 2, 1, 1, 5, 1, 4, 2, 1, 2, 1, 1, 5, 1, 1, 4, 1, 2, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1}; for (int i=0; i < map.length; i++) { int column = i % 8; int row = (i - column) / 8; tiledLayer.setCell(column,row,map[i]); } animatedIdx = tiledLayer.createAnimatedTile(5); tiledLayer.setCell(1,1,animatedIdx); return tiledLayer; }}

  • Animated Cells (2)public ExampleGameCanvas() throws Exception { super(true); width = getWidth(); height = getHeight(); currentX = width / 2; currentY = height / 2; delay = 20; tiledBackground = initBackground(); layerManager = new LayerManager(); layerManager.append(tiledBackground); }public void run() { Graphics g = getGraphics(); while (isPlay == true) { input(); drawScreen(g); try { Thread.sleep(delay); } catch (InterruptedException ie) {} }}private boolean switchTile;private int animatedIdx;if (switchTile) { tiledBackground.setAnimatedTile(animatedIdx,3); } else { tiledBackground.setAnimatedTile(animatedIdx,4); }switchTile = !switchTile; layerManager.paint(g,0,0);.animatedIdx = tiledLayer.createAnimatedTile(5);tiledLayer.setCell(1,1,animatedIdx);

    V d: ExampleTiledLayerAnimated

  • V d : Animation (1)To Sprite tnh: AnimationSprite.javaimport javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;public class AnimationSprite extends Sprite {public AnimationSprite(Image image, int frameWidth, int frameHeight) {super(image, frameWidth, frameHeight); } }Chy Animation:public void start() {running = true;Thread t = new Thread(this);t.start(); }public void run() {Graphics g = getGraphics();while (running) {drawDisplay(g);Try {Thread.sleep(150); }catch (InterruptedException ie) {System.out.println("Thread exception"); } }} Draw frameprivate void drawDisplay(Graphics g){// Animated sprite, show next frame in sequencespSpiral.nextFrame();lmgr.paint(g, 0, 0); // Paint layersflushGraphics();}

  • V d : Animation (2), AnimationCanvas.javaimport javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;public class AnimationCanvas extends GameCanvas implements Runnable {private static final int FRAME_WIDTH = 57;private static final int FRAME_HEIGHT = 53;private AnimationSprite spSpiral; // Animated spriteprivate LayerManager lmgr; // Manage layersprivate boolean running = false; // Thread running?public AnimationCanvas() {super(true);Try {spSpiral = new AnimationSprite(Image.createImage("/spiral.png"),FRAME_WIDTH, FRAME_HEIGHT);spSpiral.defineReferencePixel(FRAME_WIDTH / 2, FRAME_HEIGHT / 2);spSpiral.setRefPixelPosition(getWidth() / 2, getHeight() / 2);

  • V d : Animation (3)lmgr = new LayerManager();lmgr.append(spSpiral); }catch (Exception e) {System.out.println("Unable to read PNG image"); }}public void start() {running = true;Thread t = new Thread(this);t.start(); }public void run() {Graphics g = getGraphics();while (running) {drawDisplay(g);Try {Thread.sleep(150); }catch (InterruptedException ie) {System.out.println("Thread exception");} } }private void drawDisplay(Graphics g){spSpiral.nextFrame(); lmgr.paint(g, 0, 0);flushGraphics();}public void stop(){running = false;}}

  • V d : Animation (4), Animation.javaimport javax.microedition.midlet.*;import javax.microedition.lcdui.*;public class Animation extends MIDlet implements CommandListener {private Display display; // Reference to displayprivate AnimationCanvas canvas; // Game canvasprivate Command cmExit; // Exit commandpublic Animation() {display = Display.getDisplay(this);cmExit = new Command("Exit", Command.EXIT, 1);if ((canvas = new AnimationCanvas()) != null) {canvas.addCommand(cmExit);canvas.setCommandListener(this); }}public void startApp() {if (canvas != null) {display.setCurrent(canvas);canvas.start(); } }public void pauseApp() {}public void destroyApp(boolean unconditional) {canvas.stop(); }public void commandAction(Command c, Displayable s) {if (c == cmExit) {destroyApp(true);notifyDestroyed();} } }

  • V d: Collisions, AppleSprite.java, CubeSprite.java v StarSprite.java

  • V d: Collisions, AnimatedSprite.javaimport javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;public class AnimatedSprite extends Sprite {public AnimatedSprite(Image image, int frameWidth, int frameHeight) {super(image, frameWidth, frameHeight); // Call sprite constructor }}Move Sprite: MoveLeft(), moveRight(int w), moveUp(), moveDown(int h)Khi mun Move Sprite, ta phi lu li v tr hin thi saveXY() trong trng hp Sprite ng vi Sprite khc, sau tr v v tr trc restoreXY()private void saveXY() {// Save last positionprevious_x = x;previous_y = y;}public void restoreXY() {x = previous_x;y = previous_y;setPosition(x, y);}

  • V d: Collisions, Di chuyn Sprite:ManSprite.java (1)import javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;public class ManSprite extends Sprite{private int x = 0, y = 0, // Current x/yprevious_x, previous_y; // Last x/yprivate static final int MAN_WIDTH = 25; // Width in pixelsprivate static final int MAN_HEIGHT = 25; // Height in pixelspublic ManSprite(Image image){// Call sprite constructorsuper(image);}public void moveLeft() {if (x > 0) { // If the man will not hit the left edge... saveXY();// If less than 3 from left, set to zero,// otherwise, subtract 3 from current locationx = (x < 3 ? 0 : x - 3);setPosition(x, y);}}

  • V d: Collisions, Di chuyn Sprite:ManSprite.java (2)public void moveRight(int w) {if ((x + MAN_WIDTH) < w) { // If the man will not hit the right edge...saveXY();// If current x plus width of ball goes over right side,// set to rightmost position. Otherwise add 3 to current location.x = ((x + MAN_WIDTH > w) ? (w - MAN_WIDTH) : x + 3);setPosition(x, y); } }public void moveUp() {if (y > 0) {// If the man will not hit the top edge...saveXY();// If less than 3 from top, set to zero,// otherwise, subtract 3 from current location.y = (y < 3 ? 0 : y - 3);setPosition(x, y);} }

  • V d: Collisions, Di chuyn Sprite:ManSprite.java (3)public void moveDown(int h){if ((y + MAN_HEIGHT) < h) { // If the man will not hit the bottom edge...saveXY();// If current y plus height of ball goes past bottom edge,// set to bottommost position. Otherwise add 3 to current location.y = ((y + MAN_WIDTH > h) ? (h - MAN_WIDTH) : y + 3);setPosition(x, y); }}private void saveXY() {// Save last positionprevious_x = x;previous_y = y; }public void restoreXY() {x = previous_x;y = previous_y;setPosition(x, y);}}

  • V d: Collisions, CollisionCanvas.java (1)Tr v phm n:private void checkForKeys() {int keyState = getKeyStates();if ((keyState & LEFT_PRESSED) != 0) {spMan.moveLeft();}else if ((keyState & RIGHT_PRESSED) != 0) {spMan.moveRight(canvas_width);}else if ((keyState & UP_PRESSED) != 0) {spMan.moveUp();}else if ((keyState & DOWN_PRESSED) != 0) {spMan.moveDown(canvas_height);}} Tr v true nu c ng private boolean checkForCollision() {if (spMan.collidesWith(spSpiral, true) ||spMan.collidesWith(spApple, true) ||spMan.collidesWith(spCube, true) ||spMan.collidesWith(spStar, true)) {// Upon collision, restore the last x/y positionspMan.restoreXY();return true;}elsereturn false;}

  • V d: Collisions, CollisionCanvas.java (2)Lp CollisionCanvaspublic class CollisionCanvas extends GameCanvas implements Runnable {private AnimatedSprite spSpiral; // Animated spriteprivate static final int FRAME_WIDTH = 57; // Width of 1 frameprivate static final int FRAME_HEIGHT = 53; // Height of 1 frameprivate int canvas_width, canvas_height; // Save canvas infoprivate ManSprite spMan; // Man (moveable)private AppleSprite spApple; // Apple (stationary)private CubeSprite spCube; // Cube "private StarSprite spStar; // Star "private LayerManager lmgr; // Manage all layersprivate boolean running = false; // Thread running?private Collisions midlet; // Reference to main midlet

  • V d: Collisions, CollisionCanvas.java (3)public CollisionCanvas(Collisions midlet) { // Gamecanvas constructorsuper(true);this.midlet = midlet;Try {// Nonanimated spritesspMan = new ManSprite(Image.createImage("/man.png"));spApple = new AppleSprite(Image.createImage("/apple.png"));spCube = new CubeSprite(Image.createImage("/cube.png"));spStar = new StarSprite(Image.createImage("/star.png"));// Animated spritespSpiral = new AnimatedSprite(Image.createImage("/spiral.png"),FRAME_WIDTH, FRAME_HEIGHT);// Change the reference pixel to the middle of spritespSpiral.defineReferencePixel(FRAME_WIDTH / 2, FRAME_HEIGHT / 2);// Center the sprite on the canvas// (center of sprite is now in center of display)spSpiral.setRefPixelPosition(getWidth() / 2, getHeight() / 2);// Create and add to layer managerlmgr = new LayerManager();lmgr.append(spSpiral);lmgr.append(spMan);lmgr.append(spApple);lmgr.append(spCube);lmgr.append(spStar);

  • V d: Collisions, Collisions.javapublic class Collisions extends MIDlet implements CommandListener {protected Display display; // Reference to displayprivate CollisionCanvas canvas; // Game canvasprivate Command cmExit; // Exit commandpublic Collisions() {display = Display.getDisplay(this);if ((canvas = new CollisionCanvas(this)) != null) { // Create game canvas and exit commandcmExit = new Command("Exit", Command.EXIT, 1);canvas.addCommand(cmExit);canvas.setCommandListener(this);}}public void startApp() {if (canvas != null) {display.setCurrent(canvas);canvas.start();} }