Question

I'm programming this really simple game, and want the damage done by each player random each hit. For some reason, the first hit has a random value, but then the next following values are exactly the same. It is almost like the Math.floor(Math.random()) function runs once, then stops and uses the value it was given the first time.

Here's the code:

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

}
Was it helpful?

Solution 2

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

}

OTHER TIPS

You're only running Math.random once, when you initialize the value of this.attackpoints.

You could do this instead:

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

}

Use a function -

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

Then get a new random value by invoking your function -

opponent.hitpoints-=this.attackpoints();

Unfourtunately you didn't post the code where we could see, where your code above is called, but my guess is that you only call

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

once and afterwards you only use the attackpoints variable which stays the same all the time.

That's because you always call the attackpoints variable of your object. Instead you should call a method that calculates the attackpoints again, and doesn't take the one from the variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top