I'm trying to figure out how to use an if statement before the assignment to change it is made. The point of this script is to check if the knife is taken before it prompts with the question to take it from the table. It's to make it so that you can walk back to the table and get another response if you've already taken it. What am I doing wrong?
def table ():
if knife_taken == False:
print "it's an old, brown wooden table, and atop it you find a knife"
print "Will you take the knife or go back?"
knife = raw_input ("> ")
if knife.strip().lower() in ["back", "b", "no"]:
basement2()
elif knife.strip().lower() in ["take knife", "knife", "yes", "k"]:
knife_taken = True
print "You now have the knife, good, you are going to need it"
raw_input()
basement2()
else:
print "I did not understand that."
raw_input()
table()
else:
print "There's nothing on the table"
raw_input()
basement2()
Basically when you change the variable knife_taken in your function you change it at a local level, this means when the function ends the changes are lost. There are two ways to fix this either use global (but thats the bad way)
global knife_taken
knife_taken = True
Or you can return the state of the knife from the function
return knife_taken
# later on
kitchen(knife_taken)
and store it in a variable, passing it back to kitchen later as an arguement
Or as an extra little bonus, you can store game state in a dictionary. You could then update the dictionary as the game state changes e.g.
game_state = {}
game_state['knife_taken'] = False
def kitchen():
if not game_state['knife_taken']:
print "Take the knife!"
game_state['knife_taken'] = True
else:
print "Nothing to see here."
kitchen()
kitchen()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With