⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 wheel_canvas.java

📁 本光盘是《J2ME无线移动游戏开发》一书的配套光盘
💻 JAVA
字号:
package ch08;

import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;

public class Wheel_Canvas
    extends GameCanvas
    implements Runnable, CommandListener {

  //代表程序是否运行的状态
  boolean running;

  //存储构成动画的各图像帧
  Image img;

  //代表动画的精灵对象
  Sprite sp;

  //屏幕宽度
  int win_width = getWidth();

  //屏幕高度
  int win_height = getHeight();

  //每帧图像的宽度
  int img_width = 90;

  //每帧图像的高度
  int img_height = 90;

  //图像X坐标
  int x;

  //图像Y坐标
  int y;

  //主MIDlet类实例
  Wheel_MIDlet wm;

  /*
   3.构造器
   */
  public Wheel_Canvas(Wheel_MIDlet wm) {
    super(true);
    this.wm = wm;
    Command exitCommand = new Command("退出", Command.EXIT, 0);
    addCommand(exitCommand);
    setCommandListener(this);

    try {
      img = Image.createImage("/icons/background/Wheel.png");
    }
    catch (IOException e) {
      System.out.println(e.getMessage());
    }
    sp = new Sprite(img, img_width, img_height);
    x = (win_width - img_width) / 2;
    y = (win_height - img_height) / 2;
    sp.setPosition(x, y);
    start();
  }

  /*
   4.启动线程
   */
  public void start() {
    running = true;
    Thread t = new Thread(this);
    t.start();
  }

  /*
   5.控制进程
   */
  public void run() {
    Graphics g = getGraphics();
    long st = 0, et = 0, diff = 0;
    //控制每秒帧数,即动画快慢
    int rate = 150;
    while (running) {
      st = System.currentTimeMillis();
      GameKeyInput();
      render(g);
      et = System.currentTimeMillis();
      //避免刷新过快,暂停线程至要求帧数
      diff = et - st;
      if (diff < rate) {
        try {
          Thread.sleep(rate - diff);
        }
        catch (InterruptedException ex) {
          stop();
        }
      }

    }
  }

  /*
   6.响应按键
   */
  private void GameKeyInput() {
    int KeyState = getKeyStates(); // 获得当前按键状态
    if ( (KeyState & LEFT_PRESSED) != 0) { // 左
      sp.setTransform(Sprite.TRANS_MIRROR);
      sp.setPosition(x, y);
      sp.move( -2, 0);
    }
    if ( (KeyState & RIGHT_PRESSED) != 0) { // 右
      sp.setTransform(Sprite.TRANS_NONE);
      sp.setPosition(x, y);
      sp.move(2, 0);
    }

  }

  /*
   7.实现绘制
   */
  private void render(Graphics g) {
    g.setColor(0x000000);
    g.fillRect(0, 0, win_width, win_height);
    sp.nextFrame();
    sp.paint(g);

    flushGraphics();
  }

  /*
   8.结束线程
   */
  public void stop() {
    running = false;
  }

  /*
   9.响应按钮事件
   */
  public void commandAction(Command c, Displayable s) {
    if (c.getCommandType() == Command.EXIT) {
      wm.quitApp();
    }
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -