我正在做一个学校项目,我们正在制作一个炸弹人游戏。在球场上有2名炸弹人,用户和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();
}
答案 0 :(得分:1)
你在某个地方从工作线程做UI工作。你需要在主线程中调用处理UI的东西。
我认为之前已经回答了同样的问题。
stackoverflow.com/questions/6354740/how-is-countdowntimer-accessing-ui-inside-ontick-method