Advertisement
Guest User

r/programmingprompts - dicebag

a guest
Nov 11th, 2014
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Die(sides) {
  2.             if (sides == undefined) {
  3.                 this.sides = 6;
  4.             } else {
  5.                 this.sides = sides;
  6.             }
  7.         }
  8.  
  9.         Die.prototype.roll = function() {
  10.             if (this.held === 1) {
  11.                 return this.latestRoll;
  12.             } else {
  13.                 this.latestRoll = Math.floor((Math.random() * this.sides) + 1);
  14.                 return this.latestRoll;
  15.             }
  16.         };
  17.        
  18.         Die.prototype.toggleHold = function() {
  19.             if (this.held === 1) {
  20.                 this.held = 0;
  21.             } else {
  22.                 this.held = 1;
  23.             }
  24.             return this.held;
  25.         };
  26.  
  27.         var singleDie = new Die();
  28.        
  29.         var dicebag = {
  30.             dice: [], //array with all dice ever
  31.  
  32.             addDie: function(sides) { //adds die to end
  33.                 this.dice.push(new Die(sides));
  34.                 return this.dice;
  35.             },
  36.  
  37.             removeDie: function(index) { //removes die at index
  38.                 this.dice.pop(this.dice[index]);
  39.                 return this.dice;
  40.             },
  41.  
  42.             rollAll: function() { //rolls all dice
  43.                 var result = [];
  44.                 for (var i = 0; i < this.dice.length; i++) {
  45.                     result.push(this.dice[i].roll());
  46.                 }
  47.                 this.latestResult = result;
  48.                 return result;
  49.             },
  50.             sumLastRes: function() {
  51.                 var sum = 0;
  52.                 for (var i = 0; i < this.latestResult.length; i++) {
  53.                     sum += this.latestResult[i];
  54.                 }
  55.                 return sum;
  56.             },
  57.  
  58.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement