pythonpython-3.xnumberscounteradventure

Python, "If if line is called on first time, do something else"


So the title is pretty self explanatory, but i'll go into more detail. I am creating a text dependent game and I will have millions of areas. And each time you enter a new area, you will be greeted with a one time only different reaction than if you came into the same place again later, and I need to find a way to to this:

if len(line) == 1:
    do exclusive thing
else:
    do normal thing

Sure, I could use a counter system like "a = 0" but then I would need to create a separate counter for every single area I create, and I don't want that.


Solution

  • You could just store a single dict to keep track of room visits, and probably even better to use a defaultdict

    from collections import defaultdict
    
    #Using a defaultdict means any key will default to 0
    room_visits = defaultdict(int)
    
    #Lets pretend you had previously visited the hallway, kitchen, and bedroom once each
    room_visits['hallway'] += 1
    room_visits['kitchen'] += 1
    room_visits['bedroom'] += 1
    
    #Now you find yourself in the kitchen again
    current_room = 'kitchen'
    #current_room = 'basement' #<-- uncomment this to try going to the basement next
    
    #This could be the new logic:
    if room_visits[current_room] == 0: #first time visiting the current room
        print('It is my first time in the',current_room)
    else:
        print('I have been in the',current_room,room_visits[current_room],'time(s) before')
    
    room_visits[current_room] += 1 #<-- then increment visits to this room