⚃ 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>
blog comments powered by Disqus