Łukasz Motyczka Łukasz Motyczka - 11 days ago 7
Java Question

IndexOutOf range exception thrown in TimeHandler

I'm making a card-like game. The method below handles the opponents' attacks. It is supposed to go through the opponents' cards (with a two second delay between them) and execute their attacks (dealDamage() returns the damage). First it should check if the current opponent is active (i.e. not killed) and if it has already attacked, if so, their attack is executed. After that, the method moved to the next active opponent. After the last one it should stop iterating and change to the next round. Although the in first round everything goes as planned, but then it often crashes during the second or last round (when only one opponent is active). There can be 5 opponents max. I am clearly missing some obvious thing, but I can't get this to work.

EDIT
The error is in while(gm.opponentList.get(i).is available...
it is for examle index out of range: index 4 size 4.

public void opponentAttack(){


this.registerUpdateHandler(new TimerHandler(2f, true, new ITimerCallback() {
int i = 0;
@Override
public void onTimePassed(TimerHandler pTimerHandler) {



if (i < gm.opponentList.size()) {
while (gm.opponentList.get(i).isAvailable == false
|| gm.opponentList.get(i).attacked == true) {
i++;
}
if (gm.opponentList.get(i).isAvailable == true
&& gm.opponentList.get(i).attacked == false) {

gm.negotiationStrength = gm.negotiationStrength - gm.opponentList.get(i).dealDamage();
i++;
}
if (gm.negotiationStrength < 1) {
gm.negotiationEnded = true;
gm.playersTurn = false;
}
i = 0;
}else{

pTimerHandler.setAutoReset(false);

}

}
}));

gm.nextRound();

}

Answer
  while (gm.opponentList.get(i).isAvailable == false
                        || gm.opponentList.get(i).attacked == true) {
      i++;
  }

if the exit condition is never met, you keep incrementing i, and when it exceed the size of gm.opponentList throws an IndexOutBoundExcetion. You probably want to check i against gm.opponentList.size(), in the while loop