How to flatten nested IF statements which all contain strings?

1.5k views Asked by At

I'm making a Choose Your Own Text Adventure game which, so far, contains far too much nesting. Example code is below = mine's in the same format, just with far more nesting - sometimes approaching 10 layers deep.

My question is: Any way to flatten it? The strings mean I need every IF statement to print something every time it's valid, so I can't just use 'AND' like this:

if A and B:
    do something
elif C and D:
    do something else

I've thought of putting the parts that repeat in their own functions, but then that won't improve readability in this case - at least, not that I can figure out.

Help?

print "First String"
choice = raw_input("Choose A or B")
if choice == "A":
    print "You Chose A"
    choice = raw_input("Choose C or D")
    if choice == "C":
        print "You Chose C"
        choice = raw_input("Choose E or F")
        if choice == "E" or choice == "F":
            print "END"
    elif choice == "D":
        print "You Chose D"
        choice = raw_input("Choose G or H")
        if choice == "G" or choice == "H":
            print "END"
elif choice == "B":
    print "You Chose B"
    choice = raw_input("Choose I or J")
    if choice == "I":
        print "You Chose I"
        choice = raw_input("Choose C or D")
        if choice == "C":
            print "You Chose C"
            choice = raw_input("Choose E or F")
            if choice == "E" or choice == "F":
                print "END"
        elif choice == "D":
            print "You Chose D"
            choice = raw_input("Choose G or H")
            if choice == "G":
                print "END"
            elif choice == "H":
                print "You Chose H"
                choice = raw_input("Choose K or L")
                if choice == "K" or choice == "L":
                    print "END"
1

There are 1 answers

2
Anand S Kumar On

If the mappings are straightforward, like , lets say , if I chose A first, i can chose C or D , also if I chose B first I can chose C or E. Now when in C , irrespective of whether the first choice was A or B, the choices you get are same. Then you can use recursion along with a dictionary like -

dict = {'-1':['A','B'], 'A' : ['C','D'] , 'B':['I','J'], 'C':['E','F'] ..}

Then a recursive function like -

def choose(previousChoice, num):
    print str(num) + " String"
    choice = raw_input("Choose " + ' or '.join(dict[previousChoice]) + " :")
    if dict.get(choice) != None and len(dict.get(choice)) > 0:
        choose(choice, num + 1)

In the above example you start with -

choose('-1',1)