Game Development Reference
In-Depth Information
1. import random
This game imports the random module so we can use the module's random number
functions.
Shuffling a Unique Set of Digits
2. def getSecretNum(numDigits):
3. # Returns a string that is numDigits long, made up of
unique random digits.
4. numbers = list(range(10))
5. random.shuffle(numbers)
Our first function is named getSecretNum() , which will generate the random secret
number. Instead of having the code only produce 3-digit numbers, we use a parameter
named numDigits to tell us how many digits the secret number should have. (This way,
we can make the game produce secret numbers with four or six digits, for example, just by
passing 4 or 6 as numDigits .)
You may have noticed that the return value of our call to range() was in turn passed to
a function called list() . The list() function returns a list value of the value passed to
it, much like the str() function returns a string form or the int() function returns an
integer form. The reason we do this is because the range() function technically does not
return a list but something called an iterator object. Iterators are a topic that you don't need
to know at this point, so they aren't covered in this topic.
Just about every time we use the range() function it is in a for loop. Iterators are fine
to use in for loops (just like lists are), but if we ever want to store a list of integers in a
variable, be sure to convert the return value of range() to a list with the list()
function first. (Just like we do on line 4.)
The random.shuffle() Function
First, we create a list of integers 0 to 9 by calling list(range(10)) and store a
reference to this list in numbers. Then we call a function in the random module named
shuffle() . The only parameter to random.shuffle() is a reference to a list. The
shuffle() function will randomly change the order of all the items in the list.
Notice that random.shuffle() does not return a value. It changes the list you pass it
"in place" (just like our makeMove() function in the Tic Tac Toe chapter modified the list
it was passed in place, rather than return a new list with the change). It would actually be
incorrect to write numbers = random.shuffle(numbers) .
Search WWH ::




Custom Search