Python Forum

Full Version: How do I shorten my input options? - text adventure
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
As the tittle states I want to shorten a piece of my code into something like a dictonary, im fairly new to python and dont really know how to go about this so any help or an example would be great.
	print (" Go to the -")
	print ("1.) Tavern")
	print ("2.) Arena")
	print ("3.) Quest Board")
	print ("4.) Potion Shop")
	print ("5.) Blacksmith")

	Option = input("-->")
	if (Option == "1"):
		print("You enter the Tavern")
		Tavern()
	elif (Option == "2"):
		print("You enter Arena")
		preArena()
	elif (Option == "3"):
		print("You walk to the Quest Board")
		Quest_Board()
	elif (Option == "4"):
		print("You enter the Potion Shop")
		Potion_Shop()
	elif (Option == "5"):
		print("You enter the Blacksmith")
		Blacksmith()
class smart_dict(dict):
    def __missing__(self, key):
        return key

def Tavern():
    print('Typed 1')

def preArena():
    print('Typed 2')

def Quest_Board():
    print('Typed 3')

def Potion_Shop():
    print('Typed 4')

def Blacksmith():
    print('Typed 5')

options = {
    '1': ['You enter the Tavern', Tavern, 'Go to the -Tavern'],
    '2': ['You enter Arena', preArena, 'Go to the - Arena'],
    '3': ['You walk to the Quest Board', Quest_Board, 'Go to the - Quest Board'],
    '4': ['You enter the Potion Shop', Potion_Shop, 'Go to the - Potion Shop'],
    '5': ['You enter the Blacksmith', Blacksmith, 'Go to the - Blacksmith']
}

smart_dict(options)

while True:
    n=1
    print()
    for key, value in options.items():
        print('{}.) {}'.format(n, value[2]))
        n += 1

    Option = input("-->")
    if Option == options[Option]:
        continue
    print(options[Option][0])
    options[Option][1]()
I added stubs for the various functions you need to write
Not actually shorter in this case, but hopefully you can gain some insight into how you could do things like this:
entrance = {"standard" : "You enter the {}.", "walk" : "You walk to the {}."}


options = [(Tavern, "Tavern", "standard"), 
           (preArena, "Arena", "standard"),
           (Quest_Board, "Quest Board", "walk"),
           (Potion_Shop, "Potion Shop", "standard"),
           (Blacksmith, "Blacksmith", "standard")]
    

print(" Go to the -")
for i, option in enumerate(options, start=1):
    print("{}.) {}".format(i, option[1]))


option = int(input("-->")) - 1
call, name, message = options[option]
print(entrance[message].format(name))
call() 
Assuming that those areas are classes you could roll the information in entrance and options into them as well.
There's a tutorial on exactly that.