Python-Using Random Choice to Prompt User-Adventure Game - python

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

Related

Text adventure game-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"

Python CMD module quit

I'm programming a simple text adventure game with Python 3 and the cmd module.
I need to somehow trigger the game over method but I didn't find a solution on document.
The CMD module got the do_quit() function, but that needs user input, and quit() or exit() kills the whole program, whereas I just need to get out of cmdloop()
Any idea how to deal with this?
Thanks in advance!
def moveDirection(direction):
global location
if direction in rooms[location]:
if rooms[rooms[location][direction]].get(UNLOCKED, True) == True:
print('You move to the %s.' % direction)
location = rooms[location][direction]
if location == 'Hallway' and bGuardAlive == True:
print("Game over! Guard caught you!")
printLocation(location)
else:
print("Door is locked")
else:
print('You cannot move in that direction')
def main():
printLocation(location)
GameLoop().cmdloop()
class GameLoop(cmd.Cmd):
prompt = '\n> '
def do_quit(self, arg):
"""Quit the game."""
return True
Usually (if I understand correctly), you create you own class derived from Exception, you throw the exception at the place you want to exit, and you will have a try clause where you want to land.
After trial and error i get it working. I needed use postcmd()
Here is my code:
def postcmd(self, stop, line):
if bGuardAlive == False and location == 'Hallway':
print("Game over! Guard caught you!")
return True
elif location == 'Tower Ruins':
print("You won!")
return True
return stop
Hopefully this will help somebody

Always go to: global name is not defined

That's my codes. When it runs it always shows:
nameerror: global name "weapon_choice" is not defined.
But i have already put in the weapon_choice. Why?
from sys import exit
def dead(why):
print why,"YOU ARE EATEN BY ZOMBIES!"
exit(0)
def start():
print "You wake up alone in a room.A crowed of corpses around you."
print "You find some tools beside maybe helpful."
print "What will you get?"
weapons = ['axe', 'bat', 'knife', 'pistol']
print weapons
while True:
weapon_choice = raw_input(">")
if weapon_choice in weapons:
print "Zombies walk towards you, now it's in urgency!"
print "You can't deal with them.You must flee!"
print "You find door and window.Where you will go?"
paths = raw_input(">")
if paths == "window":
dead("You fall down to the ground.")
elif paths == "door":
lift()
else:
dead("oops!")
else:
print "Can't understand what you say."
def lift():
print "You can't recognize the number in the lift."
print "Get out of the lift or tap a floor whatever. "
floor_choice = raw_input(">")
if floor_choice == "get out" and weapon_choice != "pistol":
dead("Outside full of zombies.You have nowhere to go.")
elif floor_choice == "get out" and weapon_choice == "pistol":
print "WOW!!!YOU KILL ALL THE ZOMBIES!!"
print "you get back to the bed for another sleep."
start()
elif floor_choice == "tap a floor" and weapon_choice == "axe":
street_1()
elif floor_choice == "tap a floor" and weapon_choice == "bat":
friends_axe()
elif floor_choice == "tap a floor" and weapon_choice == "pistol":
kill_frinends()
else:
print "Can't understand what you say."
start()
I thought when it runs,at the very beginning,it have already ask the inputer to input the weapon_choice.
First, it looks like you have an indention error. Everything from
while True:
to
else:
print "Can't understand what you say."
should be tabbed over one level so that it is inside the start function.
There is also a scope issue In your lift function: weapon_choice is not defined.
You should pass weapon_choice as a parameter to the lift function when calling it:
def start():
print "You wake up alone in a room.A crowed of corpses around you."
print "You find some tools beside maybe helpful."
print "What will you get?"
weapons = ['axe', 'bat', 'knife', 'pistol']
print weapons
while True:
# your while loop code here
elif paths == "door":
lift(weapon_choice)
# the rest of your while loop code here
def lift(weapon_choice):
# your lift function code here
After that, you just need to write the functions street_1, friends_axe, and kill_frinends--then you're done!
You should be getting: NameError: name 'weapons' is not defined
while True:
weapon_choice = raw_input(">")
is called before start() hence the error. Try enclosing code blocks in functions for better readability and debugging.
Update: I believe your code indentation above is not correct. It works fine, and as expected without the error you mentioned.

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.

Variable is not updating in function

I'm new in Python but bear with me.
In my code, I am trying to make variable room to 2, via west() function.
Code:
EDIT: I have isolated most of the non-essential code.
room = 1
cmds = 'west'.lower()
def isValidCMD(cmd):
if cmd in cmds:
return True
else:
print("Unknown command. For help type /help, for available options type /options")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
return False
def runCMD(cmd):
if cmd == '/help':
help()
elif cmd == '/exit':
exit()
elif cmd == '/about':
about()
elif cmd == '/stats':
stats()
elif cmd == '/options':
options()
elif cmd == 'north':
north()
elif cmd == 'south':
south()
elif cmd == 'east':
east()
elif cmd == 'west':
west()
elif cmd == '/lookaround':
look_around()
def west():
if room == 1:
print("You head on over to the lab, to get some advice from Professor Andrew.")
return 2 #LINE 40 < -------
elif room == 7:
print("You head back to Auderban Square feeling primed for battle.")
else:
print("You cannot go west.")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
def main():
while True:
# Town
if room == 1:
print("\nYou are at the centre of town, Auderban Square.".upper())
print("\nYou look at the signpost and see 4 signs.")
print("\t- North - Twinleaf Forest")
print("\t- South - Store of Celestia")
print("\t- East - Deskemon Training Ground")
print("\t- West - Auderban's Deskemon centre")
# Lab
elif room == 2:
print("You are at Auderban's Deskemon Centre")
AndrewConv()
print("\nYou see the exit at the door.")
print("\t- East - Auderban Square")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
main()
Output:
But room keeps its value, 1.
Please give some advice for the future so I won't make the same mistake twice.
Replace west() function with this:
def west():
global room
...
Global variables are widely considered bad programming practice because it is extremely difficult to determine where and when they might be modified in a large program. They also make thread-safe and reentrant code almost impossible to write.
A simple approach would be to have each function accept the room as a parameter and return the “new room.” You can then always update the room in your main function every time you invoke a command.
You will probably end up keeping track of more than the room, though. Consider using a mutable data structure like a dictionary or a class to store the game state, and then passing it into your command functions. That way, it is just as simple to keep up with many state variables as one, and you still do not need global variables.
def main():
state = {'room': 1}
while True:
[...]
if isValidCMD(cmd, state):
runCMD(cmd, state)
def west(state):
thisroom = state['room']
if thisroom == 1:
print("You head on over to the lab, to get some advice from Professor Andrew.")
state.update(room=2)
elif thisroom == 7:
print("You head back to Auderban Square feeling primed for battle.")
else:
print("You cannot go west.")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
There are some additional issues with this code. For example, you duplicate the command prompt code in each command prompt, which is brittle and error prone, and unnecessary since you will be returning to main() anyway.
Edited: Here is a minimal, runnable example:
def main():
state = {'room': 1}
for i in range(20):
oldroom = state['room']
nextroom(state)
print("Went from room {} to room {}.".format(oldroom, state['room']))
def nextroom(state):
state['room'] += 2

Categories

Resources