Tuesday 20 December 2011

Scategories Letter Generator

A couple of weeks ago I was talking to a M's brother's girlfriend, C, about board games. She told me about a game she used to play called Scategories. The idea is that you have a list of categories and come up with a word for each one beginning with a certain letter. The letter is determined by rolling dice and a corresponding letter is referenced by the number rolled. C no longer has a copy of this game, but likes playing it. I thought that this a perfect opportunity to play around with some JavaScript. Demo here.

The HTML and CSS for this is dead simple, so I'm not going to bother to go through it in detail. The button to bind the event to is button#generate, and the letter appears in div#letter.
To bind the event to the button I used jQuery. I wanted to use jQuery to populate the div with the generated letter because the code would be much cleaner. This is an incredibly short bit of scripting.

$(document).ready(function(){
$('#generate').click(function() {
$('#letter').text(String.fromCharCode(65 + Math.round(Math.random() * 25)));
});
});


The clever part here is how the letter is generated. I've generated a random number under 25 (26 letters in English alphabet, 0 based) and then added 65 to it. This gives the decimal code from the ASCII table for upper case, English alphabet characters. Change this to 97 if you want lower case letters. By feeding this into the function String.fromCharCode you change your randomly generated number into a letter.

No comments:

Post a Comment