Game Development Reference
In-Depth Information
print(letter, end=' ')
print()
This for loop one line 71 will display all the missed guesses that the player has made.
When you play Hangman on paper, you usually write down these letters off to the side so
you know not to guess them again. On each iteration of the loop the value of letter will
be each letter in missedLetters in turn. Remember that the end=' ' will replace the
newline character that is printed after the string is replaced by a single space character.
If missedLetters was 'ajtw' then this for loop would display a j t w .
Displaying the Secret Word with Blanks
So by this point we have shown the player the hangman board and the missed letters. Now
we want to print the secret word, except we want blank lines for the letters. We can use the _
character (called the underscore character) for this. But we should print the letters in the
secret word that the player has guessed, and use _ characters for the letters the player has not
guessed yet. We can first create a string with nothing but one underscore for each letter in
the secret word. Then we can replace the blanks for each letter in correctLetters . So if
the secret word was 'otter' then the blanked out string would be '_____' (five _
characters). If correctLetters was the string 'rt' then we would want to change the
blanked string to '_tt_r' . Here is the code that does that:
75. blanks = '_' * len(secretWord)
76.
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:]
80.
81. for letter in blanks: # show the secret word with
spaces in between each letter
Line 75 creates the blanks variable full of _ underscores using string replication.
Remember that the * operator can also be used on a string and an integer, so the expression
'hello' * 3 evaluates to 'hellohellohello' . This will make sure that blanks
has the same number of underscores as secretWord has letters.
Then we use a for loop to go through each letter in secretWord and replace the
underscore with the actual letter if it exists in correctLetters . Line 79 may look
confusing. It seems that we are using the square brackets with the blanks and
secretWord variables. But wait a second, blanks and secretWord are strings, not
lists. And the len() function also only takes lists as parameters, not strings. But in Python,
many of the things you can do to lists you can also do to strings:
Search WWH ::




Custom Search