Home > other >  How do I use the if and elif with a random choice command?
How do I use the if and elif with a random choice command?

Time:03-12

I am trying to create a program to generate a complete random build in the NHL video games. Essentially you get an archetype and from that archetype you get certain abilities and such and i am trying to get the first part to run to just pick an archetype and a build. I also need to implement a way to do height, weight, and boosts as well, but I am unable to get the program to choose an ability based on whichever archetype that is chosen. This is the code I have so far and i know it is a lot and i dont know if this is the easiest way to do something like this because i have to make more if/elif loops for other areas of the build unless there is an easier more efficient way:


import random

allbuilds = ["two way forward", "power forward", "dangler", "sniper", "enforcer", "enforcer d"]
twfabils= ["truculence", "back at ya", "big rig"]
pwfabils= ["shutdown", "quick pick", "schnipe"]
dangabils= ["ankle breaker", "one tee", "puck on string"]
snipabils= ["one tee", "snappy", "schnipe"]
enfabils= ["heatseeker", "elite edges", "medic"]
enfdabils= ["unstoppable force", "stick em up", "ice pack"]

pickrandbuild=random.choice(allbuilds)
randbuild=print(pickrandbuild)

picktwfabil=random.choice(twfabils)
pickpwfabil=random.choice(pwfabils)
pickdangabil=random.choice(dangabils)
picksnipabil=random.choice(snipabils)
pickenfabil=random.choice(enfabils)
pickenfdabil=random.choice(enfdabils)



if randbuild == "two way forward":
    print(picktwfabil)
elif randbuild == "power forward":
    print(pickpwfabil)
elif randbuild == "dangler":
    print(pickdangabil)
elif randbuild == "sniper":
    print(picksnipabil)
elif randbuild == "enforcer":
     print(pickenfabil)
else:
    print(pickenfdabil)

CodePudding user response:

If you format your data as a dictionary, you can reduce the coding to just two lines:

allbuilds = {
    "two way forward": ["truculence", "back at ya", "big rig"],
    "power forward": ["shutdown", "quick pick", "schnipe"],
    "dangler": ["ankle breaker", "one tee", "puck on string"],
    "sniper": ["one tee", "snappy", "schnipe"],
    "enforcer": ["heatseeker", "elite edges", "medic"],
    "enforcer d": ["unstoppable force", "stick em up", "ice pack"]
}

pickrandbuild = random.choice(list(allbuilds.keys()))
pickability = random.choice(allbuilds[pickrandbuild])

And, as was suggested in the comments on this answer, it can even be reduced to one line using tuple unpacking:

pickrandbuild, pickability = random.choice(list(allbuilds.items()))
  • Related