Python: Can One Piece of Script Skip into another? - python

here is a piece of the code I am working with:
if second_do.lower() == "market":
print "You are now inside of the market place. It appears to be abandoned. The shelves are almost empty, however, you to manage find some salvagable goods, including peanut butter, beans, and crackers."
goods = raw_input(">>> ")
if goods.lower() == "collect":
print "You have collected the food items. These will help you later on."
if goods.lower() == "get":
print "You have collected the food items. These will help you later on."
if goods.lower() == "collect food":
print "You have collected the food items. These will help you later on."
if goods.lower() == "collect goods":
print "You have collected the food items. These will help you later on."
if goods.lower() == "get food":
print "You have collected the food items. These will help you later on."
if goods.lower() == "get goods":
print "You have collected the food items. These will help you later on."
after_market = raw_input("What's next?")
if "mansion" in after_market:
elif second_do.lower() == "mansion":
print "You are now inside of the mansion."
I was wondering how I make it so one part of the script (in this case,if mansion in after_market:) can take me to another part. (elif second_do.lower() == "mansion":)

You probably want to restructure you code a bit and use variables to keep track of where your user "is" while looping. Something like...
location = "start"
while location != "exit":
if location == "market":
# do market related stuff
elif location == "mansion":
# do mansion related stuff
location = raw_input("Where to next?")
You can then go one step further and use functions for each location, e.g.
def doMarket():
# do market related stuff
def doMansion():
# do mansion related stuff
location = "start"
while location != "exit":
if location == "market":
doMarket()
elif location == "mansion":
doMansion()
location = raw_input("Where to next?")
You could also have it be more controlled where someone in one place can go next, by having the functions return the new location:
def doMarket():
# do market related stuff
# User can go anywhere from the market
return raw_input("Where to next?")
def doMansion():
# do mansion related stuff
# User must always go to the market after the mansion
return "market"
location = "start"
while location != "exit":
if location == "market":
location = doMarket()
elif location == "mansion":
location = doMansion()

The minimal change you need to make is this:
if second_do.lower() == "market":
print "You are now inside of the market place. It appears to be abandoned. The shelves are almost empty, however, you to manage find some salvagable goods, including peanut butter, beans, and crackers."
goods = raw_input(">>> ")
if goods.lower() == "collect":
print "You have collected the food items. These will help you later on."
if goods.lower() == "get":
print "You have collected the food items. These will help you later on."
if goods.lower() == "collect food":
print "You have collected the food items. These will help you later on."
if goods.lower() == "collect goods":
print "You have collected the food items. These will help you later on."
if goods.lower() == "get food":
print "You have collected the food items. These will help you later on."
if goods.lower() == "get goods":
print "You have collected the food items. These will help you later on."
after_market = raw_input("What's next?")
if "mansion" in after_market:
second_do = "mansion"
# After this, the control drops to the next if-statement
if second_do.lower() == "mansion":
print "You are now inside of the mansion."
To make this code DRY, you have to place these options in a loop which asks the user for what to do next and the actions are functions which are executed for the option the user chose

Related

Text Game Closes after every command - NOTE: I just started out

print "Welcome to the game. In the game you can 'look around' and 'examine things'."
print "There is also some hidden actions.
print "You wake up."
input = raw_input("> ")
haveKey = False
applesExist = True
if input == "look around":
print "You are in a dusty cell. There is a barrel in the corner of the room, an unmade bed,"
print "a cabinet and chest. There is also a cell door."
elif haveKey == False and input == "use door":
print "The door is locked."
elif haveKey == True and input == "use door":
print "You open the door and immediately gets shot with an arrow. You won, kinda."
elif input == "examine barrel":
print "There is apples in the barrel."
elif applesExist == True and input == "eat apple":
print "Mmmmh, that was yummy! But now there are no apples left..."
applesExist = False
elif applesExist == False and input == "eat apple":
print "sury, u et al aples befur!!1111"
elif input == "examine bed":
print "The bed is unmade, and has very dusty sheets. This place really needs a maid."
elif input == "sleep on bed":
print "You lie down and try to sleep, but you can't because of all the bugs crawling on you."
elif input == "examine chest":
print "There is a key in the chest."
elif input == "take key":
haveKey = True
print "You take the key."
elif input == "examine cabinet":
print "The cabinet is made of dark oak wood. There is a endless cup of tea in it."
elif input == "drink tea":
print "You put some tea in your mouth, but immediately spit it out."
print "It seems it has been here for quite some time."
else:
print "Huh, what did you say? Didn't catch that."
No syntax errors, no errors of any kind. Not. One.
The problem is that after I examine, look around and eat apples the
game closes. How do I fix this? With a While loop?
plz halp
You're obviously very beginner, I won't hammer you about how to do the best architecture. Get used to write code a little first.
If you want to repeat an action, that means a loop (here it's called the main game loop). You code currently takes an input, do a lot of checks to do an action on it, do that action and then... reach the end of the file and stops.
If you wan to go back to the input, you need to enclose all the code you want to repeat in a repetitive code structure, i.e. a loop.
Here is a basic pseudo-code of a game main loop.
playing=True:
while playing:
instruction = takeUserInputOfSomeForm();
if instruction == something:
doStuff()
# etc ...
elif instruction == "quit":
playing=False
You need a loop otherwise when the code hits the bottom of the file Python will exit. http://www.tutorialspoint.com/python/python_loops.htm

How to filter a dictionary value (within another dictionary)

I will try to explain this as best as i can, so apologies in advanced for the long post.
Firstly, I have an API here (http://dev.c0l.in:5984/income_statements/_all_docs) and within this dictionary there are 5000 other dictionaries that I can access through their ID (http://dev.c0l.in:5984/income_statements/30e901a7b7d8e98328dcd77c369b6ad7)
So far I've created a programme that sorts through these dictionaries and only prints out (to csv) the dictionaries related to a user input sector (e.g. healthcare)
However, I wanted to be able to implement a filter search, so that the programme will only print statements that are above or below a user input value e.g. Only retrieve data from (user input) closing stock and only companies below (<=) a value of closing stock - 40,000.
My problem is that, I'm not necessarily sure how to.
I understand how to get the user input, and how to access the dictionary within dictionary but i have no idea how to filter above or below a user input value.
Here is a copy of my code, any pointers would be appreciated!
import urllib #Imports the url - library module (older the urllib2 but has some useful decodes if needed)
import urllib2 #Imports the Url- Library module (Most recently updated + used)
import csv #Imports the commands that allows for csv writing/reading
import json #Imports the ability to read/use Json data
import time #Imports the time module - allows the developer to examine benchmarks (How long did it take to fetch data)
import os
income_csv = csv.writer(open("Income Statement_ext.csv", "wb")) #This creates a CSV file and writes functions to it
financial_csv = csv.writer(open("Statement of financial position_ext.csv", "wb"))
#The two csv 'writers' create the headers for the information within the CSV file before the information from the api is added to it
financial_csv.writerow([
('Company name'),
('Non Current Assets'),
('Current Assets'),
('Equity'),
('Non-Current Assets'),
('Current Liabilities')])
income_csv.writerow([
('Company name'),
('Sales'),
('Opening Stock'),
('Purchases'),
('Closing Stock'),
('Expenses'),
('Interest payable'),
('Interest receivable')])
income_url = "http://dev.c0l.in:5984/income_statements/_all_docs"
income_request = urllib2.urlopen(income_url).read()
income_response = json.loads(income_request)
#defines the income url
financial_url = "http://dev.c0l.in:5984/financial_positions/_all_docs"
financial_request = urllib2.urlopen(financial_url).read()
financial_response = json.loads(financial_request)
#defines the financial postion url
count = 0
#sets the count for documents printed to 0
def income_statement_fn():
global count #allows for the count to be kept globally
print ("(Type help if you would like to see the available choices)")
income_user_input = raw_input("Which sector would you like to iterate through in Income Statement?: ").lower()# Asks the user which sector within the chosen statement he/she would like to examine
if income_user_input == "help":
print ("Available sectors are: ")
print ("Technology")
print ("Healthcare")
print ("Industrial goods")
print ("Financial")
print ("Utilities")
print ("Basic materials")
print ("Services")
income_statement_fn()
elif income_user_input == "technology" or income_user_input == "healthcare" or income_user_input == "industrial goods" or income_user_input == "financial" or income_user_input == "utilities" or income_user_input == "basic materials" or income_user_input == "services":
print 'Starting...' # I use this print to set a milestone (if it prints this, everything before it has worked without error)
start = time.clock()
start
for item in income_response['rows']:
is_url = "http://dev.c0l.in:5984/income_statements/" + item['id'] #This combines the api with the array's ID's allowing us to access every document automatically
is_request = urllib2.urlopen(is_url).read() #Opens is_url and reads the data
is_response = json.loads(is_request) #loads the data in json format
if is_response.get ('sector') == income_user_input: #matches the sector the user inputed - allows us to access that dictionary
income_csv.writerow([
is_response['company']['name'],
is_response['company']['sales'],
is_response['company']['opening_stock'],
is_response['company']['purchases'],
is_response['company']['closing_stock'],
is_response['company']['expenses'],
is_response['company']['interest_payable'],
is_response['company']['interest_receivable']]) # The lines of code above write the chosen fields to the csv file
count +=1
print ("filtering statements") + ("( "+" %s "+" )") % count
start
print start
restart_fn()
else:
print ("Invalid input!")
income_statement_fn()
def financial_statement_fn(): # Within this function is the code required to fetch information related to the financial position statement
global count # Allows for the count to be kept globally (outside the function)
print ("(Type help if you would like to see the available choices)")
financial_user_input = raw_input("Which sector would you like to iterate through in financial statements?: ").lower()
if financial_user_input == "help":
print ("Available sectors are: ")
print ("Technology")
print ("Healthcare")
print ("Industrial goods")
print ("Financial")
print ("Utilities")
print ("Basic materials")
print ("Services")
financial_statement_fn()
elif financial_user_input == "technology" or financial_user_input == "healthcare" or financial_user_input == "industrial goods" or financial_user_input == "financial" or financial_user_input == "utilities" or financial_user_input == "basic materials" or financial_user_input == "services":
print 'Starting'
for item in financial_response['rows']:
fs_url = "http://dev.c0l.in:5984/financial_positions/" + item['id']#This combines the api with the array's ID's allowing us to access every document automatically
fs_request = urllib2.urlopen(fs_url).read()
fs_response = json.loads(fs_request)
if fs_response.get ('sector') == financial_user_input:
financial_csv.writerow([
fs_response['company']['name'],
fs_response['company']['non_current_assets'],
fs_response['company']['current_assets'],
fs_response['company']['equity'],
fs_response['company']['non_current_liabilities'],
fs_response['company']['current_liabilities']])
count +=1
print ("printing statements") + ("( "+" %s "+" )") % count
print ("---------------------------------------------------------------------")
print ("finished fetching data")
print ("---------------------------------------------------------------------")
restart_fn()
else:
print ("Invalid Input!")
financial_statement_fn()
def launch_fn():
print ("Please type 'help' if you would like to examine all available options")
launch_user_input = raw_input("Welcome, Which statement would you like to examine?: ").lower()
if launch_user_input == "income" or launch_user_input == "income statement":
income_statement_fn()
elif launch_user_input == "financial" or launch_user_input == "financial statement":
financial_statement_fn()
elif launch_user_input == "help" :
print ("You can use the following commands on this menu: ")
print ("---------------------------------------------------------------------")
print ("Income or Income statement")
print ("Will allow you to retrieve data relating to financial Income statements")
print ("---------------------------------------------------------------------")
print ("Financial or Financial statement")
print ("Will allow you to retrieve data relating to the statement of financial position")
print ("---------------------------------------------------------------------")
launch_fn()
else:
print ("If you would like to look at the available options please type help")
launch_fn()
def restart_fn():
restart_prompt = raw_input("Would you like to examine another statement?: ").lower()
if restart_prompt == 'y' or restart_prompt == 'yes':
launch_fn()
count = 0
elif restart_prompt == 'n' or restart_prompt == 'no':
raise SystemExit("Shutting down....")
def restart_api_down_fn():
print ("Type 'y' or 'yes' to continue, 'n' or 'no' to exit or 'r' or 'reconnect' to test servers again")
restart_prompt_api = raw_input("Would you like to continue anyway?: ").lower()
if restart_prompt_api == 'r' or restart_prompt_api == 'reconnect' or restart_prompt_api == 'test':
api_status_fn()
count = 0
elif restart_prompt_api == 'n' or restart_prompt_api == 'no':
raise SystemExit("Shutting down....")
elif restart_prompt_api == 'y' or restart_prompt_api == 'yes':
print (" Continuing... Programme performance may be severely affected")
launch_fn()
else:
print ("Invalid input...")
restart_api_down_fn()
def api_status_fn():
hostname_income = "http://dev.c0l.in:5984/income_statements"
response_income = os.system("ping -c 1 " + hostname_income)
hostname_financial = "http://dev.c0l.in:5984/financial_positions"
response_financial = os.system("ping -c 1 " + hostname_financial)
global count
count = 0
if response_income == 0:
print hostname_income, 'is up!'
count +=1
else:
print hostname_income, 'is experiencing connection issues!'
if response_financial == 0:
print hostname_financial, 'is up!'
count +=1
else:
print hostname_financial, 'is experiencing connection issues!'
if count == 2:
launch_fn()
elif count == 0:
restart_api_down_fn() # Code only for UNIX SYSTEMS?
#def api_status_fn():
# hostname = "http://dev.c0l.in:5984/income_statements"
# ping = urllib.urlopen(hostname).getcode()
# if ping == "200":
# print 'oh no!'
# add filtering & sorting
api_status_fn()
Please let me know if you need any additional explanations,
Cheers!
I would say that your code is quite confused and you may have more luck with it if you try to break it down a little. I will try to make some suggestions towards the end of this answer.
Fundamentally you need to filter the specific results that you get. Looking at your code I can see the following:
elif financial_user_input == "technology" or financial_user_input == "healthcare" or financial_user_input == "industrial goods" or financial_user_input == "financial" or financial_user_input == "utilities" or financial_user_input == "basic materials" or financial_user_input == "services":
print 'Starting'
for item in financial_response['rows']:
fs_url = "http://dev.c0l.in:5984/financial_positions/" + item['id']#This combines the api with the array's ID's allowing us to access every document automatically
fs_request = urllib2.urlopen(fs_url).read()
fs_response = json.loads(fs_request)
if fs_response.get ('sector') == financial_user_input:
This code mixes the following responsibilities up:
Validating user input
Requesting records
Filtering records
If you split out these responsibilities into separate methods then you will find that your code is easier to reason about. Also, as I will shortly show, splitting things up in this way allows you to recombine the different parts to customise the way in which the records are filtered etc.
If it gets split up a little:
def _get_single_record(id):
""" Request an individual financial position.
This does not filter """
... read and return the json decoded data ...
def _record_matches_sector(record, sector):
""" Determine if the record provided matches the sector """
return record['sector'] == sector
def _record_meets_closing_stock_limit(record, limit):
""" Determine if the record provided has a
closing stock of at least limit """
return record['closing stock'] >= limit
def _get_all_filtered_records(ids, sector, limit):
""" Return all financial position records that
match the sector and closing stock limit """
record_generator = (_get_single_record(id) for id in ids)
return (
record for record in record_generator
if _record_matches_sector(record, sector)
and _record_meets_closing_stock_limit(record, limit)
)
This obviously just returns a generator which returns the records that match your sector and limit. You can add more tests and so on, but updating the code to test for each of these is still quite manual. What you need is a way to apply some selectable tests to the record_generator and return the results that match.
This is quite trivial in python because python treats functions as first class objects (meaning you can assign them to variables) and you can create custom functions quickly using lambdas. This means you can restate the _get_all_filtered_records as:
def _make_limit_test(limit):
""" This returns a function which accepts records that meet the limit """
return lambda record: record['closing stock'] >= limit
def _make_sector_test(sector):
""" This returns a function which accepts records that match the sector """
return lambda record: record['sector'] == sector
def _filter_records_by_tests(ids, tests):
""" Returns all the records that pass all the tests """
record_generator = (_get_single_financial_position_record(id) for id in ids)
for record in record_generator:
if all(test(record) for test in tests):
yield record
You can then build the list of tests to pass by asking the user. This would be a sufficient demo just to verify that this approach works:
def demo_filtering_by_healthcare_and_40k(ids):
tests = [_make_sector_test("healthcare"), _make_limit_test(40000)]
return _filter_records_by_tests(ids, tests)
As you can see my method names are quite long and the methods are quite short. This is really a matter of personal style, but I find that doing it that way makes it obvious what a method does and allows you to quickly comprehend the code to verify that it matches the name.
So to wrap this up, you are requesting records from the remote api. You can filter these by using list comprehensions. List comprehensions are extremely powerful and allow you to take source data and transform it and filter it. It would help you a lot to read about them.

Use of lists for collecting items

I'm currently going through the book "Learning Python The Hard Way", and I'm trying to make a simple game. In this game, I want to be able to pick up at item "Flashlight" in one room, to be able to get into another room. I can, however, not make it work :-(
So the question is, how do I carry the same list through several functions, and how do I put things in it? I want to be able to put multiple things in it.
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
Hope you can help me out, thanks :-)
Code:
def start(bag):
print "You have entered a dark room"
print "You can only see one door"
print "Do you want to enter?"
answer = raw_input(">")
if answer == "yes":
light_room(bag)
elif answer == "no":
print "You descidede to go home and cry!"
exit()
else:
dead("That is not how we play!")
def light_room(bag):
print "WOW, this room is amazing! You see magazines, cans of ass and a flashlight"
print "What do you pick up?"
print "1. Magazine"
print "2. Cans of ass"
print "3. Flashlight"
pick(bag)
def pick(bag):
pick = raw_input(">")
if int(pick) == 1:
bag.append("Magazine")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 2:
bag.append("Can of ass")
print "Your bag now contains: \n %r \n" % bag
elif int(pick) == 3:
bag.append("Flashlight")
print "Your bag now contains: \n %r \n" % bag
else:
print "You are dead!"
exit()
def start_bag(bag):
if "flashlight" in bag:
print "You have entered a dark room"
print "But your flashlight allows you to see a secret door"
print "Do you want to enter the 'secret' door og the 'same' door as before?"
answer = raw_input(">")
if answer == "secret":
secret_room()
elif answer == "same":
dead("A rock hit your face!")
else:
print "Just doing your own thing! You got lost and died!"
exit()
else:
start(bag)
def secret_room():
print "Exciting!"
exit()
def dead(why):
print why, "You suck!"
exit()
bag = []
start(bag)
I tried to call the pick() function within it self, but keep getting a "TypeERROR: 'str' is not callable, though I am providing my function with a list?
The problem here is that in this line:
def pick(bag):
pick = raw_input(">")
you bind pick to a new value (a str) so it doesn't reference a function anymore. Change that to something like:
def pick(bag):
picked = raw_input(">")

Why doesn't my list change?

I've been hacking away on a little game, just for fun, and I've run into a problem. I'll post the code and try my best to explain:
def parseCmd(string):
cmd = string.split(' ')
if cmd[0] == 'help':
showHelp()
elif cmd[0] == 'add':
addServer()
elif cmd[0] == 'bag':
viewInventory(inventory)
elif len(cmd) == 1 and cmd[0] == 'look':
describeRoom()
elif len(cmd) == 1 and cmd[0] == 'take':
print 'What do you want me to take?'
elif cmd[0] == 'take':
pickUp(cmd[1], items)
elif cmd[0] == 'exit':
sys.exit(0)
else:
print 'I don\'t know how to ' + cmd[0]
def describeRoom():
print locations[player_location]
def pickUp(item, item_list):
if item in item_list[player_location]:
item_list[player_location].remove(item)
inventory.append(item)
print 'You took the ' + item
else:
print 'I can\'t find any ' + item
inventory = ['id card', 'money', 'keys']
player_location = 'cookieroom'
items = {'cookieroom': ['crowbar', 'hammer']}
locations = {'cookieroom': 'The cookieroom, where all the hard work gets done. \n\nNORTH: LFA - ITEMS: %s' % items[player_location],
'LFA': 'The infamous LFA, where dreams of office supplies become reality. there is a big guy sleeping in his chair next to a fire extinguisher.\n\nSOUTH: Cookieroom, WEST: WC'}
if __name__ == "__main__":
while 1:
t = raw_input('-> ')
parseCmd(t)
So, as you can see I want the list of items in the items dictionary to change when you pick up an item available in that specific room. I can pick up the item and it gets added to my inventory but if I issue the command 'look' it shows the list of items in it's original state.
I've been googling and stackoverflowing for 1½ day now and I can't find anything that seems to solve this problem.
If something is unclear, just ask me and I'll try to answer.
The locations dictionary, which is from where the describeRoom function picks up its room description, is initialised once when the program starts. At that time, the location of the player is the cookieroom and the objects there are the crowbar and the hammer. So, a string is created like so
'The cookieroom, where all the hard work gets done. \n\nNORTH: LFA - ITEMS: ["crowbar", "hammer"]'
This string never changes even if you later alter the contents of the items dictionary.
Your locations dictionary should only contain the non changing part of the room description. The changing part (e.g. the list of items in the room etc.) should be recomputed everytime the users requests the description of the room.

python: functions

I am attempting to create a text-based adventure game for class, but I have been experiencing problems in getting the 'use' function to work when using an item in inventory.
The game has 2 interactive menus, the main menu (where you can travel, search, display and use inventory, display an ASCII map, or quit) and the travel menu (a while loop that moves you between locations). I wanted to lock one of the doors to a location, requiring the user to find a key in a different location (thereby adding it to inventory) and then choose that item from inventory when prompted to gain access to the location.
I created a dictionary to be referenced by the use function to verify if the item can be used in a specific location. I tested the logic within the function and it worked. However, it will accept any item to be used on the door for some reason and I think it has to do with the way the functions deal with each other seeing as the use function is called on by the show inventory function.
Any help would be appreciated here, whether to the specific question or anything that you might do differently.
These are the functions in question:
def eHouseAccess(action, location, oldLocation): # called by travel to validate if the location is accessable
global eHouse
if eHouse == 'locked' and inventory == []:
print "The door is locked! You need to find a key for this door."
travel(oldLocation)
elif eHouse == 'locked':
print "The door is locked! You need to find a key for this door."
print "Maybe you have it in your inventory?"
a = showInv(inventory, location, items)
if a == True:
eHouse = 'open'
travel(location)
else:
travel(oldLocation)
else:
location = travelOpt[location][action - 1]
travel(location)
def travel(location):
while True:
print "You are in the", location[0]+"."
print location[1]
print 'You can travel to:'
for (i, t) in enumerate(travelOpt[location]):
print i + 1, t[0]
action = raw_input("Pick a destination, or enter 'menu' for the main menu: ")
if action == 'menu':
main_menu(location, inventory, items)
else:
action = int(action)
if travelOpt[location][action - 1] == engineer_house:
oldLocation = location
location = engineer_house
eAccess = eHouseAccess(action, location, oldLocation)
elif travelOpt[location][action - 1] == castle_inside:
cInside = cInsideAccess(action, location, cInside)
else:
location = travelOpt[location][action - 1]
def main_menu(location, inventory, items):
print "You are in the", location[0] + "."
menu_list = ['Travel', 'Inventory', 'Search', 'Map', 'Quit']
print "Choose one:"
for (num, t) in enumerate(menu_list):
print num + 1, t
main_choice = int(raw_input("> "))
action = menu_list[main_choice - 1]
if action == 'Travel':
travel(location)
elif action == 'Inventory':
showInv(inventory, location, items)
elif action == 'Search':
search(location, inventory, items)
elif action == 'Map':
map(location)
elif action == 'Quit':
exit()
else:
print "That is not a valid option!"
main_menu(location, inventory, items)
def showInv(inventory, location, items):
if inventory == []:
print "Your inventory is EMPTY"
sInv = raw_input("Hit 'enter' to return to the 'main menu': ")
main_menu(location, inventory, items)
else:
print "These 'items' are in your 'inventory':"
for (num, i) in enumerate(inventory):
print num + 1, i
sInv = raw_input("Type 'menu' to return to the main menu or 'use' to use and item: ")
if sInv == 'menu':
main_menu(location, inventory, items)
if sInv == 'use':
a = use(items, inventory, location)
return a
else:
print "That is not a valid entry!"
showInv(inventory, location, items)
def use(items, inventory, location):
if inventory == []:
print "There is nothing to use."
invEmpty = raw_input("Hit 'enter' to return to the 'main menu': ")
main_menu(location, inventory, items)
else:
uItem = int(raw_input("Choose an item to use: "))
curItem = inventory[uItem - 1]
if location == items[curItem][0]:
print "You used", inventory[uItem - 1]+"."
inventory.pop(uItem -1)
main_menu(location, inventory, items)
return True
else:
print "You cannot use that here!"
main_menu(location, inventory, items)
return False
There are two issues that stand out to me. First, use(...) is returning a boolean value, not the item used. No matter what the item used is, use(...) will return True. Second, in the eHouseAction method, you are testing to see if the value returned from showInv(...) is equal to True.
Since use(...) returns True and showInv(...) returns use(...), then a = showInv(...) is being set to True. eHouseAction is checking against True to open the door. Since using ANY item in your inventory will result in showInv(...) returning True, using ANY item in your inventory will open the door.
The solution is to make two changes:
def eHouseAccess(action, location, oldLocation):
[snip]
a = showInv(inventory, location, items)
if a == house_key: # I'm not exactly sure what you called the key
eHouse = 'open'
travel(location)
def use(items, inventory, location):
[snip]
if location == items[curItem][0]:
print "You used", inventory[uItem - 1]+"."
return inventory.pop(uItem -1)
Now, it would probably be a good idea to place the used item back in the player's inventory if they do not try to use a house_key. Without that check, any item they use will disappear forever.
Well, I'm not sure how eHouseAccess could even work — you should be getting NameError: global name 'items' is not defined. You probably wanted, global eHouse, items. Your bug, my guess, has to do with engineer_house. You are trying to compare it to items[curItem][0]. Are you setting that correctly?
Other notes:
Inside of use (which is not the best name), you probably want a return statement before the first else clause.
I would also point this out as an issue in a code review:
if location == items[curItem][0]:
Why does that have a 0 index? It seems like putting some sort of data object there would make more sense. Then the code might look something like this:
if location == items[curItem].location:
Or better yet, make that location property a list of places where it can be used and the you can have:
if location in items[curItem].valid_locations:
Of course, I would still return the object selected and not whether or not it could be used. Otherwise, in a situation where you have two or more things you can do, then you could accidentally brush your teeth with hand soap.

Categories

Resources