【发布时间】:2016-03-11 16:19:26
【问题描述】:
我正在用 java 设计一个游戏,它类似于棋盘游戏。在实现中还有一种称为速度模式的模式,如果一个玩家在时间限制(5 秒)内没有转弯,则另一个玩家获胜。这种模式通常也可以通过“捕获”对方棋子来获胜。在满足这些条件中的任何一个后,将从主菜单再次运行游戏。当通过捕获满足获胜条件时,这在正常模式和速度模式下都可以正常工作。当它被时间耗尽时,它的行为非常奇怪,几乎随机提示输入和打印。
当时的代码如下:
public Boolean speedMode(Player player, Player opponent) {
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
Boolean outOfRange;
public void run() {
do {
outOfRange = takeTurn(player);
} while (outOfRange == true);
}
};
Future<?> f = service.submit(r);
f.get(5, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
System.out.println("The thread was interrupted during sleep, wait or join");
} catch (final TimeoutException e) {
player.setWon(false);
System.out.println("\n" + player.getName() +", you took too long... ");
return true;
} catch (final ExecutionException e) {
System.out.println("An exception from within the Runnable task");
}
return false;
}
当 TimeoutException 发生时,相反的玩家获胜,而下面显示的循环退出并打印正确的祝贺。问题是当它在代码的最后一行开始新游戏时,就是奇怪行为开始的时候。定时器方法中是否有我需要关闭的东西?它几乎就像它仍在后台运行一样。
else {
do {
timeOut = speedMode(second, first);
if(winCheck1(first) == true || timeOut == true){
break;
}
timeOut = speedMode(first, second);
} while (winCheck1(second) != true && timeOut != true);
if(player1.isWon() == true){
System.out.println("\n\nCongratulations " + player1.getName() + " you are the winner!\n\n");
}
else{
System.out.println("\n\nCongratulations " + player2.getName() + " you are the winner!\n\n");
}
}
//reload the menu
Game game = new Game();
}
基本上我的问题是;谁能告诉我为什么在抛出 TimeoutException 后开始新游戏无法正常工作?
【问题讨论】:
标签: java timer exception-handling timeoutexception