keyrepeat.java

来自「3D手机游戏开发实例源代码」· Java 代码 · 共 68 行

JAVA
68
字号


import javax.microedition.lcdui.*;


public class KeyRepeat extends Thread
{
  private static final int START_TIME = 300;   // ms
  private static final int REPEAT_TIME = 100;   // smaller than START_TIME
  private static final int START_MAX = 2;  // length of slow start

  private boolean stopped = false;
  private int gameAction = 0;     // the key to be repeated

  private int sleepTime = START_TIME;
  private int repeatCount = 0;

  private M3GCanvas gameCanvas;    // reference back to the canvas


  public KeyRepeat(M3GCanvas c)
  { gameCanvas = c;  }
  
  public void cancel()
  // stop the key repeater
  {  stopped = true;  }


  public void startRepeat(int gameAct)
  // start repeating the gameAct key
  {  gameAction = gameAct;  }

  
  public void stopRepeat(int gameAct)
  /* If the currently repeated key is gameAct then stop
     repeating it; otherwise do nothing */
  { if (gameAction == gameAct) {
      gameAction = 0;
      repeatCount = 0;
      sleepTime = START_TIME;
    }
  } // end of stopRepeat()


  public void run()
  // the key repetition loop
  {
    while (!stopped) {
      // yield to other threads if there's no key to be repeated
      while (gameAction == 0 && !stopped)
        Thread.yield();

      //  carry out the gameAction key operation
      gameCanvas.performAction( gameAction );
      
      try   // wait for a bit
      { sleep(sleepTime); }
      catch (InterruptedException e) {}

      // after START_MAX loops, start sleeping for less time
      repeatCount++;
      if (repeatCount == START_MAX)
        sleepTime = REPEAT_TIME;
    }
  } // end of run()

} // end of KeyRepeat class

⌨️ 快捷键说明

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