This question looks like homework, did you write the code so far yourself? If you didn't, try to read through it and understand what each function is doing and where it is being invoked from.
the random value should be different from the one in enemies
Q: How can I generate random integers?
A: Here is a general-use function to generate pseudo-random integers
function rand_int(max, min) {
min = min | 0;
if (max === (max | 0))
if (max < min)
throw new RangeError("Range cannot be negative [" + min + '..' + max + ']');
else
return min + Math.floor(Math.random() * (max - min + 1));
throw new TypeError("Expected Integer for max but recieved: " + max);
}
Explanation: The random number is coming from Javascript's own Math.random
which is between 0
and (but not equal to) 1
. The x | 0
used to convert variables to 32-bit integers. Math.floor
is used to change the floating point number into an Integer by always "rounding down". It works better than x | 0
for distributions over positive-and-negative numbers
can there aso be a heal option to randomly raise players power
Q: How can I add a random number to player's health?
A: Make a second <input>
type button which causes something like the following to happen
playerHealth += rand_int(10); // add between 0 and 10
and decrease it too because enemy is still attacking
Q: Where do I put the code for the enemy turn?
A: Make a copy of the function hitEnemy
, rename it to hitPlayer
and change all occurances of enemy
to player
inside it. Then invoke it after hitEnemy
is called, for example
<input
type="button" name="doit" id="doit"
value="Attack!" onclick="hitEnemy();hitPlayer();"
/>