Game Development Reference
In-Depth Information
9 - Hangman
59. words = 'ant baboon badger bat bear beaver camel cat clam
cobra cougar coyote crow deer dog donkey duck eagle
ferret fox frog goat goose hawk lion lizard llama mole
monkey moose mouse mule newt otter owl panda parrot
pigeon python rabbit ram rat raven rhino salmon seal
shark sheep skunk sloth snake spider stork swan tiger
toad trout turkey turtle weasel whale wolf wombat
zebra'.split()
As you can see, this line is just one very long string, full of words separated by spaces.
And at the end of the string, we call the split() method. The split() method changes
this long string into a list, with each word making up a single list item. The "split" occurs
wherever a space occurs in the string. The reason we do it this way, instead of just writing
out the list, is that it is easier for us to type as one long string. If we created it as a list to
begin with, we would have to type: ['ant', 'baboon', 'badger', ... and so on,
with quotes and commas for every single word.
For an example of how the split() string method works, try typing this into the shell:
>>> 'My very energetic mother just served us nine
pies'.split()
['My', 'very', 'energetic', 'mother', 'just',
'served', 'us', 'nine', 'pies']
>>>
The result is a list of nine strings, one string for each of the words in the original string.
The spaces are dropped from the items in the list. Once we've called split() , the words
list will contain all the possible secret words that can be chosen by the computer for our
Hangman game. You can also add your own words to the string, or remove any you don't
want to be in the game. Just make sure that the words are separated by spaces.
How the Code Works
Starting on line 61, we define a new function called getRandomWord() , which has a
single parameter named wordList . We will call this function when we want to pick a
single secret word from a list of secret words.
61. def getRandomWord(wordList):
62. # This function returns a random string from the
passed list of strings.
63. wordIndex = random.randint(0, len(wordList) - 1)
64. return wordList[wordIndex]
Search WWH ::




Custom Search