Game Development Reference
In-Depth Information
9 - Hangman
134. if len(missedLetters) == 6: # 6 is the last index in the
HANGMANPICS list
But it is easier to just use
len(HANGMANPICS) - 1
instead.
So, when the length of the
missedLetters
string is equal to
len(HANGMANPICS)
- 1
, we know the player has run out of guesses and has lost the game. We print a long
string telling the user what the secret word was, and then set the
gameIsDone
value to the
Boolean value
True
. This is how we will tell ourselves that the game is done and we
should start over.
Remember that when we have \n in a string, that represents the newline character.
139. # Ask the player if they want to play again (but only
if the game is done).
140. if gameIsDone:
141. if playAgain():
142. missedLetters = ''
143. correctLetters = ''
144. gameIsDone = False
145. secretWord = getRandomWord(words)
If the player won or lost after guessing their letter, then our code would have set the
gameIsDone
variable to
True
. If this is the case, we should ask the player if they want
to play again. We already wrote the
playAgain()
function to handle getting a yes or no
from the player. This function returns a Boolean value of
True
if the player wants to play
another game of Hangman, and
False
if they've had enough.
If the player does want to play again, we will reset the values in
missedLetters
and
correctLetters
to blank strings, set
gameIsDone
to
False
, and then choose a new
secret word by calling
getRandomWord()
again, passing it the list of possible secret
words.
This way, when we loop back to the beginning of the loop (on line 112) the board will be
back to the start (remember we decide which hangman picture to show based on the length
of
missedLetters
, which we just set as the blank string) and the game will be just as
the first time we entered the loop. The only difference is we will have a new secret word,
because we programmed
getRandomWord()
to return a randomly chosen word each
time we call it.
There is a small chance that the new secret word will be the same as the old secret word,
but this is just a coincidence. Let's say you flipped a coin and it came up heads, and then
you flipped the coin again and it also came up heads. Both coin flips were random, it was
just a coincidence that they came up the same both times. Accordingly, you may get the