Reputation: 936
I'm experimenting with a simple game in JavaScript which loops through 'hits' on a dragon until the dragon is killed.
The game is working well, however if the result is a miss i.e. youHit = 0
then the script gets stuck in an infinite loop. I know the infinite loop is caused by the final else statement where slaying = true
(if false then the game stops and the script must be run again). My question is how can I loop through both misses and hits without getting stuck in an infinite loop.
var slaying = true
var youHit = Math.floor(Math.random() * 2)
var damageThisRound = Math.floor(Math.random() * 5 + 1)
var totalDamage = 0
var health = 4
while(slaying) {
if (youHit) {
totalDamage += damageThisRound
console.log("You hit for " + totalDamage + " damage");
if (health <= 0) {
console.log('You slayed the dragon!')
slaying = false;
} else {
health -= totalDamage
if (health <= 0) {
slaying = false;
console.log('You slayed the dragon!')
}
else {
slaying = true;
}
}
} else {
console.log("You missed!");
slaying = true;
}
console.log('Health: ' + health)
}
Upvotes: 1
Views: 164
Reputation: 7573
You are not recalculating the hit/miss boolean inside of the loop. So you will either always hit or always miss. If you always miss, this results in an infinite loop.
Move var youHit = . . .
into your while (slaying)
loop.
Upvotes: 1