Loading a Scrabble Dictionary into Flash

posted Wednesday, October 27, 2010 in gaming

You can't make very many word games without using a dictionary or wordlist. Even finding such a dictionary took a bit of searching, but eventually I found a Scrabble dictionary text file. In it are the 80,000 or so words from the OSPD4 (Official Scrabble Player's Dictionary, version 4), one word per line. If you need a more inclusive dictionary you can find a similar version of SOWPODS (the international version) if you hunt around for it, but this one worked for me because it's pretty exhaustive and still includes tons of words that most people don't know. Embedding it into a flash game was a little trickier, though.

Of course, you can use a simple URLLoader to read a text file, but the drawback of that approach is that the file is read externally at run-time, so it introduces an external dependency to your flash game – the text file must be in the same folder as your game's SWF file on any website to which it is published, or the game won't work. After much searching I found a method for using the embed command to ensure that the text file is imported directly into your SWF file at compile-time, thus not making your game dependent upon an external file.

Here's my AS3 ScrabbleDictionary class:

package {
    import flash.utils.ByteArray;
	public class ScrabbleDictionary extends ByteArray {
		[Embed(source="f2-33.txt",mimeType="application/octet-stream")]
		private static const ScrabbleFile:Class;
		private static var words:Array = new ScrabbleFile().toString().split("\n");
		public function ScrabbleDictionary() {
		}
		public static function contains(word:String):Boolean {
			return words.indexOf(word.toLowerCase()) > -1;
		}
		public static function random():String {
			return words[Math.floor(Math.random() * words.length)];
		}
	}
}

Just put that into a class file named ScrabbleDictionary.as. Make sure the file to be embedded (in this case, f2-33.txt, the OSPD4 text file linked at the beginning of this post) is anywhere in your class path and, if you use the class on one or more of your projects by calling one of its static functions, it will automatically import the text file into your library to be compiled and read the word list into an array for you. I included a couple public methods for checking to see if a word is contained in the dictionary and for selecting a random word – feel free to expand upon it to suit your needs!

You can also use this method to embed any text file, or in fact any file at all as long as you can process it from the ByteArray that is generated.

Related Entries


Next: →
Your Very Own Lightsaber
← Previous:
Old Google Ad Format Codes

Recent / Home

Subscribe

Most Popular

Other Resources

Tags

Archives