2013-05-06 106 views
0

这是我以前的问题的后续。我有两个主板的战舰游戏。当用户点击电脑板时发生的作用,沿着这些路线:在游戏中正确实施延迟

public void mouseClicked(MouseEvent e) 
// Get coordinates of mouse click 

if (//Set contains cell) { 
    /add Cell to set of attacked cells 

//Determine if set contains attacked cell. 
// If yes, hit, if no, miss. 
checkForWinner(); 

的checkForWinner方法确定游戏已经赢得了尚未。如果没有,它会调用nextTurn方法来改变当前的转弯。如果currentTurn设置为Computer,则会自动调用ComputerMove()方法。
该方法完成后,它再次检查forWinner,更改转向并等待用户单击网格再次启动循环。

理想情况下,我想要有声音效果,或者至少在移动之间暂停。但是,不管我如何使用Thread.sleep,TimerTask或其他任何东西,我都无法使其正常工作。

如果我使用的方法CheckforWinner一个简单的Thread.sleep(500),或在ComputerMove方法,所发生的一切是人的旅途中被延迟设定的时间量。一旦他的举动被执行,计算机的移动立即完成。

我对线程知之甚少,但我认为这是因为在方法之间来回跳动的所有启动都始于鼠标监听器中的方法。

鉴于我的系统的建立,是否有一种方法来实现延迟而不会彻底改变事物?

编辑:可能也包括两类:

public void checkForWinner() { 
    if (human.isDefeated()) 
     JOptionPane.showMessageDialog(null, computer.getName() + " wins!"); 
    else if (computer.isDefeated()) 
     JOptionPane.showMessageDialog(null, human.getName() + " wins!"); 
    else 
     nextTurn(); 
} 

public void nextTurn() { 
    if (currentTurn == computer) { 
     currentTurn = human; 
    } else { 
     currentTurn = computer; 
     computerMove(); 
    } 
} 

public void computerMove() { 

    if (UI.currentDifficulty == battleships.UI.difficulty.EASY) 
     computerEasyMove(); 
    else 
     computerHardMove(); 
} 

public void computerEasyMove() { 

    // Bunch of code to pick a square and determine if its a hit or not. 
    checkForWinner(); 
} 
+0

您是否尝试过等待'ComputerMove'的开始? – 2013-05-06 13:33:34

+0

是的 - 但它只是暂停人的举动。它不会延迟电脑移动。 – 2013-05-06 13:34:03

+0

然后,你似乎需要调试你的程序来找出为什么'ComputerMove'在“人类移动”结束之前被调用,对吧? – 2013-05-06 13:36:06

回答

1

理想情况下,我想有声音效果,或至少是移动之间的停顿。但是,不管我如何使用Thread.sleep,TimerTask或其他任何东西,我都无法使其正常工作。

您应该使用摆动计时器。例如:

Timer timer = new Timer(1000, new ActionListener() 
{ 
    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     currentTurn = computer; 
     computerMove(); 
    } 
}); 
timer.setRepeats(false); 
timer.start(); 
+0

Upvoted; @Andrew,你应该在处理鼠标点击时设置计时器;在同一时间播放声音。处理程序执行时,机器将移动。这会给你在人类移动+声音和机器移动之间延迟1秒。 – tucuxi 2013-05-06 15:10:11