1

I'm making a text-based adventure game which I plan on being quite long. Naturally, instead of having all the code in main.py I decided to split the chapters into different files to be run in if blocks according to the choices the player makes. Slight problem, however: all of the user information I'm using to customize the story (name, gender, clothing, etc.) is stored in main.py. So, if I have another file (let's say option3.py for example) and I'm writing something like

print(f"{user_name} walked down the street.")

I don't have user_name stored in option3.py. I'd rather not import specific variables into each of the 20+ files every time but I hear that sharing namespace is a bad idea, so I'm wondering if there's a better way to work around this.

Extra: I'd also like to include some sort of item inventory feature but I'm not sure how to go about that, what with this multiple file issue and the fact that the inventory would often change

mrghofrani
  • 1,335
  • 2
  • 13
  • 32
Arcat
  • 11
  • 1
  • 2
    Use Object Oriented programming. Store state in object(s). Also, storing game content in `.py` file is not a good idea - it's much better to create some kind of file format (even `csv`) and keep all the stuff there. – Tupteq Mar 29 '20 at 19:24

2 Answers2

2

The best thing is to use classes and import them. If you created a class named User, and put all the necessary attributes in the class, you could import it.

For example, create a user.py file:

class User():
  def __init__(self, name, gender, clothing):
    self.name = name
    self.gender = gender
    self.clothing = clothing

Then, wherever your main game loop is, you can do from user import User.

That way, you can create a new user object with user1 = User('SomeName', 'F', 'Skirt') and access is attributes like this: print(user1.name)

Amit Aviv
  • 1,816
  • 11
  • 10
CliffJ
  • 43
  • 7
0

You can do something like this if you don't want to pollute the namespace.

game_variables.py

cat = 12
dog = 24

main.py

import game_variables as gv

print(gv.cat)
print(gv.dog)

But, I think you're missing the point that game states must be shared across all the modules, in that case you need to create global variables. But, this could lead to all sort of inconsistency.

Instead, it's better to create a class for each module in your design, and passing the object states with getter and setter between multiple files.

cat.py

class cat:
  def __init__(self):
    self.cuteness = 100
    pass
  def get_state(self):
    return self.cuteness
  def set_state(self, val):
    self.cuteness = val

update.py

def update(state):
   # some calculation
   return state + 1

main.py

import update
import cat

my_cat = cat.cat()
updated_cat_cuteness = update.update(my_cat.get_state())
my_cat.set_state(updated_cat_cuteness)

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60