Variable Reassignment

Viewed 22

I want to create a text adventure, and you know how in text adventures you get a description of the scene the first time and after that, it only gives you the room's name? I'm using Python and I want to find a way to check if a variable had previously been assigned that same value. For example:

room = "kitchen" #False
room = "living room" #False
room = "kitchen" #True
room = "living room" #True
room = "dungeon" #False

True means the variable had previously been assigned that same value, and I want to find out how to generate a True or False value based on whether that value is "familiar" with the variable.

1 Answers

There's a lot of ways to do this. A getter and setter can work. Here's one example of how this could be implemented:

class Room:
    def __init__(self, name=None):
        self.names = []
        if name is not None:
            self.names.append(name)

    # @property means the room name can be gotten like 'r.room' rather than something like 'r.get_room()'
    @property
    def room(self):
        """Return the most recent name"""
        return self.names[-1]

    # "setter" means the room name can be set like 'r.room = "blah"'
    @room.setter
    def room(self, name):
        if name not in self.names:
            self.names.append(name)
            print(f'"{name}" is a new room name')
        else:
            print(f'"{name}" was previously a room name')

    # You can compare against this list to see in advance if a name was  previously set
    def get_room_names(self):
        return self.names.copy()


r = Room()

r.room = "kitchen"
r.room = "living room"
r.room = "kitchen"
r.room = "living room"
r.room = "dungeon"
print(r.get_room_names())

Output:

"kitchen" is a new room name
"living room" is a new room name
"kitchen" was previously a room name
"living room" was previously a room name
"dungeon" is a new room name
['kitchen', 'living room', 'dungeon']
Related