why does it say "level" is not defined - python

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

Related

Progressing to next menu option in python

I have a question regarding menus and how to make a "progress to Option __ " option (please note, I am very new to Python, so this may be a very easy fix and I just haven't searched for the right thing). In my current code, I have the ability for users to choose one of 4 options with activities in them. A part of options C and D use data from option B (but are able to be visible to the user without doing Option B, just as an information hub of sorts, rather than calculating). I have made up some code to show what I am talking about below:
def printMenu ():
print("Activity List")
print("A: Standalone Activity - What is the weather like")
print("B: Events")
print("C: Times")
print("D: Olympic Standards")
print("X: Exit")
return input("Please choose a selection: ").upper()
def main():
choice = printMenu()
choice
def program(selection):
if selection == "A":
print("The weather is not important, as I am a computer")
elif selection == "B":
eventInfo = input("What is your best event and distance: ")
def sportMenu():
print("1. Return to Main Menu")
print("2. Choose another sport")
print("3. Continue to Part C: Countries")
print("ENTER. Close application")
sportMenu()
sportsMenu = input("Please select an option: ")
if sportsMenu == "1":
main()
elif sportsMenu == "2":
sports()
elif sportsMenu == "3":
times()
else:
exit()
elif selection == "C":
# information for users who selected option C originally
print("Talking about World Record times in certain events")
# if they selected B and chose an event, this is where they would be sent to
print("You have selected the event: ", eventInfo)
timeInfo = input("Please enter your best time (MM:SS.ss): ")
# same menu as above, sending to main, section B to choose a different event, section D for comparison, or exit program
...
elif section == "D":
# information for users who selected option C originally
print("Talking about top competitor's times in certain events and how younger athletes aspire to reach them, and the benefits of comparing times")
# if they selected B and chose an event, and input a time at C this is where they would be sent to
print("Your time of", timeInfo, "for", eventInfo, "has been compared to the World Record time of ____")
# an external file of all World Record times is then referred to, and compared to the user's input in timeInfo
# menus as above, main, going back to B, or C for different events or times respectively, or exit program
elif selection == "X":
exit()
else:
print("Try again, please ensure the letter is shown in the menu")
selection = printMenu()
while selection != 'X':
program(selection)
print()
selection = printMenu()
I am wondering if there is a way for users to input answers in option B, and skip directly to the section of code saying # if they selected B and chose an event, this is where they would be sent to, with information they input in section B (stored in eventInfo I would imagine)? I assume it would be the same process from C to D, and I am almost there, but obviously without those options being defined prior to wanting to jump to them, I get the error. Any help will be greatly appreciated! Thanks

How to add input into a text based program

I created a text based RPG using Python. At the moment when you execute the program it brings you through an introduction and at the end of it i have the user decide to go 1.Left 2. Right 3. Middle. Each place has a unique item needed to complete the game, meaning if you go to the right it will see if you have a specific item appended to your bag. If you do not have it you will return to the main part to decide where to go again. That being said the middle is the main part where i want the user to be able to attack a dragon right away so they can lose, or if prepared with the necessary items appended, win! Now you do not have the option to attack, you just get to the dragon and win, so there is no lose. Any tips of how to incorporate an input throughout the game would be helpful. If more information is needed i can gladly share :).
I tried implementing an input before attacking the dragon but it got caught inside the loop so even when you obtained all the items you would get returned to the main dungeon. Here is a snippet code for the final dungeon for an idea.
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
print_pause("You use the " + str(Weapon) + " against the dragon")
print_pause("But it is not strong enough "
"to defeat the dragon, he uses Fire Breath"
" and, he incinerates you! ")
print_pause("You lose!")
play_again()
break
elif option2 in response:
print_pause("Smart Choice! You head back to the main dungeon")
dungeon_game()
break
else:
print("Sorry, try again")
return response
def middle_dungeon():
print_pause("You go to the middle dungeon.")
print_pause("After a few moments,"
" you find yourself in front of a " + Dragon + "!")
print_pause("This is why you need these magical powers.")
if "MagicRune" in bag:
print_pause("Luckily the Wizard trained you well, you now obtain "
" the power of the " + str(MagicRune) + "!")
print_pause("You attack the dragon! ")
if "MagicRune" not in bag:
print_pause("You do not obtain the necessary magical powers.")
print_pause("It looks like you need a scroll or more power!.")
print_pause("You head back to the main dungeon.")
dungeon_game()
dragon_health = 100
count = 0
while dragon_health > 0:
damage_by_player = random.randint(0, 60)
print_pause(f"You hit the dragon and caused {damage_by_player} damage")
dragon_health = dragon_health - damage_by_player
print_pause(f"dragon health is now {dragon_health}")
count = count + 1
print_pause(f"You successfully defeated the dragon in {count} attempts, you win!")
play_again()
def dungeon_game():
passage = ''
if 'started' not in Dungeon:
display_intro()
Dungeon.append('started')
while passage != '1' and passage != '2' and passage != '3':
passage = input("1. Left\n"
"2. Right\n"
"3. Middle\n")
if passage == '1':
left_dungeon()
elif passage == '2':
right_dungeon()
elif passage == '3':
middle_dungeon()
dungeon_game()
So essentially this output will deny you until you go to the left dungeon and right dungeon, where you see MagicRune in bag: this will let you go to the dragon while loop and win the game.
You need to rearrange your code a bit. Here's how you could change your input function:
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
return option1
elif option2 in response:
return option2
else:
print("Sorry, try again")
Now it returns the option the user chose and lets the calling code determine what to do with that information. This makes it actually reusable. You'd call it like this:
chosen = valid_input("Wanna attack the dragon?", "yes", "no")
if chosen == "yes":
# do that stuff
else:
# do other stuff
You also have another problem that you really need to fix: you are treating function calls like goto statements. This will cause you pain when you're trying to debug your code, and also causes hard-to-track bugs.
For example, you should not call play_again() to restart your code. Instead, set up your code structure so that you don't have to do that. E.g.
def dungeon_game():
while True:
# set up initial game state here, e.g.
bag = ["sword", "potion"]
# call main game logic function
dungeon()
# that function returned, so the game is over.
want_to_play = input("play again?")
if want_to_play == "no":
# if we don't break, the While loop will start the game again
break
def dungeon():
# blah blah dragon attack
if (whatever):
print("You got killed. Game over.")
return # goes back to dungeon_game()
else:
print("You won the fight")
# code for the next thing that happens...
if __name__ == "__main__":
dungeon_game()

Same conditional branch keeps being executed regardless of user input

I'm trying to write the basic code for a random name generator in Python. This will soon become a fully working web application with an easy-to-use GUI but for some reason the program doesn't work.
When I run the program, it asks the user to specify either "console" or "game". When I enter "game" it still carries on with the if route instead of the else route.
import string
#This is a Name Generato
print("Welcome To the first version of my name generator at the moment there is only 20 names but in the final version there will be 200 names with over 25 different tags")
print("First of all what do you need a Console or a game Name?")
console = input()
if (console):
print("is it a,PS4,PS3,XBOX 360,XBOX ONE or PC")
print("NOTE:Wii,PSP and DS are not supported")
consolename = input()
print("The,",consolename)
print("Is good")
print ("now give me one or two key words that you would like in your name out of...")
print("happy,sad,depressed,fox,cow,cat,dog,wolf,lion,lil,lazy,forgetful,gaming,xxx,orthodox,apex,toXic")
firstname1=input()
secondname=input()
print(firstname1)
print(secondname)
print("Good Choice")
else:
print("What game is it?")
print("Minecraft,Black ops 1//2/3,COD,Halo1/2/3/4/5/CE/Reach,Terraria,World of warcraft,League Of Legends")
print("NOTE:Type the Game As you see it!")
game1 = input()
print("Ah good choice eh")
You are getting a string input and you are checking if its True which is always true if its not empty. You need to compare your console variable to a string. Something like this will do the job.
import string
#This is a Name Generato
print("Welcome To the first version of my name generator at the moment there is only 20 names but in the final version there will be 200 names with over 25 different tags")
print("First of all what do you need a Console or a game Name?")
console = input()
if (console=="console" or console=="Console"):
print("is it a,PS4,PS3,XBOX 360,XBOX ONE or PC")
print("NOTE:Wii,PSP and DS are not supported")
consolename = input()
print("The,",consolename)
print("Is good")
print ("now give me one or two key words that you would like in your name out of...")
print("happy,sad,depressed,fox,cow,cat,dog,wolf,lion,lil,lazy,forgetful,gaming,xxx,orthodox,apex,toXic")
firstname1=input()
secondname=input()
print(firstname1)
print(secondname)
print("Good Choice")
else:
print("What game is it?")
print("Minecraft,Black ops 1//2/3,COD,Halo1/2/3/4/5/CE/Reach,Terraria,World of warcraft,League Of Legends")
print("NOTE:Type the Game As you see it!")
game1 = input()
print("Ah good choice eh")

Defining functions in python - code block wont run

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

Code is looped again and again

I have the following code:
def begin_game():
print "You landed on planet and see three rooms."
door = int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password = raw_input("Enter your surname>>>")
if door == 1:
medical_room()
if door == 2:
library()
if door == 3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
When I enter door number, I get medical_room function done but then else statement is executed and code starts again over and over.
My question is why else statement is executed? Shouldn't it stop on if statement, execute inside block and stop?
You need to use elif for the second and third if statements. else only considers the statement immediately before it.
Or since it seems that you're looking for switch statement which does not exist in python you could do something like this:
rooms = {
1: medical_room,
2: library,
3: basement,
}
chosen_room = rooms[door]
chosen_room()
You should be using elif, or else every time you input anything other than 3, the else block will be executed, as door != 3 and the else block only considers the preceding if or elif block.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
Currently, your code tests the first if condition (door==1) and associated actions, then it tests the second and third if conditions. Since the third if statement is False (door==1), it will perform the else statement.
You should use elif statements instead of repeated if statements.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()

Categories