Choose Your Own Pyventure/Wandering Grue

Let's say you'd like to have a wandering Grue in your Mysterious House that pops up in a room (or rooms) randomly.

One way to do this is to make a function that decides whether the Grue is in the room or not:

Test Frameowrk

Later in our complete code, we will see code similar to:

eaten=grue()if eaten:
print"Sadly, you were torn limb-from-limb by the Grue and suffered a slow, painful death."else:
print"Congratulations, you have not been eaten by the Grue! May you have a long happy life."

Here we introduce a new python data type: boolean. Python booleans can take two values True and False. These code fragments are equivalent:

Exercise: Make the reverse -- a grue that never appears. The signature of the function should be grue_never() -> False

Variation 2: the 50/50 Grue

importrandom## random is a Python module, as mentioned above. ## We need to import it to access the random() function.## now to begin the function definition## Everything inside the function definition is indented! Remember, white space matters!def random_grue():
''' boolean. a grue that appears 50% of the time '''## we want something that will return True 50% of the time.## one method: get a random float between (0,1), and return True if it's over .5## now we need a random number. random() will give us one between 0 and 1
n=random.random()## the random before the dot tells Python what module to look in for the function, which is the one we imported aboveif n >0.5:
grue=1## 1 == Trueelse:
grue=0## 0 == Falsereturn grue ## returning allows us to capture the value

So what does the random_grue() function do? Let's try it. In the Python interpreter:

The first command is to import the random module, the second is to define the function and the third is to actually call the function. The 1 is the return of the function. You may get a 1 or a 0 depending on the number random() generated. (Hint: try running it several times)

Note that we simplified down the function quite a bit by returning the boolean value directly (especially in 'grue_moody2'), rather than doing any conditional logic to get a 1 or 0. Also notices that we specified a default value for the argument cutoff.

Exercises

Predict the behaviour of these functions calls. Then try them.

grue_moody()

grue_moody(-1)

grue_moody(1)

grue_moody("a")

grue_moody([1,2,3])

Fix the code so that it prints an angry message and returns None if n is outside the interval (0,1).

try help(grue_moody). What do you see?

what are the types of random, random.random, random.random()

Variation 3: the location, location, location Grue

In our final variation, we want a grue that:

has different percentages of appearing based on which page

should have zero chance of appearing in the main room "foyer"

should have a default chance of appearing of 5% in rooms that aren't otherwise described