www.pudn.com > TWPlaneGame.rar > KeyRepeat.java


package twplanegame;


class KeyRepeat extends Thread
{
   private boolean            m_cancel = false;
   private long               m_sleepTime = 50;
   private int                m_gameAction = 0;
   private final KeyRepeater  m_ui;

   /**
    * Creates a KeyRepeated object and saves the reference to the UI
    * in which the key repeat emulation shoudl occur.
    * @param ui The UI in which the key repeat emulation shoudl occur.
    */
   public KeyRepeat(KeyRepeater ui)
   {
      m_ui = ui;
   }

   /**
    * Stops the thread.
    */
   public void cancel()
   {
      m_cancel = true;
   }

   /**
    * Returns the game action currently repeated.
    *
    * @return The game action currently repeated.
    */
   public int getGameAction()
   {
      return m_gameAction;
   }

   /**
    * Sets the amount of time between actions.
    *
    * @param sleepTime The amount of time to sleep between actions.
    */
   public void setSleepPeriod(long sleepTime)
   {
      m_sleepTime = sleepTime;
   }

   /**
    * Start the key to be repeated.
    *
    * @param gameAction The game action that is to be performed.
    */
   public void startRepeat(int gameAction)
   {
      m_gameAction = gameAction;
   }

   /**
    * Stop the key from being repeated.  If the currently repeated key is
    * the same as the one that is to be stopped then stop; otherwise
    * ignore it, we must be repeating a different key.
    *
    * @param gameAction The game action that is to be performed.
    */
   public void stopRepeat(int gameAction)
   {
      if (gameAction == m_gameAction)
      {
         m_gameAction = 0;
      }
   }

   /**
    * Perform the repetition of the key.
    */
   public void run()
   {
      while (!m_cancel)
      {
         // yield to other threads if there is no key to be repeated
         while (m_gameAction == 0  && !m_cancel)
         {
            Thread.yield();
         }
         // perform the repetition of the last key
         m_ui.moveMyPlane(m_gameAction);
         // wait for a little bit
         try
         {
            sleep(m_sleepTime);
         }
         catch (InterruptedException e)
         {
         }
      }
   }
}