sbatson5
sbatson5

Reputation: 648

Having a Javascript variable update live

I am very new Javascript and am messing around trying to make a simple game. Basically, you can attack or heal and your HP goes up or down accordingly. Here is what I have so far:

<script type="text/javascript">
var myHP=50;
var eHP=50;
</script>

<script type="text/javascript">
function attack()
{
    var dmg=(Math.floor(Math.random()*11));
    var edmg=(Math.floor(Math.random()*11));
    var nHP=myHP - edmg;

    alert("You deal " + dmg + " damage!");
    alert("You are dealt " + edmg + " damage!");
    document.getElementById("hp").innerHTML=nHP;
}
</script>

So, I make a paragraph with an id of "hp" and I can see it change when I click the attack button. However, it always does 50-edmg. I.e. I get attacked for 3, my HP is 47. Next, I get attacked for 2, my HP is 48 and not 45 because it is always subtracting from the base. How can I make it so that the myHP variable is updated live and therefore always reflects the correct number?

Upvotes: 2

Views: 2999

Answers (3)

AlanFoster
AlanFoster

Reputation: 8306

You need to update the health value.

myHP = myHP - edmg;
alert("You deal " + dmg + " damage!");
alert("You are dealt " + edmg + " damage!");
document.getElementById("hp").innerHTML= myHP;

Upvotes: 1

ziesemer
ziesemer

Reputation: 28687

You are never updating the myHP variable. The fix could be as simple as adding:

myHP = nHP;

as the last line of your last script.

Upvotes: 2

Alex M
Alex M

Reputation: 3513

You aren't assigning the new health back to the myHP variable

myHP -= edmg

Upvotes: 1

Related Questions