Write a program using an object
Start to create your object-oriented text-based adventure game
Extend other people’s classes
Create an enemy in the room
Recap Week 3
Extending your knowledge of OOP
Finish your game
End of the course
Where we are up to...
Extending a class takes advantage of a concept called inheritance; the new class can be said to inherit properties from its parent class. To extend a class, you can define new attributes or methods, and you can also change the behavior of existing methods.
In this step you are going explore how to extend an existing class. It is also perfectly normal to write your own classes and then extend them.
Copy the code from this program, paste it into a new file named character.py, and save it in the folder containing all your earlier code.
The code is a Character class that I have written for you. If you have a look at it, you should recognise some familiar things.
You’ll see that to create a Character object, the constructor needs two parameters: the character’s name and a description of the character:
def __init__(self, char_name, char_description):
self.name = char_name
self.description = char_description
self.conversation = None
Create a new Python file and save it as character_test.py, in the folder with your other code.
from character import Character
dave = Character("Dave", "A smelly zombie")
Add this code in the character_test.py to call the describe method on the object you created to show the character’s description on the screen.
dave.describe()
Save and run your program. You should see the description of the character you just created:
Dave is here!
A smelly zombie
Examine the Character class inside character.py to find the name of the method that sets the conversation attribute.
Add code to your program to call this method and give Dave a line of dialogue.
Add code to your program to call a different method that talks to Dave.
So far, so good. You can use this code as the basis for your characters. However, not every character in the game will have the same characteristics. Some will be friends and some will be enemies, and friend and enemies should behave differently.