繁体   English   中英

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

[英]Math.floor(Math.random()) not displaying random numbers after first use

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

}

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

您可以改为:

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

}

使用功能-

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

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

opponent.hitpoints-=this.attackpoints();
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 + ".");

}

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

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

一次又一次,您只能使用Attackpoints变量,该变量始终保持不变。

那是因为您总是调用对象的Attackpoints变量。 相反,您应该调用一种方法来重新计算攻击点,并且不要从变量中获取攻击点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM