Slack 'n' Hash

Javascript Dice Bag

Back in 2006, I uploaded an article that contained JavaScript code for a dice bag. It was a horrible, monolithic and unwieldy thing; involving the creation of a new class, some unnecessary methods and properties. I released the thing under the GNU General Public License, thinking that it'd be nice to give something back.

As far as gifts go, it was probably the equivalent of an itchy, ill-fitting sweater from an aunt you don't like very much. Looking back on it, my first thought was "I can't believe I coded that!" But then we always say that when we look at old code, don't we? I mean, the ZIP archive was 9.6 KB for Bod's sake!

Here's a newer, simpler, cleaner and better version. And I am very sorry for the earlier version.

/*
    dicebag.js: a simple javascript die roller
    Copyright (C) 2008 Phil Smith
    WWW: http://www.slacknhash.net
    Email: slacknhash@googlemail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 
    USA
*/

function dice(diesize) {
  // This function just rolls a die and returns the result. No modifiers. 
  // Example: x = dice(6);
  result = (Math.ceil(Math.random() * diesize));
  return result;
}

function dicebag(multiple,diesize,modifier) {
  // This function rolls MULTIPLE dice with DIESIZE number of sides, and adds
  // MODIFIER.
  // Example: x = dicebag(2,6,6); // That rolls 2d6+6.
  result = 0;
  for (count = 1; count <= multiple; count++) {
    result += Number(dice(diesize));
  }
  result += Number(modifier);
  return result;
}

Last modified: 26/11/08. All material ©2003-8 its creators.

No widgets?

This sidebar is set aside for our gadgets. If you want to add a die roller or one of our other widgets, then go to the Customise Panel to add some.

I'm always after new excuses to code, so if you can think of a gadget this site needs, mail me and I might just code it for you!