问题
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