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() 方法。
当该方法完成时,它会再次检查Winner,更改轮次并等待用户单击网格以再次开始循环。

理想情况下,我希望有声音效果,或者至少在动作之间有一个停顿。但是,无论我如何使用 Thread.sleep、TimerTask 或其他任何东西,我都无法让它正常工作。

如果我在 CheckforWinner 方法或 ComputerMove 方法中使用一个简单的 Thread.sleep(500),那么所发生的只是人类的行动被延迟了设定的时间。他的动作一执行,计算机的动作就立即完成。

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

鉴于我的系统设置,有没有办法在不彻底改变事物的情况下实现延迟?

编辑:也可以包括以下课程:

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

1 回答 1

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();
于 2013-05-06T15:01:12.857 回答