Monday, June 29, 2015

Java Midlet and sources

http://www.csis.ysu.edu/~john/5895MWP/j2me/






package com.j2me.part3;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

import java.io.IOException;

public class MyGameCanvas
  extends GameCanvas implements Runnable {

public MyGameCanvas() {
  super(true);
}

public void start() {

  try {

    // create and load the couple image
// and then center it on screen when
// the MIDlet starts
coupleImg = Image.createImage("/couple.gif");
coupleX = CENTER_X;
coupleY = CENTER_Y;

  } catch(IOException ioex) { System.err.println(ioex); }

  Thread runner = new Thread(this);
  runner.start();

}

public void run() {

  // the graphics object for this canvas
  Graphics g = getGraphics();

  while(true) { // infinite loop

      // based on the structure

  // first verify game state
  verifyGameState();

  // check user's input
  checkUserInput();

  // update screen
  updateGameScreen(getGraphics());

// and sleep, this controls
// how fast refresh is done
try {
  Thread.currentThread().sleep(30);
} catch(Exception e) {}

  }

}

private void verifyGameState() {
  // doesn't do anything yet
}

private void checkUserInput() {

  // get the state of keys
  int keyState = getKeyStates();

  // calculate the position for x axis
  calculateCoupleX(keyState);

}

private void updateGameScreen(Graphics g) {

  // the next two lines clear the background
  g.setColor(0xffffff);
  g.fillRect(0, 0, getWidth(), getHeight());

  // draws the couple image according to current
  // desired positions
  g.drawImage(
    coupleImg, coupleX,
coupleY, Graphics.HCENTER | Graphics.BOTTOM);

  // this call paints off screen buffer to screen
  flushGraphics();

}

private void calculateCoupleX(int keyState) {

  // determines which way to move and changes the
  // x coordinate accordingly
  if((keyState & LEFT_PRESSED) != 0) {
    coupleX -= dx;
  }
  else if((keyState & RIGHT_PRESSED) != 0) {
    coupleX += dx;
  }

}

// the couple image
private Image coupleImg;

// the couple image coordinates
private int coupleX;
private int coupleY;

// the distance to move in the x axis
private int dx = 1;

// the center of the screen
public final int CENTER_X = getWidth()/2;
public final int CENTER_Y = getHeight()/2;

}



package com.j2me.part3;

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;

public class GameMIDlet extends MIDlet {

MyGameCanvas gCanvas;

public GameMIDlet() {
gCanvas = new MyGameCanvas();
}

public void startApp() {
Display display = Display.getDisplay(this);
gCanvas.start();
display.setCurrent(gCanvas);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}



No comments:

Post a Comment