0

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.

DuckyQuack
  • 39
  • 10
  • 1
    Put a flag on your `Room` class indicating whether it has been entered yet. – kindall Feb 10 '17 at 01:58
  • how?, and the data structure of my game, is different, its more of a story mode kinda game – DuckyQuack Feb 10 '17 at 02:01
  • 1
    For example, define `visits = 0` on the class and increment it when you enter the room (`self.visits += 1`). (Using a counter rather than a flag gives you a lot of flexibility if you later decide something should happen if the player goes to the same room ten times, or whatever.) – kindall Feb 10 '17 at 02:04

2 Answers2

1

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
mitoRibo
  • 4,468
  • 1
  • 13
  • 22
0

You need static var : What is the Python equivalent of static variables inside a function?

def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate

@static_var("counter", 0)
def is_first_time():
    is_first_time.counter += 1
    return is_first_time.counter == 1

print(is_first_time())
print(is_first_time())
print(is_first_time())
Community
  • 1
  • 1
XiaoChi
  • 369
  • 4
  • 4