Share your repls and programming experiences

← Back to all posts
How do I make a die
FranklinStopar (20)

I need help making a class that rolls a die twice. I then need to get it to add both rolls but when I try to add them it shows NaN instead of what they add up to be...for example if you roll a 1 and a five it should show a 6...if you can help it would be great...Thanks.

Comments
hotnewtop
mwilki7 (1137)

You can get the value of the die roll from calling the getDieTotal() function like this:

console.log( Roll.getDieTotal() );
mwilki7 (1137)

@FranklinStopar

        getDie1()
	{
		return Die1
	}
	getDie2()
	{
		return Die2
	}

Die1 and Die2 should be referenced as
this.Die1 and this.Die2

        getDie1()
	{
		return this.Die1
	}
	getDie2()
	{
		return this.Die2
	}
notGilbert (45)

You're getting NaN because you're adding 2 Objects (of RollDie) together.

Whenever you add 2 incompatible types, you always get NaN,
ie:

Object (RollDie) + Object(RollDie) = NaN
Map + Array = NaN

try this:

function rollOnce() {
  return Math.floor(Math.random() * 6) + 1;
}

// you can call this whenever you want
function roll2Die() {
  return rollOnce() + rollOnce()
}
FranklinStopar (20)

@notGilbert
it has to be in a class not a function...

FranklinStopar (20)

@notGilbert thats why I need help doing it....like I know how to make one in a function