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
You can use a class variable to keep track of the number of rooms you have in your game.
First, add a class variable to the Room class, outside the constructor.
class Room():
number_of_rooms = 0
To use a class variable you use the name of the class, as opposed to the name of an object, for example:
Room.number_of_rooms = 1
Each time a Room object is created, you can increment the number_of_rooms class variable in the constructor to keep track of the rooms created.
class Room():
number_of_rooms = 0
def __init__(self, room_name):
...
Room.number_of_rooms = Room.number_of_rooms + 1
Regardless of how many rooms are created, the total number will be available in the class variable Room.number_of_rooms.
kitchen = Room("kitchen")
ballroom = Room("ballroom")
dining_hall = Room("dining hall")
print("There are " + str(Room.number_of_rooms) + " rooms to explore.")
How do you think class variables might be of use to you in creating your game?
Can you think of any other situations in which you would need a variable to be shared by all instances of a class?