Game Development Reference
In-Depth Information
11 - Bagels
Try experimenting with the random.shuffle() function by entering the following
code into the interactive shell:
>>> import random
>>> spam = range(list(10))
>>> print(spam)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(spam)
>>> print(spam)
[1, 2, 5, 9, 4, 7, 0, 3, 6, 8]
>>> random.shuffle(spam)
>>> print(spam)
[3, 0, 5, 9, 6, 8, 2, 4, 1, 7]
>>> random.shuffle(spam)
>>> print(spam)
[9, 8, 3, 5, 4, 7, 1, 2, 0, 6]
>>>
Every time you pass a list reference to random.shuffle() , the list it references has
all the same items but in a different order. The reason we do this is because we want the
secret number to have unique values. The Bagels game is much more fun if you don't have
duplicate numbers in the secret number, such as '244' or '333' .
Getting the Secret Number from the Shuffled Digits
6. secretNum = ''
7. for i in range(numDigits):
8. secretNum += str(numbers[i])
9. return secretNum
The secret number will be a string of the first three digits (because we'll pass 3 for the
numDigits parameter) of the shuffled list of integers. For example, if the shuffled list is
[9, 8, 3, 5, 4, 7, 1, 2, 0, 6] then we want the string returned by getSecretNum() to be
'983' .
The secretNum variable starts out as a blank string. We then loop a number of times
equal to the integer value in numDigits . On each iteration through the loop, a new
integer is pulled from the shuffled list, converted to a string, and concatenated to the end of
secretNum . So if numDigits is 3 , the loop will iterate three times and three random
digits will be concatenated as strings.
For example, if numbers refers to the list [9, 8, 3, 5, 4, 7, 1, 2, 0, 6] ,
then on the first iteration, numbers[0] (that is, 9 ) will be passed to str() , which in
turn returns '9' which is concatenated to the end of secretNum . On the second iteration,
Search WWH ::




Custom Search