Reputation: 45
I want to add a random modifier to this code, something that will either add to or subtract from the damage based off of a range of +-20% of the base value. The damage would randomize between a range of 80% of result to 120% of result. For a numeric example:
attacker.Strength(20) - defender.Defense(10) = result
20 - 10 = range(8 to 12)
var Fight = function (attacker, defender) {
var result;
result = (attacker.Strength - defender.Defense);
defender.HP = defender.HP - result;
if(defender.HP >= 1) {
return defender.Name + " has taken " + result + " damage!";
} else {
return defender.Name + " has been slain";
}
};
Upvotes: 1
Views: 367
Reputation: 34367
For eaxact +/- 20%, use random
to generate two numbers only i.e. 0, 1
.
If 0
, treat it as +
and if 1
, treat it as -
e.g. below:
var randomNum = Math.round(Math.random()); //it will return 0 or 1
if(randomNum ==0){
//write +20% code here
result = (attacker.Strength - defender.Defense)*1.2;
}else{
//write -20% code here
result = (attacker.Strength - defender.Defense)*0.8;
}
EDIT: For range based, its much simpler.
var factor = 0.8 + Math.random()*0.4;
result = (attacker.Strength - defender.Defense)*factor ;
Upvotes: 0
Reputation: 664548
Math.random
returns a number between zero and one. Map this to your range from 0.8
to 1.2
with this:
var factor = Math.random() * 0.4 + 0.8;
// | | |
// [0, 1[ | |
// \ / |
// [0, 0.4[ /
// \ /
// [0.8, 1,2[
var result = Math.round((attacker.Strength - defender.Defense) * factor);
Not sure whether you want to round somewhere so that your player's health points are always natural numbers. If not, you should change your death condition to defender.HP > 0
.
Upvotes: 3
Reputation: 224932
As in Math.random() * 0.4
?
result = (attacker.Strength - defender.Defense) * (0.8 + Math.random() * 0.4);
Upvotes: 1