Making an open world choose-your-own-adventure text based game in python. Sorta new to python so I'm not sure what the best way to do this is. I want to store information about lots of different items such as armor, weapons, etc. I also want to store information about different towns and the NPCs in them. How can I store this info, all with their own subdata such as a swords damage, in a easy to use, sorted manner?
My first thought was to use classes. This was so I could do something like
class goblin:
health = 10
class items:
class weapons:
class ironSword:
damage = 1
goblin.health -= items.weapons.ironSword
But i figured this wouldn't work because I need the items to be accessible, like a variable. This is because I am using a class for the player, which has a list for their inventory. I want to be able to store these items in said list, Which I am not sure how to do with classes.
Your approach of organizing the data in classes is good. But you're defining the classes in a rather complex way. A better option would be to use inheritence
. If you are unfamiliar with the concepts of inheritence
or subclasses
, you can check out this excellent video by Corey Schafer.
You may want to do something like this:
class Item:
def __init__(self, name, description):
self.name = name
self.description = description
class Weapon(Item):
def __init__(self, name, description, damage):
super().__init__(name, description)
self.damage = damage
class Armor(Item):
def __init__(self, name, description, defense):
super().__init__(name, description)
self.defense = defense
Then you can create as many objects
(your items) you want from these classes like this:
iron_sword = Weapon("Iron Sword", "A basic iron sword.", damage=10)
machine_gun = Weapon("Machine Gun", "An automatic assault rifle.", damage=90)
leather_armor = Armor("Leather Armor", "Light armor made of leather.", defense=5)