Generating Random Words

To play a game of Hangman, the app needs access to a list of words to play. Luckily lists of words are available in a number of places on the web. One of the best spots to grab a list is at http://wordlist.sourceforge.net/. Of the myriad lists available there, the best list for the purposes of Hangman is the 12dicts list, which contains a list approximating the common core of the vocabulary of American English.

You can download the original 12dicts source files from http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip, but the chapter code has a file called words.txt that is a single list of the most common words, which has been slightly modified to adjust the line endings. The 12dicts file uses the Automatically Generated Inflection Database (AGID) list as a source, so the license for the AGID is included in the chapter download. It can be used freely but must include the copyright notice if distributed.

To indicate words that are somehow peculiar, the words.txt has some files marked with punctuation at the end; the code to generate a random word will be set up to ignore these words.

The basic mechanism to generate a random word is to load the words.txt file into a large array and then pick a random item out of the array until one is found that consists only of alphabetical characters.

This code will be incorporated into the main game later in this chapter, but to play around with generating random words, you can create a file called word.js using ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.