Game Development Reference
In-Depth Information
9 - Hangman
to the Boolean value True . We start out assuming that we have found all the letters, but
will change foundAllLetters to False when we find a letter in secretWord that is
not in correctLetters .
The for loop will go through the numbers 0 up to (but not including) the length of the
word. Remember that range(5) will evaluate to the list [0, 1, 2, 3, 4] . So on
line 123, the program executes all the code inside the for-block with the variable i will be
set to 0 , then 1 , then 2 , then 3 , then 4 .
We use range(len(secretWord)) so that i can be used to access each letter in the
secret word. So if the first letter in secretWord (which is located at secretWord[0] )
is not in correctLetters , we know we can set foundAllLetters to False . Also,
because we don't have to check the rest of the letters in secretWord , we can just break
out of this loop. Otherwise, we loop back to line 123 and check the next letter.
If foundAllLetters manages to survive every single letter without being turned to
False , then it will keep the original True value we gave it. Either way, the value in
foundAllLetters is accurate by the time we get past this for loop and run line 127.
129. if foundAllLetters:
130. print('Yes! The secret word is "' +
secretWord + '"! You have won!')
131. gameIsDone = True
This is a simple check to see if we found all the letters. If we have found every letter in
the secret word, we should tell the player that they have won. We will also set the
gameIsDone variable to True . We will check this variable to see if we should let the
player guess again or if the player is done guessing.
When the Player Guesses Incorrectly
130. else:
This is the start of the else-block. Remember, the code in this block will execute if the
condition was False . But which condition? To find out, point your finger at the start of
the else keyword and move it straight up. You will see that the else keyword's
indentation is the same as the if keyword's indentation on line 118. So if the condition on
line 118 was False , then we will run the code in this else-block. Otherwise, we skip down
past the else-block to line 140.
131. missedLetters = missedLetters + guess
Search WWH ::




Custom Search