在Java乒乓游戏中,如何使漫游器每隔几秒钟暂停一次?

时间:2019-06-08 05:29:46

标签: java core

我已经使用了正确的桨作为机器人,并且我试图每隔几秒钟暂停一次。我尝试了几种方法。

This is the code I tried:
 float time = System.currentTimeMillis();

 if (time >= 1000) {
        rPad.bot(theBall);
        time = System.currentTimeMillis();
 }

我也尝试使用线程:

   PongMain run = new PongMain();
    Thread thread = new Thread(run);
    thread.start();

 @Override
public void run() {
    rPad.bot(theBall);
    // TODO Auto-generated method stub  
 }

我也试图睡桨:

 try {
        Thread.sleep(1000);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }

即使没有错误,它们都没有起作用。桨应每隔几秒钟暂停0.5或1秒。

1 个答案:

答案 0 :(得分:0)

是的,您可以在其中使用Thread.sleep和计时器。

为此,您可以使用Timer暂停和继续执行任务,我在示例下面粘贴了一个小示例,您可以对Timer和Timer任务的工作有所了解。

import java.util.Timer;
import java.util.TimerTask;

class MyTask extends TimerTask {
  int counter;

  public MyTask() {
    counter = 0;
  }
  public void run() {
    counter++;
    System.out.println("Ring " + counter);
  }
  public int getCount() {
    return counter;
  }
}

public class Main {
  private boolean running;
  private MyTask task;
  private Timer timer;
  public Main() {
    timer = new Timer(true);
  }

  public boolean isRinging() {
    return running;
  }

  public void startRinging() {
    running = true;
    task = new MyTask();
    timer.scheduleAtFixedRate(task, 0, 3000);
  }

  public void doIt() {
    running = false;
    System.out.println(task.getCount() + " times");
    task.cancel();
  }

  public static void main(String[] args) {
    Main phone = new Main();
    phone.startRinging();
    try {
      System.out.println("started running...");
      Thread.sleep(20000);
    } catch (InterruptedException e) {
    }
    phone.doIt();
  }
}

=>输出:

started running...
Ring 1
Ring 2
Ring 3
Ring 4