Hey, I am creating a turn based combat system and I got it working but I'm not very proud of my algorithm. First, let me explain. My heroes have a speed stat, lower means better, and it could potentially range between 1000 to 1. When a hero with 3 speed can act 3 times before a hero with 10 speed can. I need a list of heroes to show the turn order and conveniently with my current algorithm I can pop the first on the list and add a new one. However I am looking for new heroes by increasing the time by 1 and keep looking for a new hero that should act. So I am traversing my hero loops countless times for nothing.
private void updateLineUp()
{
while (lineUp.size() < 10)
{
//Check if tiebreaking pool has heroes in it
if (tieBreakingPool.size() > 0)
{
//Check if there is only one hero in the tiebreaking pool to add it directly
if (tieBreakingPool.size() == 1)
{
Hero nextHero = tieBreakingPool.remove(0);
lineUp.add(nextHero);
System.out.println("[Time: " + futureTime + "] Added " + nextHero.getName() + " has " + nextHero.getSpeed() + " speed to the lineup.");
}
else
{
//Pick random hero from the tieBreakingPool
Hero nextHero = tieBreakingPool.remove(random.nextInt(tieBreakingPool.size()));
lineUp.add(nextHero);
System.out.println("[Time: " + futureTime + "] Added " + nextHero.getName() + " has " + nextHero.getSpeed() + " speed to the lineup.");
}
}
else { //search for new heroes to add
//increment the future time for reference where the last hero is at.
futureTime++;
//find next heroes in line to add
for (int i = 0; i < 5; i++) {
if (futureTime % playerHeroes[i].getSpeed() == 0) {
tieBreakingPool.add(playerHeroes[i]);
}
if (futureTime % opponentHeroes[i].getSpeed() == 0) {
tieBreakingPool.add(opponentHeroes[i]);
}
}
}
}
}
private Hero getNextHero()
{
//remove first hero from list
Hero hero = lineUp.remove(0);
System.out.println("Popped " + hero.getName() + " from the lineup.");
//update the line up
updateLineUp();
return hero;
}
To get a list of the next 10 heroes takes only around 10ms so that is not bad at all since I only need a complete new list if the speed of the hero changes. But I'm not really looking for improving performance but rather coding style and cc on that.