⚃ 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>

January 7th, 2010 at 8:39 am
That’s nice, but a bit verbose.
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.
January 7th, 2010 at 11:15 am
Yeah, I was thinking of doing it that way, but I didn’t, for no particular reason, really.
January 7th, 2010 at 11:25 am
Of course then I thought of this.
Every time you request it you get a new dice string.
January 7th, 2010 at 11:45 am
Doesn’t work in chrome
January 7th, 2010 at 1:09 pm
Works for me in Chrome. Perhaps you don’t have a unicode font that has those glyphs?