For or While help please!


#1

Looking for Help on exercise flow control. I think I got the hang of what is going on but i think i tried to do something more then I should. that said now I am wondering why its not working. I am very very new to this stuff. so please make your answer as clear as possible and explain why etc..

For or While

SyntaxError: Unexpected token '{'. Parse error.


var playerName = prompt("What is your name demon slayer?");
var hits = Math.floor(Math.random() * 2);
var damage = Math.floor(Math.random() * 5 + 1);
var demonHp = 25;
var playerHp = 30;
var fight = true;

while(fight) {
    if (hits) {
        console.log("You have hit the demon for" + damage + "damage!");
        damage -= demonHp;
        console.log("The demon now has" + demonHp + "left");
        if (demonHp <= 1) {
        console.log("You have been slain by the demon!");
        fight = false;
        }
        else{
            hits = Math.floor(Math.random() * 2);
        }
    }
    else {
        console.log("You have missed the demon and he swings at you!");
        damage -= playerHp;
        console.log("You have" + playerHp + "remaining");
        if (playerHp <= 1){
            console.log("You have been slain by the demon")
            fight = false;
        }
        else{
            hits = Math.floor(Math.random() * 2);
        }
            
    }
}


#2

The error makes me think you either have an extra opening bracket or you have some in the wrong spot. ie There was an opening bracket that wasn't expected. Or you could say there was an unexpected token.


#3

Solved.
var playerName = prompt("What is your name demon slayer?");
var hits = Math.floor(Math.random() * 2);
var damage = Math.floor(Math.random() * 5 + 1);
var demonHp = 25;
var playerHp = 30;
var fight = true;

while(fight) {
if (hits) {
console.log("You have hit the demon for" + damage + "damage!");
demonHp -= damage;
console.log("The demon now has" + " "+ demonHp +" "+ "left");
if (demonHp < 1) {
console.log("You have been slain by the demon!");
fight = false;
}
else{
hits = Math.floor(Math.random() * 2);
}
}
else {
console.log("You have missed the demon and he swings at you!");
playerHp -= damage;
console.log("You have" + " "+ playerHp + " "+ "remaining");
if (playerHp < 1){
console.log("Congratulations" + " " + playerName + " " + "You have been slain by the demon")
fight = false;
}
else{
hits = Math.floor(Math.random() * 2);
}

}

}


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.