Math.floor(Math.random())在首次使用后不显示随机数

时间:2014-02-06 15:38:35

标签: javascript math random floor

我正在编写这个非常简单的游戏,并希望每个玩家每次击中时都会造成伤害。出于某种原因,第一个匹配具有随机值,但接下来的后续值完全相同。它几乎就像Math.floor(Math.random())函数运行一次,然后停止并使用它第一次给出的值。

以下是代码:

this.attackpoints=Math.floor((Math.random()*10)+5);

this.attack=function(opponent) {

    opponent.hitpoints-=this.attackpoints;
    console.log(this.name + " has " + this.hitpoints + " hitpoints and " + this.energy + " energy.");
    console.log(this.name + " just hit " + opponent.name + ".");

}

5 个答案:

答案 0 :(得分:1)

初始化Math.random的值时,您只运行this.attackpoints次。

你可以这样做:

this.getAttackPoints = function() {
  return Math.floor((Math.random()*10)+5);
}

this.attack=function(opponent) {
    opponent.hitpoints-=this.getAttackPoints();
    console.log(this.name + " has " + this.hitpoints + " hitpoints and " + this.energy + " energy.");
    console.log(this.name + " just hit " + opponent.name + ".");

}

答案 1 :(得分:0)

使用功能 -

this.attackpoints= function () {
  return Math.floor((Math.random()*10)+5);
};

然后通过调用函数获得一个新的随机值 -

opponent.hitpoints-=this.attackpoints();

答案 2 :(得分:0)

this.attackpoints=function(){ return Math.floor((Math.random()*10)+5); };

this.attack=function(opponent) {

    opponent.hitpoints-=this.attackpoints();
    console.log(this.name + " has " + this.hitpoints + " hitpoints and " + this.energy + " energy.");
    console.log(this.name + " just hit " + opponent.name + ".");

}

答案 3 :(得分:0)

不幸的是你没有发布我们可以看到的代码,上面的代码被调用,但我的猜测是你只能调用

this.attackpoints=Math.floor((Math.random()*10)+5);

一次又一次,你只使用始终保持不变的攻击点变量。

答案 4 :(得分:0)

那是因为你总是调用你对象的攻击点变量。相反,你应该调用一个再次计算攻击点的方法,而不是从变量中获取一个。

相关问题