Game Development Reference
In-Depth Information
73. print('You ran out of guesses. The answer was
%s.' % (secretNum))
If guess is the same value as secretNum , then we know the player has correctly
guessed the secret number and we can break out of this loop (the while loop that was
started on line 60). If not, then execution continues to line 72, where we check to see if the
player ran out of guesses. If so, then we tell the player that they have lost and what the secret
number was. We know that the condition for the while loop on line 55 will be False , so
there is no need for a break statement.
At this point, execution jumps back to the while loop on line 60 where we let the player
have another guess. If the player ran out of guesses (or we broke out of the loop with the
break statement on line 71), then execution would proceed to line 75.
Asking the Player to Play Again
75. if not playAgain():
76. break
After leaving the while loop on line 60, we ask the player if want to play again by
calling our playAgain() function. If playAgain() returns False , then we should
break out of the while loop that was started on line 55. Since there is no more code after
this loop, the program terminates.
If playAgain() returned True , then we would not execute the break statement and
execution would jump back to line 55. A new secret number would be generated so that the
player can play a new game.
Summary: Getting Good at Bagels
Bagels is a fairly simple game to program but can be difficult to win at. But if you keep
playing, you will eventually discover better ways to guess and make use of the clues the
game gives you.
This chapter introduced a few new functions and methods ( random.shuffle() , sort
() , and join() ), along with a couple handy shortcuts. Using the augmented assignment
operators involve less typing when you want to change a variable's relative value (such as in
spam = spam + 1 , which can be shortend to spam += 1 ). String interpolation can
make your code much more readable by placing %s (called a conversion specifier) inside the
string instead of using many string concatenation operations.
The join() string method is passed a list of strings that will be concatenated together,
with the original associated string in between them. For example, 'X'.join
( ['hello', 'world', 'yay'] ) will evaluate to the string,
Search WWH ::




Custom Search