MONT 105S, Spring 2009

Home | | Course Schedule | | Assignments | | Lecture Notes

Laboratory 8
Due at the end of today's class

The Hero class
In this lab you will create the Hero class. A hero is an object that has a name, an inventory of items that he or she carries, and some number of health points. This class would be useful if you were developing an adventure game in which a hero journeys through a world collecting objects and fighting monsters.

Creating the class.
Create the Hero class with the following properties and methods:

Properties:

Methods (functions):

Part 1:
Start by defining the Hero class with the two properties (inventory and health). Add the __init__(self, name) method and the __str__(self) method.

Use the following template to test your class so far:

#Program: heroClass.py
#Your program prologue goes here

class Hero:
#Add your properties and methods here (don't forget to indent)



#The main program starts here (to test the class)
heroName = raw_input("Please enter the hero's name: ")
myHero = Hero(heroName)
print myHero

Sample output: The output should look as follows (user input is underlined):

Please enter the hero's name: Fred
I am the hero, Fred

Part 2:
Add the definitions of add_inventory(self, item) and print_inventory(self). Add these methods after the __str__(self) method but before the main program.

Change your main program so that it tests these new methods as follows:

heroName = raw_input("Please enter the hero's name: ")
myHero = Hero(heroName)
print myHero
myHero.add_inventory("sword")
myHero.add_inventory("potion")
myHero.add_inventory("armor")
myHero.print_inventory( )

Sample output: The output should look as follows (user input is underlined):

Please enter the hero's name: Eowyn
I am the hero, Eowyn
The following items are in the inventory: 
sword
potion
armor

Part 3:
Add the definitions of attack_troll(self) and heal(self). Add these after the definition of print_inventory(self) but before the main program.

Change your main program to test these new methods as follows:

heroName = raw_input("Please enter the hero's name: ")
myHero = Hero(heroName)
print myHero
myHero.add_inventory("sword")
myHero.add_inventory("potion")
myHero.add_inventory("armor")
myHero.print_inventory( )
myHero.attack_troll( )
myHero.heal( )

Sample output: The output should look as follows (user input is underlined):

Please enter the hero's name: Mario
I am the hero, Mario
The following items are in the inventory: 
sword
potion
armor
Mario has attacked a troll.
Mario now has 8 health points.
The healing potion heals Mario
Mario now has 10  health points.

What To Turn In.

Reminder.

Be sure to save a copy of each program on your P:\ drive.