Search code examples
javascriptmathrandomfloor

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

}

Solution

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