Reputation: 545
So, I'm working on a turn based game where there are friendly characters on the left and enemy characters on the right. The characters are looped through a for loop to determine actions/update health/etc.
public function onTurn() {
for each (var i in charactersPlayer) {
i.everyTurn();
}
for each (i in charactersOpponent) {
i.everyTurn();
}
turn++;
}
My problem arises when I want to play an animation or halt the progression of the for loops (to let health bars animate). Ultimately I want each character to run their everyTurn()
method one by one, and for the for loops to wait for a character to finish their animation before going on to the next iteration.
I have a method in the Character
class (charactersPlayer
and charactersOpponent
are both containers for Character
objects) animationDone
which returns false
if the animation is not done yet, and true
if the animation is done.
All help will be greatly appreciated! Thanks in advance.
Upvotes: 0
Views: 84
Reputation: 18747
You need to do an asynchronous loop, instead of calling it all at once, you call one's everyTurn()
and wait for him to dispatch an event (either Event.COMPLETE
or any custom string), this will signify this character has finished its turn. You react on the event by finding the next character which should perform actions, and call its everyTurn()
, and so on until a winning condition. Or, as you have a state check function, you can use an enter frame listener to do this trick.
var turn:int;
var currentlyActing:Character;
function onEnterFrame(e:Event):void {
// other enter frame code, if any
if (currentlyActing.animationDone()) {
currentlyActing=selectNext(currentlyActing);
if (currentlyActing) currentlyActing.everyTurn();
}
}
function selectNext(c:Character):Character {
var i:int=charactersPlayer.indexOf(c);
if (i>=0) {
i++;
if (i<charactersPlayer.length) return charactersPlayer[i];
if (charactersOpponent.length>0)return charactersOpponent[0];
// no opponents at this point. Process win
processWin();
return null; // game over
}
i=charactersOpponent.indexOf(c);
if (i==-1) return null; // oops!
i++;
if (i<charactersOpponent.length) return charactersOpponent[i];
if (charactersPlayer.length>0) return charactersPlayer[0];
// no player chars left
processLose();
return null;
}
Upvotes: 1