From d6f2e9b32427e0941de2ec8ce974b88b34a401de Mon Sep 17 00:00:00 2001 From: Douglas Muth Date: Wed, 1 Feb 2017 00:02:19 -0500 Subject: [PATCH] Wrote getNumValuesFromNumDice() and rollDice(). --- main.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/tests.js | 25 +++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/main.js b/main.js index 01db141..bed8424 100644 --- a/main.js +++ b/main.js @@ -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. * diff --git a/tests/tests.js b/tests/tests.js index 8a5e9e9..30f0860 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -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"); + + +}); + + +