Text adventure game-python - python

I am new with coding. I have started this coding and it keeps giving me an error when I run the code. Can you tell me what is wrong with my code?
import time
import random
response = []
decision_list = ["1", "2"]
print(random.choice(decision_list))
def print_pause(message_to_print):
print(message_to_print)
time.sleep(1)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if 1 == response:
break
elif 2 == response:
break
return response
def intro():
print_pause("You find yourself driving down a long road alone to a cabin.")
print_pause("You have heard on the radio that it is a bear on the loose.")
print_pause("All of a sudden your car slows down by the dark woods.")
print_pause("You become terrified, but you see a house nearby for help.")
print_pause("You come closer to the house, it is a big shed to the left.")
print_pause("In your pocket, you have a pocketknife.")
def decision():
response = valid_input("Enter 1 to knock on the door of the house."
"Enter 2 to walk into the shed."
"What is you decision?"
"Please enter 1 or 2.")
if "1" in response:
print_pause("You have arrived to the door of the house.")
print_pause("Before knocking, the door starts to creek open.")
print_pause("The bear is standing in the doorway.")
print_pause("The bear attacks.")
print_pause("With your pocket knife, you cannot handle the bear.")
elif "2" in response:
print_pause("You walk towards the shed.")
print_pause("You look around and you saw a gun.")
print_pause("Next to the gun are bullets.")
print_pause("You have a weapon for protection besides your pocketknife.")
print_pause("You walk back to the house.")
play_again()
def action():
response = valid_input("Would you like to 1 fight or 2 run away?"
" Please enter 1 or 2.")
if "1" in response:
print_pause("The bear attacks and you have taken out the gun.")
print_pause("You begin to shoot the bear.")
print_pause("You have defeated the bear!!")
elif "2" in response:
print_pause(" You run back to your car where it is safe.")
elif "1" in response:
print_pause("You begin fighting back.")
print_pause("The pocketknife is not helpful.")
print_pause("The bear had defeated you!!")
def play_again():
response = valid_input("Would you like to play again?"
"Please say 'yes' or 'no'.\n",
"yes", "no")
if "yes" == response:
print_pause("Great! Restarting game.")
play_drive()
elif "no" == response:
print_pause("Thanks for playing!! Goodbye!")
exit(0)
def play_drive():
intro()
decision()
action()
play_drive()

The problem is in the first line of the function decision. There you call the function valid_input with only one argument. I'm not sure if you need it but you separate the different arguments by a coma. Hope I helped you:)

You didnt mention what is your error, but I can point out a few things that will not work.
You defined valid_input(prompt, option1, option2), which means three parameters are expected. But you just pass a text everytime you invoke valid_input() so that will produce an error. But later in the code you never use option1 and option2 for anythin, since you have hardcode 1 and 2 in the if..elif. Also keep in mind that input will capture the value as string, and then you compare it with two integers. So better:
def valid_input(prompt, option1 = "1", option2 = "2"):
while True:
response = input(prompt).lower()
if option1 == response or option2 == response:
return response
response = valid_input("Enter 1 to knock on the door of the house."
"Enter 2 to walk into the shed."
"What is you decision?"
"Please enter 1 or 2.")
Update: Since you try to invoke the same function sometimes passing the options as "yes"/"no" and sometimes you want to compare with "1" and "2", what you can do is to keep "1" and "2" as default, and those values will be ignored in case you invoke valid_input with "yes" and "no"

Related

Pygamezero code, My code works when I don't have any code after this, why is this?:

backg.pos = 242, 105
WIDTH = int(backg.width + 200)
HEIGHT = int(backg.height + 50)
def draw():
screen.clear()
backg.draw()
print("hi")
I have a picture called dining that I am trying to use as a background in a game which works just fine on its own, but when I add the rest of the code
name = input("What would you like to be called? >>> ")
inventory = []
def welcome():
print(f'Hello detective {name.title()}')
print("There has been a murder by poison in this house of a woman named Carla, you have to find the clues to unlock who the murderer is, there are 10 suspects and 5 rooms all with clues that will be useful to your mission. \n\nYOUR MISSION: FIND THE MURDERER AND BRING THEM TO JUSTICE!\n")
print("First question the suspects, then explore the rooms.")
question()
def dr():
drq = input("What do you want to do? \nA:Look in the cubbords \nB: Talk to Ella \nC: Go to a different room")
if drq.title == "A":
print("*You Find Insulin in the Cubbord*")
print("[Ella]>>> That was Carla's insulin, she had diabetes type one.")
inventory.insert("insulin")
print("*INSULIN HAS BEEN ADDED TO YOUR INVENTORY*")
elif drq.title == "B":
print("This is the Dining Room, Please talk to me if you need any infomation")
elif drq.title == "C":
rooms()
else:
print("Please pick a valid option A, B, C")
dr()
def lr():
lrq = input("What do you want to do? \nA:Check the book \nB:Check the fire place \n C:Talk to Ella \nD: Go to a different room")
if lrq.title == "A":
print("*Notice The Book Has Some Blood On It* [YOU]>>> Who's book was this?")
print("[Ella]>>> That's Johnny's book acctually, I better return it to him.")
print("[YOU]>>>I would like to keep it for evidence.")
inventory.insert("book")
print("*BOOK HAS BEEN ADDED TO INVENTORY")
elif lrq.title == "B":
print("*In the fire place you see a burnt note that reads \"THE DEED IS DONE\" *")
elif lrq.title == "C":
print("This is the Living Room, we all relaxed here after dinner")
elif lrq.title == "D":
rooms()
else:
print("Please pick a valid option A, B, C")
lr()
def mb():
mbq = input("What do you want to do? \nA:Check the draws \nB:Talk to Ella \nC: Go to a different room")
if mbq.title == "A":
print("you rummage through the draws and find jewlery, makeup, and a knife!\nYou deside not to tell Ella as she has been through enough trouble and you need more evidence.\n*KNIFE HAS BEEN ADDED TO INVENTORY!")
elif mbq.title == "B":
print("[Ella]>>> This is me and my husbands bedroom, we slept here last night when the murder occoured.")
elif mbq.title == "C":
rooms()
else:
print("Please pick a valid option A, B, C")
mb()
def rooms():
room = input("Which room would you like to go to? \nA:Dining Room \nB:Living Room \nC:Master Bedroom \nD:Carla's Room \nE:The Kitchen \n >>>")
if room.title == "A":
dr()
elif room.title == "B":
lr()
elif room.title == "C":
mb()
elif room.title == "D":
cr()
elif room.title == "E":
K()
else:
print("Please pick a valid option: A, B, C, D, E.")
rooms()
def question():
interview = input("Who do you want to question? Ella, Johnny, Harry, Lesley, Brook, Casey, Corey, Adrien, Hannah >>> ")
if interview.title() == "Ella":
print(f'\nI\'m Carla\'s Mother and i am so upset, I Think whoever did this NEEDS to be brought to justice, thank for spending your time to help us detective {name}')
elif interview.title() == "Johnny":
print(f'\nHello detective, I am Carla\'s brother. I was in my room when the murder occoured at 8 O\'clock, I heard her scream and being the scaredy cat I am, rather than going to see if I could find her and see if she was ok, I cowered in my bed.')
elif interview.title() == "Harry":
print(f'\nHello detective, I am Carla\'s Farther. I was with my darling Ella in our Master bedroom when the murder occoured, we had invited everyone over for dinner as it was, my beautiful daughters birthday, what a horrible day to be killed on')
elif interview.title() == "Lesley":
print('\nHello detective, I am Carla\'s nextdoor neighbour and we have been best friends for years, if you accuse me i will be very offended! This family seems to be addement it was me that killed her, I just think they don\'t want to belive it was part of their family that killed her')
elif interview.title() == "Brook":
print("\nHello detective, I am Carla\'s sister and although we have had our differences, I would never want to kill her, I was sleeping in the room next to Casey and Adrien.")
elif interview == "Blake":
print("\nCarla is my wife, I love her to pieces who ever did this, I will make them pay, with or without the Law on my side")
elif interview.title() == "Casey":
print("\nI\'m Carla\'s Mothers\'s neighbour, they invited me and my husband, Adrien, over for dinner and we politely refused'")
elif interview.title() == "Corey":
print("\nI\'m Carla\'s Godfarther and although we have never been very close i do love her dearly.'")
elif interview.title() == "Adrien":
print("\nI\'m Casey's husband and I don\'t really know what happend, I have had little to none contact with Carla and have know idea what was going on. Me and my wife just stayed over there's for the night as we were having work done to our house")
elif interview.title() == "Hannah":
print("\nI\'m Carla\'s Godmother and have always loved and cared for my Godchild, I do not know for certain but I think Adrien and Casey are acting quite suspicious")
else:
print("\n\nPlease pick a valid option\n\n")
question()
bigq()
def bigq():
answer = input("\nDo you want to \nA:Question anyone else \nor \nB:Do you want to investigate the rooms?\n>>>")
if answer.title() == "A":
print("\n\n")
question()
elif answer.title() == "B":
rooms()
else:
print("Please pick a valid option A or B")
bigq()
welcome()
(it's a murder mystery type thing and I just need help getting it to work)
i need to type as it says there is to much codeeeeeee
please reply for answers and if you need any more details
thank you everyone for you kindness and support :-)

Python-Using Random Choice to Prompt User-Adventure Game

I am having trouble with my code. When running my code and select the no option to play the game again the game ends. But, I am having trouble with my code when I select the yes option to play again, it does not automatically go back to play the game again. What am I do wrong?
import time
import random
response = []
action_list = ["option1", "option2"]
print(random.choice(action_list))
def print_pause(message_to_print):
print(message_to_print)
time.sleep(2)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 == response:
break
elif option2 == response:
break
else:
print_pause("Sorry, I do not follow.")
return response
def intro():
print_pause("You have approached your apartment building.")
print_pause("You noticed a shadow nearby.")
print_pause("Should you run and drive off to the nearest safe location?")
print_pause("Should you face your fears and attack?")
def adventure_panic():
response = valid_input("Please make your decision. "
"Would you like run or attack?\n",
"run", "attack")
if "run" in response:
print_pause("Run towards your car and drive to a safe location.")
print_pause("Call the police to inform them what you saw.")
elif "attack" in response:
print_pause("Slowly walk towards the nearby shadow.")
print_pause("Grab your pocketknife and pepper spray.")
print_pause("As you come closer to the shadow.")
print_pause("You find out that it is just a cat")
print_pause("Congratulations! You're safe.")
play_again()
def play_again():
response = valid_input("Would you like to play again? "
"Please say 'yes' or 'no'.\n",
"yes", "no")
if "yes" == response:
print_pause("Great, let's play again!")
intro()
adventure_panic()
elif "no" == response:
print_pause("Ok, exit game!")
exit(0)
def play_panic():
intro()
# adventure_panic()
play_panic()
In def play_panic() you only call intro() try to change it to def play_panic(): intro() adventure_panic() play_again()
When I ran your code, I didnt even get to the play again function. Instead of calling the adventure_panic() function in play_panic(), you registered it as a comment with a "#". You also didnt call the play_again function. The actual function works properly for me
import time
import random
response = []
action_list = ["option1", "option2"]
print(random.choice(action_list))
def print_pause(message_to_print):
print(message_to_print)
time.sleep(2)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 == response:
break
elif option2 == response:
break
else:
print_pause("Sorry, I do not follow.")
return response
def intro():
print_pause("You have approached your apartment building.")
print_pause("You noticed a shadow nearby.")
print_pause("Should you run and drive off to the nearest safe location?")
print_pause("Should you face your fears and attack?")
def adventure_panic():
response = valid_input("Please make your decision. "
"Would you like run or attack?\n",
"run", "attack")
if "run" in response:
print_pause("Run towards your car and drive to a safe location.")
print_pause("Call the police to inform them what you saw.")
elif "attack" in response:
print_pause("Slowly walk towards the nearby shadow.")
print_pause("Grab your pocketknife and pepper spray.")
print_pause("As you come closer to the shadow.")
print_pause("You find out that it is just a cat")
print_pause("Congratulations! You're safe.")
play_again()
def play_again():
response = valid_input("Would you like to play again? "
"Please say 'yes' or 'no'.\n",
"yes", "no")
if "yes" == response:
print_pause("Great, let's play again!")
intro()
adventure_panic()
elif "no" == response:
print_pause("Ok, exit game!")
exit(0)
def play_panic():
intro()
adventure_panic() #remove the # so that adventure_panic() is called. If there is a # python registers it as a comment and it is ignored
play_again() #calls the play again function
play_panic()

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

changing variables in one function from another function

I'm working on a text based adventure game in python. Nothing super fancy. I want to have a lever in 2 different rooms unlock a gate in a third room. Both levers need to be pulled in order for the gate to be unlocked.
here are the two rooms with the levers.
def SnakeRoom():
choice = raw_input("> ")
elif "snake" in choice:
FirstRoom.SnakeLever = True
print "As you pull the lever... You hear something click down the hall behind you."
SnakeRoom()
elif "back" in choice:
FirstRoom()
else:
dead("Arrows shoot out from the walls. You don't make it.")
def WolfRoom():
choice = raw_input("> ")
elif "wolf" in choice:
FirstRoom.WolfLever = True
print "As you pull the lever... You hear something click down the hall behind you."
WolfRoom()
elif "back" in choice:
FirstRoom()
else:
dead("Arrows shoot out from the walls. You don't make it.")
Here is the room with the gate.
def FirstRoom():
Lever = WolfLever and SnakeLever
choice = raw_input("> ")
if "straight" in choice and Lever != True:
print "You see a large gate in front of you. The gate is locked, there doesn't seem to be any way to open it."
FirstRoom()
elif "straight" in choice and Lever == True:
SecondRoom()
elif "left" in choice:
WolfRoom()
elif "right" in choice:
SnakeRoom()
elif "lever" in choice:
print "WolfLever: %s" % WolfLever
print "SnakeLever: %s" % SnakeLever
print "Lever: %s" % Lever
FirstRoom()
I shortened the code so you don't have to read through all the unnecessary stuff.
My biggest problem is I'm not super familiar with the Python language yet, so I'm not sure how to word everything to find the answers I'm looking for.
edit: Instead of FirstRoom.WolfLever I also tried just using WolfLever, in the body of my code, above Start() I have:
WolfLever
SnakeLever
Lever = WolfLever and SnakeLever
But my functions weren't updating these values. So I tried the FirstRoom. approach.
Credit to #Anthony and the following link: Using global variables in a function other than the one that created them
Globals definitely were the answer (With the exception of using classes). Here's what my WolfRoom() and SnakeRoom() functions look like now:
def WolfRoom():
global WolfLever
choice = raw_input("> ")
elif "wolf" in choice:
WolfLever = True
print "As you pull the lever... You hear something click down the hall behind you."
WolfRoom()
For FirstRoom() I added
global Lever
to the beginning of the function and right before Start() I have
WolfLever = False
SnakeLever = False
this way I have no errors or warnings (Was getting syntax warnings for assigning a value to my levers before declaring them as global) and everything works perfectly.

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(">")

Categories

Resources