Game Development Reference
In-Depth Information
Because the player's guessed letter was wrong, we will add it to the missedLetters
string. This is like what we did on line 119 when the player guessed correctly.
133. # Check if player has guessed too many times and
lost
134. if len(missedLetters) == len(HANGMANPICS) - 1:
135. displayBoard(HANGMANPICS, missedLetters,
correctLetters, secretWord)
136. print('You have run out of guesses!\nAfter '
+ str(len(missedLetters)) + ' missed guesses and ' + str
(len(correctLetters)) + ' correct guesses, the word was
"' + secretWord + '"')
137. gameIsDone = True
Think about how we know when the player has guessed too many times. When you play
Hangman on paper, this is when the drawing of the hangman is finished. We draw the
hangman on the screen with print() calls, based on how many letters are in
missedLetters . Remember that each time the player guesses wrong, we add (or as a
programmer would say, concatenate) the wrong letter to the string in missedLetters .
So the length of missedLetters (or, in code, len(missedLetters) ) can tell us the
number of wrong guesses.
At what point does the player run out of guesses and lose? Well, the HANGMANPICS list
has 7 pictures (really, they are ASCII art strings). So when len(missedLetters)
equals 6 , we know the player has lost because the hangman picture will be finished.
(Remember that HANGMANPICS[0] is the first item in the list, and HANGMANPICS[6]
is the last one. This is because the index of a list with 7 items goes from 0 to 6, not 1 to 7.)
So why do we have len(missedLetters) == len(HANGMANPICS) - 1 as
the condition on line 134, instead of len(missedLetters) == 6 ? Pretend that we
add another string to the HANGMANPICS list (maybe a picture of the full hangman with a
tail, or a third mutant arm). Then the last picture in the list would be at HANGMANPICS
[7] . So not only would we have to change the HANGMANPICS list with a new string, but
we would also have to remember to change line 134 to len(missedLetters) == 7 .
This might not be a big deal for a program like Hangman, but when you start writing larger
programs you may have to change several different lines of code all over your program just
to make a change in the program's behavior. This way, if we want to make the game harder
or easier, we just have to add or remove ASCII art strings to HANGMANPICS and change
nothing else.
A second reason we user len(HANGMANPICS) - 1 is so that when we read the code
in this program later, we know why this program behaves the way it does. If you wrote
len(missedLetters) == 6 and then looked at the code two weeks later, you may
wonder what is so special about the number 6. You may have forgotten that 6 is the last
index in the HANGMANPICS list. Of course, you could write a comment to remind yourself,
like:
Search WWH ::




Custom Search