我正在做一个学校项目,我们正在制作一个炸弹人游戏。操场上有 2 个轰炸机,用户和 AI。
当用户放置炸弹并离开它时,炸弹会在时间结束时闪烁并爆炸。
但是,这不适用于 AI。
当 AI 放置炸弹并离开它时,当它应该闪烁然后爆炸时,应用程序会因留下以下错误而崩溃:
FATAL EXCEPTION: Timer-0
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
CountDownTimer
代码如下。
public void explodeAIBomb(){
//Starts countdown 2-4 seconds
new CountDownTimer(new Random().nextInt(2000) + 2000, 300) {
//test for onTick; bomb flashes
boolean test = false;
public void onFinish() {
//on explosion{
gameBoard[locateAIX][locateAIY] = new Blast();
explosionSide(locateAIX, locateAIY);
explosionVert(locateAIX, locateAIY);
updateView();
//Clear all blasts after 1 second
new CountDownTimer(1000, 1000){
public void onFinish(){
for (int x = 0; x < XasLength + 1; x++) {
for (int y = 0; y < YasLength + 1; y++) {
if(gameBoard[x][y] != null){
if(gameBoard[x][y].getTileId() == BLAST || gameBoard[x][y].getTileId() == BLAST_SIDE || gameBoard[x][y].getTileId() == BLAST_VERT){
gameBoard[x][y] = null;
}
}
}
}
aiBombPlanted = false;
updateView();
}
@Override
public void onTick(long millisUntilFinished) {
}
}.start();
updateView();
}
//Flashes the bomb every 0.3 second
public void onTick(long millisUntilFinished) {
if(test){
loadTile(BOMB, r.getDrawable(R.drawable.bomb));
test = false;
}
else{
loadTile(BOMB, r.getDrawable(R.drawable.bomb2));
test = true;
}
updateView();
}
}.start();
}