User Tools

Site Tools


blog:2009:dice_roller
Please note, that this is an old archived version of this site. Check out the new version at andunix.net!

Dice Roller

I programmend a small dice roller in javascript. You enter the number of dice, sides and the offset and press the button “roll”. The script shows the individual dice and the resulting sum. For convenience, there is a second form where you can just enter the number of dice and press the butten for the type of dice. At the bottom, there are some links of six- and eightsided dice, which are often needed in roleplaying games. You can also create bookmarks for dice, e.g. dice.html?n=3&s=8&o=5 for a 3d8+5 (three eight-sided dice plus five).

The dice roller is at http://andunix.net/pub/dice.html.

And here's the code. You can use it under the Apache License, Version 2.0 or CC Attribution 3.0 Unported.

HTML Form

  <form name="rolldice" method="GET">
      <input type="text" name="n" size="2"/>
      d
      <input type="text" name="s" size="2"/>
      +
      <input type="text" name="o" size="4"/>
      <input type="submit" value="roll"/>
      <input disabled="true" type="text" name="r" size="4"/>
  </form>

Javascript Code

function roll() {
  var count = parseInt(document.rolldice.n.value);
  var sides = parseInt(document.rolldice.s.value);
  var offset = parseInt(document.rolldice.o.value);
  var result = offset;
  var rolls = "";
  var roll;
  for (var i = 0; i < count; i++) {
    roll = 1+Math.floor(Math.random()*sides);
    result += roll;
    rolls += " "+roll;
  }
  document.rolldice.r.value = result;
  document.getElementById("rolls").innerHTML = rolls;
  return false;
}
function load() {
  var n;
  var s;
  var o;
  var params = window.location.search.split("&");
  for (var i = 0; i < params.length; i++) {
    var eqIx = params[i].indexOf("=");
    var key = params[i].slice(i==0?1:0, eqIx);
    var value = params[i].slice(eqIx+1);
    if (key=="n") {
      n = value;
    } else if (key=="s") {
      s = value;
    } else if (key=="o") {
      o = value;
    }
  }
  if (!(n>0)) { n = 1; }
  if (!(s>0)) { s = 6; }
  o = Number(o);
  if (isNaN(o)) { o = 0; }
  document.rolldice.n.value=n;
  document.rolldice.s.value=s;
  document.rolldice.o.value=o;
  roll();
}
blog/2009/dice_roller.txt · Last modified: 2009-02-18 19:25 (external edit)