I'm been having a lot of trouble properly using functions in python. Im a beginner so I'm creating this kinda maze like game, and want to use functions so that a user can return to previous locations if they choose to. The problem is that all the code after the "def sec2():" does not run, and it totally skips over this block of code. So if the user were to run the program and choose left, the program finishes with "Ah, nevermind, remember those numbers," never prompting the user with anything or printing anything from sec2. I believe my problems could be occurring with indentation. If anyone has any idea as to why the code under my functions isn't executing please let me know! Many thanks!
print ("********")
print ("Hey there soldier. This is General Chris.")
print ("I understand you are in quite the situation!")
print ("Just 4 hours ago, your patrol was ambushed by ISIS...You may not rememeber much after being knocked unconscious!")
name = input('Whats your name, soldier?')
print ("********")
print ("Alright, here's the deal",name)
print ("You are now being held hostage in an encampment near Soran, Iraq.")
print ("Unfortunately for you, our hackers have recieved intel that your captors plan on executing you in just two hours.")
print ("You dont have long to make your escape! Get moving fast!")
def sec1():
print ("********")
print ("You have two doors in front of you. Do you choose the door on the left or right?")
room1 = input('Type L or R and hit Enter.')
if room1 == "L":
print ("********")
print ("Good choice",name)
print ("Whats this? A slip of paper says '8642' on it...Could it mean something?")
print ("Ah, nevermind! Remember those numbers!")
def sec2():
print ("********")
print ("Now you have a choice between crawling into the cieling, or using the door!")
room2 = input('Type C for cieling or D for door, and hit Enter!')
if room2 == "C":
print ("********")
print ("Sure is dark up here in the ducts!")
print ("Stay quiet, and move very slowly.")
def ductoptionroom():
print ("Do you want to continue into the ducts or retreat?")
ductoption = input('Type C or R and hit Enter!')
if ductoption == "C":
print ("You are continuing into the ducts!")
elif ductoption == "R":
sec2()
else:
print ("Focus on the mission!")
elif room2 == "D":
print ("********")
print ("You slowly turn the door knob and see a guard standing there...He doesnt notice you!")
print ("Look, theres a piece of rope on the ground! You could use this to strangle the guard!")
def guardkillroom():
print ("Do you want to try and kill the guard so you can continue on your escape?")
guardkill = input ('Type K for kill or R for retreat and hit Enter!')
if guardkill == "K":
print ("********")
print ("You sneak behind the unsuspecting guard and quickly pull the rope over his neck!")
print ("You've strangled the guard! Now you can continue on your mission!")
elif guardkill == "R":
guardkillroom()
else:
print ("We dont have all day!")
guardkillroom()
else:
print ("Focus soldier!")
room2()
elif room1 == "R":
print ("********")
print ("Uh oh. Two guards are in this room. This seems dangerous.")
print ("Do you want to retreat or coninue?")
roomr = input('Type R or C and hit enter.')
if roomr == "R":
print ("********")
print ("Good choice!")
sec1()
elif roomr == "C":
print ("********")
print ("You continue and are spotted by a guard.")
print ("***MIISSION FAILED***")
def gameover1():
print ("Do you want to retry?")
retry1 = input("Type Y or N and hit enter!")
if retry1 == "Y":
sec1()
elif retry1 == "N":
print ("********")
print ("Thanks for playing!")
else:
gameover1()
sec1()
It looks like you only ever define sec2 and you never actually call it. When you do something like def myfunc() it just tells python what should happen when that function is called. The code will never actually be ran until you run myfunc() from somewhere else in the code. And the only place sec2 is called is recursively from within sec2 (if the player decides to retreat from the ducts)
So to use sec2 you need to call it from somewhere else within sec1
I'm not sure where that should be based upon a quick reading of the game but for testing you could do something like the following
print ("Ah, nevermind! Remember those numbers!")
def sec2():
....
elif room2 == "D":
sec2()
Additionally since sec2 is defined inside of sec1 that means sec2 can only ever be called inside of sec1 as well. I suspect that was not what was intended (though I could be wrong). To fix that you could do the following
def sec2():
...
def sec1():
... #All the same code as before except for the sec2 definition
sec1()
Related
I am making trying to make a text base game and I want to make a level selection
print ("You and your crew are pinned in the remains of a church on the top floor, with two wounded. Being fired at by German machine guns, matters will soon only get worse as you see German reinforcements on their way. Find a way to escape with your 9 man crew with minimal casualties.")
#Start up Menu
print ("Before you start the game ensure that you are playing in fullscreen to enhance your gaming experience")
print("")
print ("")
time.sleep(1)
print ("Menu")
print ('Instructions: In this game you will be given a series of paths. Using your best judgment you will choose the best path by using the "1" or "2" number keys, followed by pressing the "enter" button')
print ('If the wrong path is selected, there will be consequences of either death, or a lower final score.')
print ('Death will end the game, and you will be forced to start from the beginning of the level.')
time.sleep(1)
print ('If you will like to restart, press "r"')
print ('If you will like to quit, press "q"')
print ('If you want to play level 1, press "a"')
print ('If you want to play level 2, press "s"')
print ('you cannot restart or quit at this time')
print ('')
print ('')
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
over here, why does it say "level is not defined? and how can I fix it so the program works?
levelselection()
if level == "1":
print ("good job!")
First of all , level is a local variable to your function levelselection .
After that you are returning level variable but not saving it to some other variable.
Do like this -
levelselected = levelselection()
if levelselected == "1":
print ("good job!")
I would suggest you to read about python variables scope, this is a good source.
Explanation:
As level is initialized within the function levelselection you won't have access to the variable outside the function.
Solution:
1.You can fix this with defining level in a global scope.
2.Also, you can return level from the function as you did, but you will need to catch this return value, for example:
level = levelselection()
if level == "1":
print ("good job!")
you forgot to indent the return level. So in your current code, the return doesn't belong to the levelselection()function.
Try this:
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
level = levelselection()
if level == "1":
print("good job!")
import random
import time
name=input("Welcome to the game what is your name")
print(("This is a numbers game"),(name),
("You will be playing against the computer"))
print
("The idea of the game is to get closer than the computer to 21 without
going over 21")
,ready="N"
ready = input("Are you ready to play the game?").lower
if ready == "yes" or ready =="y":
score=0
The Error is coming up and saying its the line above this
while(score)<21 and(ready=="Y" or ready == "Yes"
or ready =="YES" or ready ==
"yes" or ready =="y"):
player1=random.randint(1,21)
score=(score+player1)
time.sleep(3)
print(("You have scored"),(score))
if score<21:
ready=input("Do you want to add more to your score")
if score>21:
print("Sorry Over 21 You Went Bust The Computer Wins")
else:
print("Ok well done lets see what the computer gets")
(Ignore this line please)
computerscore=0
while(computerscore)<21 and (computerscore)<(score):
computer=random.randint(1,21)
computerscore=(computerscore+computer)
time.sleep(3)
print(("The Computer Has Scored"),(computerscore))
if(computerscore)<=21 and (computerscore)>(score):
print("sorry the computer wins")
else:
print("You win well done")
break
I ran it in the CMD
You have to indent the blocks after your conditions lines, that's how python understands if you're still in the condition or not.
if a>b:
print b
print "I'm still in the case a>b"
else:
print a
Use tab or 4 spaces to indent.
I'm pretty new to programming, but I've got a quick question. I'm trying to write a sort of "choose your own adventure" game, but I've run into a problem. I'm only really as far into if statements in the code, but I want to be able to send the user back to previous code when they type something.
For example:
print "You are in a room with two doors to either side of you."
choiceOne = raw_input("Which way will you go?")
choiceOne = choiceOne.lower()
if choiceOne = "r" or choiceOne = "right":
print "You go through the right door and find yourself at a dead end."
elif choiceOne = "l" or choiceOne = "left":
print "You go through the left door and find yourself in a room with one more door."
else:
print "Please choose left or right."
In the if statement, I want to send the user back to choiceOne's raw_input(). In the elif statement, I want to give the user the option to either proceed through the next door, or return to the first room to see what secrets the other door may hold. Is there any way to do this? I don't care if the way is complicated or whatever, I just want to get this working.
Are you looking for a while loop?
I think that this website explains it very well: http://www.tutorialspoint.com/python/python_while_loop.htm
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
→
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Use a while loop:
while True:
print "You are in a room with two doors to either side of you."
choice_one = raw_input("Which way will you go?").lower()
if choice_one == "r" or choice_one == "right":
print "You go through the right door and find yourself at a dead end."
continue # go back to choice_one
elif choice_one == "l" or choice_one == "left":
print "You go through the left door and find yourself in a room with one more door."
choice_two = raw_input("Enter 1 return the the first room or 2 to proceed to the next room")
if choice_two == "1":
# code go to first room
else:
# code go to next room
else:
print "Please choose left or right."
You need to use == for a comparison check, = is for assignment.
To break the loop you could add a print outside the loop print "Enter e to quit the game":
Then in your code add:
elif choice_one == "e":
print "Goodbye"
break
After the initial question of how much do you take, it works fine. If you type 0 you die, 5 million it says nice take. After it says nice take, it exits the program and forgets the rest of the code.
How do I get python to load the next part of the code and run it.
from sys import exit
def bank_vault():
print "This room is full of money up to 5 million dollars. How much do you take?"
choice = raw_input("> ")
if "0" in choice:
dead("You are robbing a bank and took nothing... The cops shot you in the face.")
how_much = int(choice)
if how_much < 5000000:
print "Nice take, now you have to escape!"
escape_route()
def escape_route():
print "There are cops blocking the front door."
print "There are cops blocking the back door."
print "There is no way to get out of there."
print "You see a small opening on the ceiling."
print "Type ceiling to go through it."
print "Or type stay to try your luck."
escaped_cops = False
while True:
choice = raw_input("> ")
if choice == "stay":
dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
elif choice == "ceiling" and not escaped_cops:
print "You escaped! Now wash that money and don't go to prison."
escaped_cops = True
def dead(why):
print why, ""
exit(0)
bank_vault()
Cool game. I love games and would like to try to improve your code. Code below works on Python 3. It should work on Python 2:
from sys import exit
try: input = raw_input # To make it work both in Python 2 and 3
except NameError: pass
def bank_vault():
print("This room is full of money up to 5 million dollars. How much do you take?")
how_much = int(input("> ")) # Why not eliminate choice variable here?
if how_much == 0:
dead("You are robbing a bank and took nothing... The cops shot you in the face.")
elif how_much < 5000000: # Changed to else condition
print("Nice take, now you have to escape!")
else: # Added a check
dead("There isn't that much!")
def escape_route():
print("There are cops blocking the front door.")
print("There are cops blocking the back door.")
print("There is no way to get out of there.")
print("You see a small opening on the ceiling.")
print("Type ceiling to go through it.")
print("Or type stay to try your luck.")
escaped_cops = False
while not escaped_cops:
choice = input("> ")
if choice == "stay":
dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
elif choice == "ceiling":
print("You escaped! Now wash that money and don't go to prison.")
escaped_cops = True
def dead(why):
print(why)
exit(0)
bank_vault()
escape_route()
You have to call the function escape_route rather than exit.
Also, when checking for choice you call dead no matter what.
In reply to your comment:
You need to check if it's 0 then call dead, if it's not 0 don't bother with the else, go directly to the if how_much < 5000000 and call escape_route
You need to try and convert the input to an int if it isn't 0!
And what happens if they take more than 5 mil?
I'm pretty new to programming and I'm currently going through "Learn Python The Hard Way". I'm doing exercise 36, which asked to create my own simple text based game.
Unfortunately I've ran into a problem. What I'm trying to do, is basically make the function allow a maximum of 3 times of repeated use of 'else', after which it should run 'dead()' function.
I understand that using 'while', it will loop 'else' forever. I tried creating a 'for'-loop which should build a list and after number 3 it should run 'dead()', but that didn't really work. I tried positioning it before and after 'while', but that failed as well.
def genie():
print "Suddenly a genie appears!"
print "The genie says that it will grant 3 of your wishes. "
print "Do you want to wish something, or leave him?"
while True:
next = raw_input("> ")
if next == "wish":
print "You want your 3 wishes granted. "
wishes()
elif next == "leave":
print "The genie gets angry at you for wasting its time! "
print "You suddenly appear in a huge room with a dragon in it. "
dragon_room()
else:
print "The genie doesn't understand your muttering."
i = 0
angry = []
for i in angry:
print "The genie has got a little bit annoyed."
i = i + 1
angry.append(i)
if i == 3:
dead("The genie got angry and killed you!")
else:
exit()
I think what you want is something like:
for i in range(3):
next = raw_input("> ")
if next == "wish":
...
wishes()
break
elif next == "leave":
...
dragon_room()
break
print "The genie doesn't understand your muttering."
if i:
print "The genie has got a little bit annoyed."
else:
dead("The genie got angry and killed you.")
exit()
The else on a for (or while) loop only runs if the loop doesn't break early.
You should place a count variable outside the while loop, and increase it by 1 when "The genie not understand".
print "Suddenly a genie appears!"
print "The genie says that it will grant 3 of your wishes. "
print "Do you want to wish something, or leave him?"
count = 0
while True:
next = raw_input("> ")
if next == "wish":
print "You want your 3 wishes granted. "
wishes()
elif next == "leave":
print "The genie gets angry at you for wasting its time! "
print "You suddenly appear in a huge room with a dragon in it. "
dragon_room()
else:
print "The genie doesn't understand your muttering."
if count == 3:
dead("The genie got angry and killed you!")
else:
print "The genie has got a little bit annoyed."
count += 1