Tobias Birkeland
Tobias Birkeland

Reputation: 21

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

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

}

Upvotes: 1

Views: 920

Answers (5)

Mathias G.
Mathias G.

Reputation: 5085

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.

Upvotes: 0

morten.c
morten.c

Reputation: 3515

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.

Upvotes: 0

chrisboustead
chrisboustead

Reputation: 1563

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

}

Upvotes: 0

Tibos
Tibos

Reputation: 27823

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

}

Upvotes: 1

John Strickler
John Strickler

Reputation: 25421

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();

Upvotes: 0

Related Questions