1

我正在编写这个非常简单的游戏,并且希望每个玩家每次击中随机造成的伤害。由于某种原因,第一个命中具有随机值,但随后的后续值完全相同。这几乎就像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 + ".");

}
4

5 回答 5

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 + ".");

}
于 2014-02-06T15:43:29.807 回答
0

使用功能 -

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

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

opponent.hitpoints-=this.attackpoints();
于 2014-02-06T15:43:14.723 回答
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 + ".");

}
于 2014-02-06T15:43:44.107 回答
0

不幸的是,您没有将代码发布在我们可以看到的地方,上面的代码被调用的地方,但我的猜测是您只调用

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

一次和之后,您只使用始终保持不变的攻击点变量。

于 2014-02-06T15:44:04.210 回答
0

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

于 2014-02-06T15:44:10.237 回答