1

我想在此代码中添加一个随机修饰符,该修饰符将根据基础值的 +-20% 范围增加或减少伤害。伤害会在结果的 80% 到结果的 120% 之间随机化。对于数字示例:

攻击者.力量(20) - 防御者.防御(10) = 结果

20 - 10 = 范围(8 到 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";
    }
};
4

3 回答 3

3

Math.random返回一个介于 0 和 1 之间的数字。将此映射到您的范围 from 0.8to 1.2

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.

于 2012-10-14T16:44:47.240 回答
1

Math.random() * 0.4?

result = (attacker.Strength - defender.Defense) * (0.8 + Math.random() * 0.4);
于 2012-10-14T16:43:19.050 回答
0

对于精确的 +/- 20%,random仅用于生成两个数字,即0, 1.

如果0,则将其视为+,如果1,则将其视为-如下:

   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;
   }

编辑:对于基于范围的,它要简单得多。

  var factor = 0.8 + Math.random()*0.4;
  result = (attacker.Strength - defender.Defense)*factor ;
于 2012-10-14T16:44:28.820 回答