ID #84997

J2ME 2D小游戏入门之游戏的框架


  一、游戏的框架

  我们的游戏需要一个通用的游戏框架,也方便以后的开发,但实现一个引擎是复杂的。作为初学者假如要你考虑太多的问题,恐怕会让你偏离主线,这里只给出canvas的代码,不理解可以参看本站的另外一篇系列文章《使用MIDP2.0开发游戏》。

public class MyGameCanvas extends GameCanvas
 implements Runnable, CommandListener{
  PRivate static MyGameCanvas instance;
  Graphics g;
  boolean running;
  Thread t;
  Command startcmd,exitcmd,restartcmd;
  int keystate;
  boolean keyevent;
  boolean key_up,key_down,key_left,key_right,key_fire;
  private boolean allowinput;
  public int screenwidth;
  public int screenheight;
  boolean gameover;
  //define your variable here
  //define your variable end
  protected MyGameCanvas() {
   super(true);
   g=getGraphics();
   running=false;
   t=null;
   addCommand(startcmd=new Command("start",Command.OK,1));
   addCommand(exitcmd=new Command("exit",Command.EXIT,1));
   setCommandListener(this);
   screenwidth=getWidth();
   screenheight=getHeight();
   //put your init once code here
   //put your init once code end
  }
  synchronized public static MyGameCanvas getInstance() {
   if (instance == null) {
    instance = new MyGameCanvas();
    System.out.println("new MyGameCanvas");
   }
   return instance;
  }
  public void run(){
   System.out.println("MyGameCanvas run start");
   long st=0,et=0,diff=0;
   int rate=50;//16-17 frame per second
   while(running){
    st=System.currentTimeMillis();
    gameinput();
    gameMain();
    et=System.currentTimeMillis();
    diff=et-st;
    if(diff<rate){
     //System.out.println("Sleep "+(rate-diff));
     try {
      Thread.sleep(rate - diff);
     }
     catch (InterruptedException ex) {}
    }else{
     //System.out.println("rush , and the frame using time: "+diff);
    }
   }
   System.out.println("MyGameCanvas run end");
  }
  public void start(){
   if(!running){
    running=true;
    t=new Thread(this);
    t.start();
   }
  }
  private void gameMain() {
   g.setColor(0,0,0);//clear screen
   g.fillRect(0,0,getWidth(),getHeight());
   flushGraphics();
  }
  private void gameInit() {

2011-09-28 21:57
阅读:
I'm VC , Just U know Y
本站部分文章来源于互联网,版权归原作者所有。

延伸阅读:

有关J2ME新手程序员开发入门的几点说明

J2ME开发经验:J2ME应用程序内存优化三招

J2ME编程应用平台中几个重要概念的介绍

关于J2ME程序员新手开发入门的几大要点

J2ME编程开发平台中几个重要概念的说明