正确实施游戏延迟

时间:2013-05-06 13:31:49

标签: java swing awt delay mouselistener

这是我之前的一个问题的后续跟进。我有一个有两块板的战舰游戏。当用户点击计算机主板时,会发生以下行:

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

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

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

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

考虑到我的系统的设置,有没有办法实现延迟而不会彻底改变事物?

编辑:也可以包括这些类:

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

1 个答案:

答案 0 :(得分:1)

  

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

你应该使用Swing Timer。类似的东西:

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