2

I am making a text based adventure game in python. Once the game begins, I would like to create an instance of a class called "Character" which is the player's character object. I would like the user to be able to choose the race of the character they want to play. So far I have:

class Race:
    def __init__(self, name, passive, hp):
        self.name = name
        self.passive = passive
        self.hp = hp

and

class Lizard(Race):
    def __init__(self, name, passive, hp):
        super().__init__(name, passive, hp)
        self.name = 'Lizardman'
        self.passive = 'Regrowth'
        self.hp = 20

    def regrowth(self):
        if 0 < self.hp <= 18:
            self.hp += 2

and

def race_select():
    races = ['Lizard']

    while True:
        for i, j in enumerate(races):
            print(f"[{i + 1}]", j)

        choice = int(input('Pick a race:'))

        if choice <= len(races):
            print('You are a ', races[choice - 1])
            return races[choice - 1]
        else:
            continue

If I understand correctly, if I wanted the race to be a Lizard, I would still have to do

character = Lizard('Lizardman', 'Regrowth', 20)

Is there an easy way to let the user choose the race and the object to be created accordingly? Thanks

2
  • To answer both your questions, right now it sort of works but I have to finagle it to output the right thing so it only works if there is one race choice. I am just a bit confused because I was wondering if there were some way to make it so that I could just say character = Lizard() without specifying any parameters, because I already gave the parameters in the class Lizard code (aka the 'Lizardman', 'Regrowth', 20... seems a bit repetitive to have to do it twice) Commented Jan 1, 2021 at 0:28
  • As for the parameters, you can simply have an empty __init__ for Lizard, and just pass hardcoded "Lizardman", "Regrowth", 20, .... to super(). Commented Jan 1, 2021 at 0:33

1 Answer 1

3

A simple solution would be to map a name to a class using a dictionary. As a simple example:

race_map = {"lizard": Lizard,
            "human": Human}  # I'm adding a theoretical other class as an example

choice = input('Pick a race:')
race_initializer = race_map.get(choice, None)  # Get the chosen class, or None if input is bad
if race_initializer is None:
    # They entered bad input that doesn't correspond to a race
else:
    new_creature = race_initializer(their_name, their_passive, their_hp)

new_creature is now the new object of the chosen class.

You may want to standardize the input using choice.lower() to ensure that capitalization doesn't matter when they enter their choice.


I changed it to allow for specifying a race by a string name instead of a number. If you wanted a number, you could keep your list, but apply the same idea. Something like:

race_list = races = [('Lizard', Lizard), ('human', Human)]
choice = int(input('Pick a race:'))
try:
    race_initializer = race_list[choice][1]  # 1 because the class object is the second in the tuple
    new_creature = race_initializer(their_name, their_passive, their_hp) 
except IndexError:
    # Bad input

I included the name in the race_list so that you can loop over the list and print out index->name associations for the user to pick from.

You may also want to use a more robust structure than a plain tuple to store name->initializer mappings, but it works well in simple cases.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome thanks for clearing that up. Just to make sure, would the code you shared go inside of a function? Can you create an instance of a class inside of a function and you can mess around with it outside of that function?
@Schnibs This code could definitely be inside of a function. If you wanted new_creature outside of a function that it was created in, you could simply return the object from the function, or have the function as a method of a "environment" class that houses all the objects that the game uses, and append the new_creature to a list of creatures that the class maintains. It really depends on how you plan on structuring things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.