龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

使用MIDP2.0开发游戏(1)GameCanvas基础

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
MIDP2.0提供了对游戏的强有力支持,通过Javax.microedition.lcdui.game包,原来在MIDP1.0中很多需要自己写的功能现在都被当作标准API实现了,包括GameCanvas,Sprite,Layer等等。 我们将使用MIDP2.0编

  MIDP2.0提供了对游戏的强有力支持,通过Javax.microedition.lcdui.game包,原来在MIDP1.0中很多需要自己写的功能现在都被当作标准API实现了,包括GameCanvas,Sprite,Layer等等。

  我们将使用MIDP2.0编写一个坦克大战的手机游戏,我也是初学J2ME不久,预备边看书边做,争取把这个游戏做出来!J2ME高手请多指点,和我一样学习中的朋友欢迎多多交流!

  我们的开发环境为Windows XP SP1 + J2DK1.4 + J2ME WTK2.1 + Eclipse 3.0 + EclipseMe,关于如何配置Eclipse的J2ME开发环境,请参考:

  http://blog.csdn.net/mingjava/archive/2004/06/23/24022.ASPx

  下面是一个最简单的GameCanvas的例子,出自《J2ME  & Gaming》:

  // MyGameCanvas.java
  // 编写Canvas类
  import javax.microedition.lcdui.*;
  import javax.microedition.lcdui.game.*;
  
  public class MyGameCanvas extends GameCanvas implements Runnable {
      private boolean isPlay; // Game Loop runs when isPlay is true
      private long delay; // To give thread consistency
      private int currentX, currentY; // To hold current position of the 'X'
      private int width; // To hold screen width
      private int height; // To hold screen height
  
      // ConstrUCtor and initialization
      public MyGameCanvas() {
          super(true);
          width = getWidth();
          height = getHeight();
          currentX = width / 2;
          currentY = height / 2;
          delay = 20;
      }
  
      // Automatically start thread for game loop
      public void start() {
          isPlay = true;
          new Thread(this).start();
      }
  
      public void stop() { isPlay = false; }
  
      // Main Game Loop
      public void run() {
          Graphics g = getGraphics();
          while (isPlay) {
              input();
              drawScreen(g);
              try {
                  Thread.sleep(delay);
              }
              catch (InterruptedException ie) {}
          }
      }
  
      // Method to Handle User Inputs
      private void input() {
          int keyStates = getKeyStates();
          // Left
          if ((keyStates & LEFT_PRESSED) != 0)
              currentX = Math.max(0, currentX - 1);
          // Right
          if ((keyStates & RIGHT_PRESSED) !=0 )
              if ( currentX + 5 < width)
                  currentX = Math.min(width, currentX + 1);
          // Up
          if ((keyStates & UP_PRESSED) != 0)
              currentY = Math.max(0, currentY - 1);
          // Down
          if ((keyStates & DOWN_PRESSED) !=0)
              if ( currentY + 10 < height)
                  currentY = Math.min(height, currentY + 1);
      }
  
      // Method to Display Graphics
      private void drawScreen(Graphics g) {
          g.setColor(0xffffff);
          g.fillRect(0, 0, getWidth(), getHeight());
          g.setColor(0x0000ff);
          g.drawString("X",currentX,currentY,Graphics.TOPGraphics.LEFT);
          flushGraphics();
      }
  }

  
  

精彩图集

赞助商链接