I’m working on a simple game and I’ve gotten as far as coding it so that when you click on an attack button it should generate a random number based on a base and strength then subtract that from the enemy’s health but the subtracting part doesn’t seem to work. It always outputs NaN.
<head>
<script>
var playerHealth=100;
var enemyHealth=100;
var strength=10;
function begin(){
document.getElementById('playerhealth').innerHTML = playerHealth;
document.getElementById('enemyhealth').innerHTML = enemyHealth;
}
function hitEnemy(){
var attack=Math.floor(Math.random()*20 + strength);
var enemyHealth = enemyHealth - attack;
document.getElementById('damage').innerHTML = attack;
document.getElementById('enemyhealth').innerHTML = enemyHealth;
}
</script>
</head>
<body onload="begin()">
<input type="button" name="doit" id="doit" value="Attack!" onclick="hitEnemy();">
<br /><span>playerhealth</span>
<div style="font-size:3em;" id="playerhealth"></div>
<span>enemyhealth</span>
<div style="font-size:3em;" id="enemyhealth"></div>
<br />
<span>You Did:</span><span style="font-size:3em;" id="damage"></span><span>damage</span>
</body>
It may have something to do with not specifically making sure that they’re integers but I’m not sure how to do that.
because you redefine the enemyHealth var inside hitEnemy function. Remove the var to fix it.