Game Development Reference
In-Depth Information
9 - Hangman
Get the Player's Guess
The getGuess() function we create next will be called whenever we want to let the
player type in a letter to guess. The function returns the letter the player guessed as a string.
Further, getGuess() will make sure that the player types a valid letter before returning
from the function.
85. def getGuess(alreadyGuessed):
86. # Returns the letter the player entered. This
function makes sure the player entered a single letter,
and not something else.
The getGuess() function has a string parameter called alreadyGuessed which
contains the letters the player has already guessed, and will ask the player to guess a single
letter. This single letter will be the return value for this function.
87. while True:
88. print('Guess a letter.')
89. guess = input()
90. guess = guess.lower()
We will use a while loop because we want to keep asking the player for a letter until
they enter text that is a single letter they have not guessed previously. Notice that the
condition for the while loop is simply the Boolean value True . That means the only way
execution will ever leave this loop is by executing a break statement (which leaves the
loop) or a return statement (which leaves the entire function). Such a loop is called an
infinite loop , because it will loop forever (unless it reaches a break statement).
The code inside the loop asks the player to enter a letter, which is stored in the variable
guess . If the player entered a capitalized letter, it will be converted to lowercase on line
90.
elif ("Else If") Statements
Take a look at the following code:
if catName == 'Fuzzball':
print('Your cat is fuzzy.')
else:
print('Your cat is not very fuzzy at all.')
We've seen code like this before and it's rather simple. If the catName variable is equal
to the string 'Fuzzball' , then the if statement's condition is True and we tell the user
 
Search WWH ::




Custom Search