⚃ Rolling Dice with JS and Unicode ⚂

I recently discovered the unicode xscreensaver hack, and have had it running on my secondary monitor for the heck of it. I found out that there are dice face symbols, and I was inspired to do something with them.

So, I made a simple Unicode-dice roller in JavaScript. I know the same thing could be done in JS, but this way you can roll some numbers to paste into Twitter or something, if you feel like it.

Enter number of Dice to roll:

Result:  

The code is extremely simple, calling Math.floor on the result of Math.random n times, then using a small table of the codepoints from U+2680 to U+2685 to build a string.

Here is the code for anyone interested:

<script type="text/javascript">
function roll(n) {
    var dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685'];
    var results = '';
    for (var i=0; i<n; i++) {
        results += dice[Math.floor(Math.random()*6)] + ' ';
    }
    return results;
}
 
function doRoll(countElem, resultElem) {
    document.getElementById(resultElem).innerHTML = 
        roll(parseInt(document.getElementById(countElem).value));
}
</script>
 
Enter number of Dice to roll:<br><input type="text" id="dice-roll-number" />
<input type="button" onclick="doRoll('dice-roll-number', 'dice-roll-result')" value="Roll!" />
 
Result: <span style="font-size: 64px; line-height: normal" id="dice-roll-result"></span>

Tags: ,

5 Responses to “⚃ Rolling Dice with JS and Unicode ⚂”

  1. Simon Proctor Says:

    That’s nice, but a bit verbose.

    
    function roll(n) {
      var results = '';
      for ( var i=0;i < n;i++ ) {
        results += String.fromCharCode( 9856 + Math.round( Math.random() * 6 ) ) + ' ';
      }
      return results;
    }
    

    You don’t need your list of unicode characters as fromCharCode will create them. you just need to know the decimal code point of the 1 spot dice as they go in sequence.

  2. pib Says:

    Yeah, I was thinking of doing it that way, but I didn’t, for no particular reason, really.

  3. Simon Proctor Says:

    Of course then I thought of this.

    
    Dice = { toString : function() { return String.fromCharCode( 9856 + Math.round( Math.random() * 6 ) ) } }
    

    Every time you request it you get a new dice string.

  4. The Big Lebowski Says:

    Doesn’t work in chrome :(

  5. pib Says:

    Works for me in Chrome. Perhaps you don’t have a unicode font that has those glyphs?

Leave a Reply