Game Development Reference
In-Depth Information
Checking if the Letter is in the Secret Word
118. if guess in secretWord:
119. correctLetters = correctLetters + guess
Now let's see if the single letter in the
guess
string exists in
secretWord
. If it does
exist, then we should concatenate the letter in
guess
to the
correctLetters
string.
Next we can check if we have guessed all of the letters and won.
Checking if the Player has Won
121. # Check if the player has won
122. foundAllLetters = True
123. for i in range(len(secretWord)):
124. if secretWord[i] not in correctLetters:
125. foundAllLetters = False
126. break
How do we know if the player has guessed every single letter in the secret word? Well,
correctLetters
has each letter that the player correctly guessed and
secretWord
is
the secret word itself. We can't just check if
correctLetters == secretWord
because consider this situation: if
secretWord
was the string
'otter'
and
correctLetters
was the string
'orte'
, then
correctLetters ==
secretWord
would be
False
even though the player has guessed each letter in the
secret word.
The player simply guessed the letters out of order and they still win, but our program
would incorrectly think the player hasn't won yet. Even if they did guess the letters in order,
correctLetters
would be the string
'oter'
because the player can't guess the letter t
more than once. The expression
'otter' == 'oter'
would evaluate to
False
even
though the player won.
The only way we can be sure the player won is to go through each letter in
secretWord
and see if it exists in
correctLetters
. If, and only if, every single letter
in
secretWord
exists in
correctLetters
will the player have won.
Note that this is different than checking if every letter in
correctLetters
is in
secretWord
. If
correctLetters
was the string
'ot'
and
secretWord
was
'otter'
, it would be true that every letter in
'ot'
is in
'otter'
, but that doesn't mean
the player has guessed the secret word and won.
So how can we do this? We can loop through each letter in
secretWord
and if we find
a letter that does not exist in
correctLetters
, we know that the player has not guessed
all the letters. This is why we create a new variable named
foundAllLetters
and set it