Game Development Reference
In-Depth Information
executed the break statement. Otherwise, we keep looping. But when
guessesTaken has the number 6 stored, the while statement's condition is False ,
since 6 is not less than 6 . Because the while statement's condition is False , we will not
enter the loop and instead jump to the end of the while-block.
The remaining lines of code run when the player has finished guessing (either because
the player guessed the correct number, or because the player ran out of guesses). The
reason the player exited the previous loop will determine if they win or lose the game, and
the program will display the appropriate message on the screen for either case.
Check if the Player Won
28. if guess == number:
Unlike the code in line 25, this line has no indentation, which means the while-block has
ended and this is the first line outside the while-block. When we left the while block, we
did so either because the while statement's condition was False (when the player runs
out of guesses) or if we executed the break statement (when the player guesses the
number correctly). With line 28, check again to see if the player guessed correctly. If so, we
enter the if-block that follows.
29. guessesTaken = str(guessesTaken)
30. print('Good job, ' + myName + '! You guessed my
number in ' + guessesTaken + ' guesses!')
Lines 29 and 30 are inside the if-block. They only execute if the condition in the if
statement on line 28 was True (that is, if the player correctly guessed the computer's
number).
In line 29 (which is similar to the guess = int(guess) code on line 15), we call
the new function str() , which returns the string form of an argument. We use this
function because we want to change the integer value in guessesTaken into its string
version because we can only use strings in calls to print() .
Line 29 tells the player that they have won, and how many guesses it took them. Notice
in this line that we change the guessesTaken value into a string because we can only
add strings to other strings. If we were to try to add a string to an integer, the Python
interpreter would display an error.
Check if the Player Lost
32. if guess != number:
Search WWH ::




Custom Search