Game Development Reference
In-Depth Information
The function getRandomWord() is passed a list of strings as the argument for the
wordList parameter. On line 63, we will store a random index in this list in the
wordIndex variable. We do this by calling randint() with two arguments. Remember
that arguments in a function call are separated by commas, so the first argument is 0 and
the second argument is len(wordList) - 1 . The second argument is an expression
that is first evaluated. len(wordList) will return the integer size of the list passed to
getRandomWord() , minus one.
The reason we need the - 1 is because the indexes for list start at 0, not 1. If we have a
list of three items, the index of the first item is 0, the index of the second item is 1, the
index of the third item is 2. The length of this list is 3, but the index 3 is after the last index.
This is why we subtract 1 from the length.
For example, if we passed ['apple', 'orange', grape'] as an argument to getRandomWord
() , then len(wordList) would return the integer 3 and the expression 3 - 1 would evaluate
to the integer 2.
That means that wordIndex would contain the return value of randint(0, 2), which means
wordIndex would equal 0, 1, or 2. On line 64, we would return the element in wordList at
the integer index stored in wordIndex.
Let's pretend we did send ['apple', 'orange', grape'] as the argument to
getRandomWord() and that randint(0, 2) returned the integer 2 . That would
mean that line 64 would become return wordList[2] , which would evaluate to
return 'grape' . This is how the getRandomWord() returns a random string in the
wordList list. The following code entered into the interactive shell demonstrates this:
>>> import random
>>> print(wordIndex)
2
>>> print(['apple', 'orange', 'grape'][wordIndex])
grape
>>>
And remember, we can pass any list of strings we want to the getRandomWord()
function, which is what makes it so useful for our Hangman game.
Displaying the Board to the Player
Next we need to create another function which will print the hangman board on the
screen, along with how many letters the player has correctly (and incorrectly) guessed.
66. def displayBoard(HANGMANPICS, missedLetters,
correctLetters, secretWord):
Search WWH ::




Custom Search