HTML and CSS Reference
In-Depth Information
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 the code in Listing 22-4 , which logs 10 random
words to the console.
Listing 22-4: Generating 10 random words
var fs = require('fs'),
words = fs.readFileSync('words.txt').toString().split("\n");
function randomWord() {
var word;
do {
word = words[Math.floor(Math.random()*words.length)];
} while(!word.match(/^\w+$/) || word.length < 5)
return word;
for(var i=0;i<10;i++) {
You can see the first thing the code does is load up the words.txt file and split it by new lines. The ran-
domWord method then just picks a random word out of the list of words and checks using a regular expression
that it contains only word characters ( \w ) and has at least five letters.
Running this file with node word.js should log 10 random words to the console every time it is run. The
words.txt file has more than 32,000 words in it, so there should be plenty of variety.
Creating Twitter Hangman
With the libraries in place to create the game, it's time to dig in to the actual code for the game. The main idea is
to post a tweet with the blanks for a game of Hangman and respond to tweets from users guessing the missing
letters. The application responds to any user that sends tweets at it with the number of times that letter appears
and tweets the updated board state.
The complete code for the game appears in Listing 22-5 . Replace any code you have in app.js with the
code in Listing 22-5 . You need to replace the accountName and Twitter configuration variables as you did
Listing 22-5: Twitter Hangman
var twitter = require("ntwitter"),
fs = require('fs'),
words = fs.readFileSync('words.txt').toString().split("\n");
Search WWH ::

Custom Search