JustMovingCanvas.java
上传用户:gyyuli
上传日期:2013-07-09
资源大小:3050k
文件大小:2k
源码类别:

J2ME

开发平台:

Java

  1. import javax.microedition.lcdui.*;
  2. import javax.microedition.lcdui.game.*;
  3. public class JustMovingCanvas    extends GameCanvas    implements Runnable 
  4. {
  5.   private Graphics g;
  6.   private int[ ] clrs = {0X0000FFFF,0x00FF0000,0x0000FF00,0x000000FF};
  7.   private int curColor = 0X000000FF;
  8.   private int[ ] rgb;
  9.   private int curX = 0,curY = 0;
  10.   private int maxX, maxY;
  11.   private boolean isRun;
  12.   private long mFrameDelay;
  13.   public JustMovingCanvas() {
  14.    super(true);
  15.    //初始化用于Alpha 绘图的像素数组
  16.    rgb = new int[81];
  17.    for(int i = 0;i<81;i++)
  18.    rgb[i] = 0x88FFFFFF;
  19.    g = getGraphics( );
  20.    //计算方块移动范围
  21.    maxX = getWidth( ) -9;
  22.    maxY = getHeight( ) -9;
  23.   }
  24.   
  25.   public void start() {
  26.     isRun = true;
  27.     Thread t = new Thread(this);
  28.     t.start();
  29.   }
  30.   public void stop() { isRun = false; }
  31.   public void run() {
  32.     while (isRun == true) {
  33.       input();
  34.       render(g);
  35.       try { Thread.sleep(mFrameDelay); }
  36.       catch (InterruptedException ie) {}
  37.     }
  38.   }
  39.   private void tick(){
  40.    //通过Alpha 混合使原来的方块颜色变浅
  41. g.drawRGB(rgb,0,9,curX,curY,9,9,true);
  42.   }
  43.   
  44.   private void input() {
  45.         int keyState = getKeyStates( );
  46.         //判断ABCD键是否被按下
  47.         if((keyState & GAME_A_PRESSED) != 0)
  48.         curColor=clrs[0];
  49.         else if((keyState & GAME_B_PRESSED) != 0)
  50. curColor=clrs[1];
  51. else if((keyState & GAME_C_PRESSED) != 0)
  52. curColor=clrs[2];
  53. else if((keyState & GAME_D_PRESSED) != 0)
  54. curColor=clrs[3];
  55. //判断上下左右键是否被按下
  56. if((keyState & UP_PRESSED) != 0 && curY>0)
  57. curY --;
  58. if((keyState & DOWN_PRESSED) != 0 && curY<maxY)
  59. curY ++;
  60. if((keyState & LEFT_PRESSED) != 0 && curX>0)
  61. curX --;
  62. if((keyState & RIGHT_PRESSED) != 0 && curX<maxX)
  63. curX ++;
  64.   }
  65.   
  66.   private void render(Graphics g) {
  67.    g.setColor(curColor);
  68. g.fillRect(curX,curY,9,9);
  69. flushGraphics( );
  70.   }
  71. }