Home > Mobile >  Way to recreate all python class instances each time program loops
Way to recreate all python class instances each time program loops

Time:12-02

For a python RPG, I have player_module.py, which contains all classes, methods and functions.

class RingOfRegeneration(Regeneration):
    def __init__(self):
        super().__init__()
        self.name = "Ring of Regeneration"
        self.item_type = "Rings of Regeneration"
        self.regenerate = 1
        self.sell_price = 10000
        self.buy_price = 10000

ring_of_regeneration = RingOfRegeneration()

Right now I have over 30 class instances. The class instances and their attributes are referenced throughout the module, (which is about 10,000 lines at this point). I have a loot_dict within the module from which random items may be found, which simply contains the instances:

loot_dict = {
            'Armor': [leather_armor, ....],
            'Rings of Regeneration': [ring_of_regeneration...],
...         }

I also have the main.py loop. Class instances like swords and rings can be found in the dungeon, and can be enhanced. For instance, a ring of regeneration can be enhanced throughout the game to self.regenerate = 2, 3...etc. My problem is, when the player dies and is given the choice to play again, breaking out to the top level loop and restarting the game, if loot is found, it still has the 'enhanced' values. I want to simply reset or recreate all class instances every time the player restarts the loop and as a beginner, I can't figure out a way to do this without exiting the program and restarting it from the command line. I have been unable to grasp any solutions from similar topics. Lastly, if I have painted myself into a corner, as a last resort, is there a way to simply re-run the program from within the program?

CodePudding user response:

Your loot dict has in real reference to objects and if you assign to player character any object from loot_dict you assign reference to the same object what is in your loot_dict. (Just like a pointer in cpp). You need to create new instance of object every time the player gets new item. To achive it You can do something like this:

loot_dict={'Rings':[RingOfRegeneration]}

Now u can call it:

item_class = random.choice(list(loot_dict.keys())) 
new_item_instance = random.choice(loot_dict[item_class])() #Calling class __init__ method

new_item_instace is now fresh base statistics.

  • Related