私が設計しているボード ゲームでは、各ユーザーが 100 セルのグリッドを持っています。ユーザーがコンピューターのグリッド内のセルをクリックすると、音が鳴り、別の色に変わります。次に、コンピューターがユーザーのグリッド内のセルを自動的にクリックすると、音が鳴り、別の色に変わります。
ユーザーのクリックは、MouseListener (および MouseClicked メソッド) を介して処理されます。現在、メソッドが最後に行うことは、computerMove() メソッドを呼び出すことです。このメソッドは、現在のプレーヤーを人間に戻す前に、コンピューターの移動を実行および実行します。人間がもう一度マウスをクリックすると、ゲームが進行します。
理想的には、各プレイヤーの動きの間に一時停止 (おそらく 1 秒) を入れたいと思います。しかし、MouseClicked メソッド内で computerMove メソッドが呼び出されているため、これが面倒です。Thread.sleep と TimerTask を使用することで、私にできる最善のことは、人間のプレイヤーの動きを遅くすることです。ただし、プレーヤーがマウスをクリックするとすぐに、コンピューターは即座に応答します。
遅延を実装する方法について何か提案はありますか? メソッドの呼び出し方法を変更する必要がありますか?
ComputerMove メソッド:
public void computerMove() {
if (currentTurn == computer) {
int xPos = randomGenerator.nextInt(10);
int yPos = randomGenerator.nextInt(10);
LogicCell attackedCell = new LogicCell(xPos, yPos);
playerGridLogic.addCellsThatHaveBeenAttacked(attackedCell);
if (playerGridLogic.getCellsWithShips().contains(attackedCell)) {
playerGrid.getCellArray()[xPos][yPos].setBackground(Color.ORANGE);
hitSound();
}
else {
playerGrid.getCellArray()[xPos][yPos].setBackground(Color.MAGENTA);
missSound();
}
nextTurn();
}
}
対応する MouseClick メソッド:
@Override
public void mouseClicked(MouseEvent e) {
if (allComputerShipsPlaced && currentTurn == human) {
ViewCell currentCell = (ViewCell) e.getSource();
xPos = currentCell.getXPos();
yPos = currentCell.getYPos();
LogicCell attackedCell = new LogicCell(xPos, yPos);
computerGridLogic.addCellsThatHaveBeenAttacked(attackedCell);
if (computerGridLogic.getCellsWithShips().contains(attackedCell)) {
cellArray[xPos][yPos].setBackground(Color.ORANGE);
hitSound();
}
else {
cellArray[xPos][yPos].setBackground(Color.MAGENTA);
missSound();
}
nextTurn();
computerMove();
}
}
missSound メソッド() (hitSound は非常に似ています):
public static void missSound() {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("water-splash.wav")));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}
編集:サウンドクラスをこれに変更しようとしましたが、役に立ちませんでした:
public static void hitSound()
{
try
{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("bomb-explosion.wav")));
clip.start();
LineListener listener = new LineListener() {
public void update(LineEvent event) {
if (event.getType() != Type.STOP) {
return;
}
try {
queue.take();
} catch (InterruptedException e) {
//ignore this
}
}
};
clip.addLineListener(listener);
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}