Game Development Reference
In-Depth Information
11 - Bagels
our getSecretNum() function (passing it NUMDIGITS to tell how many digits we
want the secret number to have) and assign it to secretNum . Remember that
secretNum is a string, not an integer.
We tell the player how many digits is in our secret number by using string interpolation
instead of string concatenation. We set a variable numGuesses to 1 , to denote that this is
the first guess. Then we enter a new while loop which will keep looping as long as
numGuesses is less than or equal to MAXGUESS .
Getting the Player's Guess
Notice that this second while loop on line 60 is inside another while loop that started
on line 55. Whenever we have these loops-inside-loops, we call them nested loops . You
should know that any break or continue statements will only break or continue
out of the innermost loop, and not any of the outer loops.
61. guess = ''
62. while len(guess) != NUMDIGITS or not isOnlyDigits
(guess):
63. print('Guess #%s: ' % (numGuesses))
64. guess = input()
The guess variable will hold the player's guess. We will keep looping and asking the
player for a guess until the player enters a guess that has the same number of digits as the
secret number and is made up only of digits. This is what the while loop that starts on line
62 is for. We set guess as the blank string on line 61 so that the while loop's condition is
False the first time, ensuring that we enter the loop at least once.
Getting the Clues for the Player's Guess
66. clue = getClues(guess, secretNum)
67. print(clue)
68. numGuesses += 1
After execution gets past the while loop on line 62, we know that guess contains a
valid guess. We pass this and the secret number in secretNum to our getClues()
function. It returns a string that contains our clues, which we will display to the player. We
then increment numGuesses by 1 using the augmented assignment operator for addition.
Checking if the Player Won or Lost
70. if guess == secretNum:
71. break
72. if numGuesses > MAXGUESS:
Search WWH ::




Custom Search