Reputation: 31
I'm making a text-based adventure game in python and would like the user to choose a race and create an instance of a race class based on their choice. For example, if the player chose a Lizardman race from this code:
def character_creation():
print("You have four choices, choose wisely")
races = ['Lizard', 'Bookshelf', 'Genie', 'Werepus']
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])
return races[choice]
else:
continue
How would I get my code to make a race object?
character = Race('Lizardman', 'Regrowth', 20)
Each race is created by Race(Name, Passive, HP)
and each race has its own passive and hp associated with it. As in, I don't want to ask the user for the passive and the HP, just the race name.
Upvotes: 1
Views: 88
Reputation: 1427
If you want the user to only choose the race name and have everything else on default you can set the default values in the class parameters.
Here's an example:
class Race():
def __init__(self, Name: str, Passive: str = "Regrowth", HP: int = 20): # Set default values here
self.Name = Name
self.Passive = Passive
self.HP = HP
def Main():
race_name = input("Pick a race: ")
character = Race(race_name)
print(character.Name, character.Passive, character.HP)
if __name__ == "__main__":
Main()
Output if user enters 'Lizardman
':
Lizardman Regrowth 20
You can still overwrite and change the the Passive and the HP as so:
character = Race(Name = race_name, Passive = "Something", HP = 100)
Upvotes: 0
Reputation: 4347
You can use classmethod here.
class Race:
def __init__(name: str, passive: str, hp: int):
self.name = name
self.passive = passive
self.hp = hp
@classmethod
def from_race_name(cls, name):
race_attributes = {'Lizardman':{'passive': 'Regrowth',
'hp': 20,
.....}
return cls(name,
race_attributes[name]['passive'],
race_attributes[name]['hp'])
This will create an instance of the class based on only name of the race. To use it call it with the class name:
liz = Race.from_race_name('Lizardman')
This will create an instance of lizardman which will automatically be assigned 'regrowth' passive and 20 hp.
Also, if you want to create a 'unique' lizardman you can still do it manually:
admiral_akbar = Race(name='Lizardman', passive='panic', hp=999)
Upvotes: 3