Game Development Reference
In-Depth Information
9 - Hangman
Replacing the Underscores with Correctly Guessed Letters
77. for i in range(len(secretWord)): # replace blanks
with correctly guessed letters
78. if secretWord[i] in correctLetters:
79. blanks = blanks[:i] + secretWord[i] + blanks
[i+1:]
Let's pretend the value of secretWord is 'otter' and the value in
correctLetters is 'tr' . Then len(secretWord) will return 5 . Then range
(len(secretWord)) becomes range(5) , which in turn returns the list [0, 1, 2,
3, 4] .
Because the value of i will take on each value in [0, 1, 2, 3, 4] , then the for
loop code is equivalent to this:
if secretWord[0] in correctLetters:
blanks = blanks[:0] + secretWord[0] + blanks[1:]
if secretWord[1] in correctLetters:
blanks = blanks[:1] + secretWord[1] + blanks[2:]
if secretWord[2] in correctLetters:
blanks = blanks[:2] + secretWord[2] + blanks[3:]
if secretWord[3] in correctLetters:
blanks = blanks[:3] + secretWord[3] + blanks[4:]
if secretWord[4] in correctLetters:
blanks = blanks[:4] + secretWord[4] + blanks[5:]
(By the way, writing out the code like this is called loop unrolling .)
If you are confused as to what the value of something like secretWord[0] or
blanks[3:] is, then look at this picture. It shows the value of the secretWord and
blanks variables, and the index for each letter in the string.
Figure 9-2: The indexes of the blanks and secretWord strings.
Search WWH ::




Custom Search