How to make the bot pause every few seconds, in java ping pong game?

那年仲夏 提交于 2019-12-11 17:44:03

问题


I have used the right paddle as a bot, and I am trying to pause it every few seconds. I have tried a few methods.

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

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

I have also tried to use thread:

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

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

I tried to sleep the paddle as well:

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

None of them has worked, even though there are no errors. The paddle should pause for 0.5 or 1 second every few seconds.


回答1:


Yes here you can use the Thread.sleep and timer.

To do that You can use Timer to pause and resume your task, I've pasted below the sample where you can have a small idea about timer and timer task work.

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();
  }
}

=> output:

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


来源:https://stackoverflow.com/questions/56503740/how-to-make-the-bot-pause-every-few-seconds-in-java-ping-pong-game

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!