Wrote getNumValuesFromNumDice() and rollDice().

This commit is contained in:
Douglas Muth 2017-02-01 00:02:19 -05:00
parent acf5389ff7
commit d6f2e9b324
2 changed files with 74 additions and 0 deletions

49
main.js
View file

@ -121,6 +121,55 @@ Diceware.convertBase6ToDice = function(roll, num_dice) {
} // End of convertBase6ToDice()
/**
* Get the maximum value from the number of dice we're rolling.
* This is in a separate function so it is testable.
*/
Diceware.getNumValuesFromNumDice = function(num_dice) {
var retval;
if (num_dice == 0) {
throw("Number of dice cannot be zero!");
} else if (num_dice < 0){
throw("Number of dice is negative!");
}
retval = Math.pow(6, num_dice);
return(retval);
} // End of getNumValuesFromNumDice()
/**
* This is our main entry point for rolling dice.
*
* Get our maximum number for a random value, turn it into base-6,
* then turn it into a dice roll!
*
*/
Diceware.rollDice = function(num_dice) {
var retval = [];
var max = Diceware.getNumValuesFromNumDice(num_dice);
var random = Diceware.getRandomValue(max);
var base6 = Diceware.getBase6(random, num_dice);
var dice = Diceware.convertBase6ToDice(base6, num_dice);
retval = dice;
return(retval);
} // End of rollDice()
/**
* Roll a die.
*

View file

@ -66,3 +66,28 @@ QUnit.test("Convert Base 6 to Dice Roll", function(assert) {
});
QUnit.test("Roll some dice!", function(assert) {
//
// Test out our helper function first
//
assert.equal(Diceware.getNumValuesFromNumDice(1), 6);
assert.equal(Diceware.getNumValuesFromNumDice(2), 36);
assert.equal(Diceware.getNumValuesFromNumDice(3), 216);
assert.equal(Diceware.getNumValuesFromNumDice(4), 1296);
assert.throws(function() {Diceware.getNumValuesFromNumDice(0); }, /zero/, "Zero");
assert.throws(function() {Diceware.getNumValuesFromNumDice(-1); }, /negative/, "Negative value");
assert.equal(Diceware.rollDice(1).length, 1);
assert.equal(Diceware.rollDice(3).length, 3);
assert.equal(Diceware.rollDice(8).length, 8);
assert.throws(function() {Diceware.rollDice(0); }, /zero/, "Zero");
assert.throws(function() {Diceware.rollDice(-1); }, /negative/, "Negative value");
});