I am currently trying to code a text-based adventure in pure python. Therefore I have a Room class which looks kinda like this (shortened):
class Room1(Room):
def __init__(self):
Room.__init__(self)
self.init_objects()
self.description = """Looks like a living room. There's a lamp, a
cupboard, and
a door to your right. On the floor, there's a carpet."""
self.door_state = 1
self.carpet_state = 0
self.images = [(text-based images)]
def init_objects(self):
self.objects = {"door" : Door1(),
"frontdoor" : FrontDoor(),
"carpet" : Carpet(),
"lamp" : Lamp1(),
"clock" : Clock(),
"escritoire" : Escritoire(),
"booklet" : Booklet(),
"screws" : Screws(),
"trapdoor" : TrapDoor()}
def update_image(self):
IMG_MAPPER = {(0, 0, 0) : 0,
(0, 0, 1) : 1,
(1, 0, 0) : 2,
(1, 0, 1) : 3,
(1, 1, 1) : 4,
(1, 1, 0) : 5,
(0, 1, 1) : 6,
(0, 1, 0) : 7}
key = (self.objects["door"].state, self.objects["carpet"].state)
self.img = img_mapper[key]
My problem is with the Room's update_image() method. I need a mapper to be stored there to figure out the right image according to the object's states (opened / closed), and if I put this mapper at the start of the method, this dict is read and constructed by python everytime the method is called, is that right? So should I rather store this mapper dict as an instance variable like self.img_mapper_dict = {(0, 0, 0) : 0, ...}?
Any ideas on that anyone perhaps?
You are correct in assuming that the way your current code is structure, IMAGE_MAPPER
would be assigned to every single time the update_image()
method is called.
Now, since this is a static mapping that doesn't change over time, this is not a problem from a functionality standpoint - it's not like you're resetting a value that should be tracked between calls to update_image()
.
Performance wise, in this particular case, the drawbacks will also be absolutely negligible.
But it would probably make sense from a purely logical standpoint to make this mapping a class attribute:
class Room1(Room):
IMG_MAPPING = {(0, 0, 0) : 0,
(0, 0, 1) : 1,
(1, 0, 0) : 2,
(1, 0, 1) : 3,
(1, 1, 1) : 4,
(1, 1, 0) : 5,
(0, 1, 1) : 6,
(0, 1, 0) : 7}
def __init__(self):
# ...
def update_image(self):
# ...
self.img = Room1.IMG_MAPPING[key]
I'm recommending a class attribute instead of an instance attribute (or instance member) because that mapping is going to stay the same for all instances of Room1
(right? I'm assuming every instance of Room1
would have exactly the same layout, just different door states etc..). So it doesn't depend on any state of the instance, but it's a property of the class instead.
Also note that the class attribute is accessed differently: Room1.IMG_MAPPING
instead of self.IMG_MAPPING
. This also reflects the fact that it's not dependent on the instance.