I am trying to do combat loop for my learning project and I finally realised I would need some async await / promises, because here is the scenario:
There are 4 fighters on each side. Everything goes well in this case, because enemy randomly picks a character to attack and functions work as intended.
However, your character can die and then we have only 3 left, but I'm not removing them from the array of characters, because they could be revived later, so enemy still rolls k4 and in case they got an index of character that already died they need to roll again.
Howeverm in theory I thought I knew what I was doing, but in reality I get undefined because (in my assumption) other functions dont wait for enemy to pick the index of the character to attack, and while it's still being rolled they execute and program crashes.
Here's some of the code from the enemy turn:
enemies.forEach((enemy, i) => {
setTimeout( async () => {
let allyIndex = await dispatch(getAllyIndex());
let enemyAgility = getEnemyAgility(i, enemies);
let allyEvasion = await dispatch(getAllyEvasion(allyIndex));
let wasAttackSuccessful = await dispatch(calculateAttackSuccessChance(enemyAgility, allyEvasion));
if (wasAttackSuccessful) {
let wasCritical = dispatch(wasAttackCritical(i));
let enemyDmg = dispatch(calculateEnemyDmg(i));
let allyDef = await dispatch(getAllyDefence(allyIndex));
let totalDmg = await dispatch(calculateTotalDmg(enemyDmg, allyDef, wasCritical));
let info = ``;
if (wasCritical) { info += `Critical hit! ` };
let allyName = await getState().characters[allyIndex].name;
info += `${enemy.name} dealth ${totalDmg} damage to ${allyName}.`;
dispatch(addInfoToArray(info))
dispatch(allyLoseHp(totalDmg, allyIndex))
} else {
let info = `${enemy.name} missed!`
dispatch(addInfoToArray(info))
}
noOfEnemiesAttacked += 1;
if (noOfEnemiesAttacked === enemies.length) {
dispatch(changeTurn('ally'))
}
}, 2000 + offset);
offset += 200;
})
Issue probably lies in getAllyIndex function. Here's how it looks:
const getAllyIndex = () => {
return function (dispatch, getState) {
let i = Math.floor((Math.random() * getState().characters.length));
if (getState().characters[i].stats.hp <= 0) {
dispatch(getAllyIndex());
} else {
return i;
}
}
}
And the program reports errors in those functions that require allyIndex:
let allyEvasion = await dispatch(getAllyEvasion(allyIndex));
let allyDef = await dispatch(getAllyDefence(allyIndex));
let allyName = await getState().characters[allyIndex].name;
Have i completely misunderstood the concept of async await or the issue lies somewhere else?