At the moment my code has multiple if statements that are similar (see below) and i was wondering if there was a way to make a variable or something that can change based on what comes out of the random.choice?
So if it landed on druid instead of checking if the result was barbarian then moving onto the next block of code it would just take druid from the random.choice output and change the import for a single block of code accordingly
sorry if this is worded badly, it's hard for me to convey what i mean, i can elaborate if needed
def randclass():
return random.choice(class_dict[chosenrace])
if randclass() == "Barbarian":
print(chosenrace, "Barbarian")
if fullconfirm == "yes":
from barbarianfullbuild import barbarianrandsubclass, barbarianrandbackground, barbarianskills
print(barbarianrandsubclass)
print(barbarianrandbackground)
print(barbarianskills)
if randclass() == "Druid":
print(chosenrace, "Druid")
if fullconfirm == "yes":
from druidfullbuild import druidrandsubclass, druidrandbackground, druidskills
print(druidrandsubclass)
print(druidrandbackground)
print(druidskills)
CodePudding user response:
You can use python's dict as a hash-map in order to avoid those ifs:
def randclass():
return random.choice(class_dict[chosenrace])
def import_barbarian():
print(chosenrace, "Barbarian")
if fullconfirm == "yes":
from barbarianfullbuild import barbarianrandsubclass, barbarianrandbackground, barbarianskills
print(barbarianrandsubclass)
print(barbarianrandbackground)
print(barbarianskills)
def import_druid():
print(chosenrace, "Druid")
if fullconfirm == "yes":
from druidfullbuild import druidrandsubclass, druidrandbackground, druidskills
print(druidrandsubclass)
print(druidrandbackground)
print(druidskills)
import_races = {
"Barbarian": import_barbarian,
"Druid": import_druid
}
import_races[randclass()]()
CodePudding user response:
Try this code, You need to write it only once and it will work for all the random cases.
def randclass():
return random.choice(class_dict[chosenrace])
a = randclass()
print(chosenrace,a)
b = a.lower()
if fullconfirm == "yes":
exec(f"from {b}fullbuild import {b}randsubclass, {b}randbackground, {b}skills")
exec(f"print({b}randsubclass)")
exec(f"print({b}randbackground)")
exec(f"print({b}skills)")
exec() is a function that executes a line of code in main passed as a string, it's a good workaround for situations like this.
