Back

Default and random data for the monsters

Introduction
Suppose we want to create a monster that has a default set of values? Or suppose we want to mix up our game each time we play it so it isn't predictable which monster is the strongest or has most magic. How can we do that?

Setting default values
The __init__ method is called the constructor method for a class. It always runs whenever we instantiate an object. Change the constructor header in the monster class so it look like this:

def __init__(self, name, strength = 5, wisdom = 6, magic = 7):

When we nstantiate an object, if we specify the strength, wisdom and magic values, they will be used. We saw this with monster1 = monster('Gregor', 11, 7, 3) but now if we miss out these values, the default ones specified in the constructor header will be used instead. Create another monster in your code, except only specify its name this time e.g. 

monster4 = monster('Klub')

Make sure you add the extra code needed to display this monster and check what happens.

Random numbers
If we want to use random numbers, we will need to import a special library of functions designed for creating random numbers. Add this extra code to lines 1 and 2 at the very top of your program to import the random module.

rand1

Each time we instantiate a new monster, will will generate a new random value between 1 and 20 for the strength, wisdom and magic values rather than saying what the starting value is for every game. Modify where you instantiate your monsters so that it looks like this:

rand2

Back