所以我是一名初学程序员,我正在努力打乒乓球比赛(但水平)。只有一个小问题。在用户得分后,球将立即返回到球员。我想知道是否有一种方法可以让玩家有时间做出反应。这是评分'系统我正在使用。
提前谢谢!
if(yBall<=100-barHeight*0.5){
yBall = 300;
xBall = 400;
text_player2 = text_player2+1;
yBallSpeed = yBallSpeed *-1;
xBar = width*0.5 - barWidth*0.5;
//pause for few seconds
}
答案 0 :(得分:2)
您可以使用Thread.sleep(millisecs)
,请参阅https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep%28long%29
请注意,您必须放置&#34; try-catch块中的Thread.sleep(millisecs)
(或者添加方法):
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
答案 1 :(得分:0)
在Java中,您可以使用
使当前正在执行的Thread进入休眠状态x毫秒Thread.sleep(1000);
如果这是一个初学者编程练习,那么这可能适合你。确保捕获此方法抛出的异常。
另外请考虑一下你是否真的想睡觉游戏运行的线程。也许你想继续处理用户输入(例如,如果他想退出),但是稍后安排新的球位。为此,您可以查看Timer的用途
答案 2 :(得分:0)
看来你是在游戏的每帧操作中执行此操作,因此Thread.sleep
将是不好的做法。它不会暂停游戏,而是会使游戏在一段时间内无响应地挂起(这可能对您而言可能不合适)。
请考虑使用System.currentTimeMillis()
,它以毫秒为单位返回当前时间:
long deadLine = 0L;
// Your method for updating the game's state
void updateState() {
if (deadline > System.currentTimeMillis()) {
// The game is currently paused. Draw a "Get Ready" string maybe?
return;
}
if (gameShouldRestart()) {
// The game should not do anything for the next two seconds:
deadLine = System.currentTimeMillis() + 2000L;
// Reset game state here.
}
}
现在updateState()
方法将立即返回并让游戏继续渲染但不做任何事情,而不是仅仅将游戏滞后几秒钟。
答案 3 :(得分:0)
您应该使用ScheduledExecutorService
在延迟后调用操作,而不会导致当前线程阻塞。尝试在整个应用程序中重复使用相同的ScheduledExecutorService
,并确保在最后关闭它。
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
try {
executor.schedule(() -> SwingUtilities.invokeLater(() -> {
readyToRestart(); // your method that restarts the action
}), 1, TimeUnit.SECONDS);
} finally { executor.shutdown(); }
由于ScheduledExecutorService
将在其自己的线程上运行计划的操作,因此您需要确保该操作不会导致任何与线程相关的问题。如何执行此操作取决于您使用的GUI工具包。在示例中,我将展示如何使用SwingUtilities.invokeLater
方法在Swing中执行此操作。