Python programming, syntax error for game - python

#makes a varible called name to identify the players name
name=input("Hello person, Whats your name?")
#prints their name
print("Hello", name)
#console asks the player if they want to play the game, if choice is "yes" then continue, else say "ok bye bye" (at the bottom!!)
print("Do you want to hear a story?", name)
choice=input("Yes, No?")
if choice==("yes" or "yes " or "Yes" or "Yes "):
print("Ok", name,", listen up")
print("There was once an old, old house at the top of a hill Sooooo high it was above the clouds")
housename=input("What do you want to call the house?")
print("The old,",housename,"was once owned by an old lady. You decide to go up to the", housename, ",you encounter a ghost in your path. You see a varitety of weapons beside you, an axe, sword and a bow.")
#asks the player if they want an axe sword or bow
choice3=input("Do you choose the axe, sword or bow?")
#if the choice is "bow" then proceed with this code
if choice3==("bow" or "Bow" or "bow " or "Bow "):
print("You equip the shoddy Bow, The bow feels as if it could snap any second.")
#sets the enemyshealth as 10
enemyhealth=int(10)
#makes a while loop to keep the battle going instead of 1 time.
while enemyhealth >= 1:
print("Take a shot!")
bowattack=input("Type attack to fire an arrow!")
if bowattack==("attack"):
import random
#randomiser for damage generator
damage = ["1", "2", "3", "4"]
damage2 = int(random.choice(damage))
enemyhealth = enemyhealth - damage2
print("The ghost took some damage. Enemys health:", enemyhealth)
else:
print("Are you sure you typed shoot?")
#if the enemys health gets below 1 print you killed the ghost, reward system! **this is what im having trouble with!!**
if enemyhealth <= 1:
print("You killed the Ghost!!")
print("You vanquished the ghost, you now collect a new weapon!")
#confirms the reward, either gives the player a shiny bow or a double shot bow.
import random
reward = ["Shiny bow", "Doubleshot bow"]
#randomiser for either reward
reward2 =(random.choice(reward)
#prints what weapon the player got
#THIS IS THE PROBLEM, ON THIS LINE
print("You got a:", reward2)
#pointless easteregg :D
elif choice==("maybe"):
print("You found an easter egg, congrats. PS this does nothing")
#if the player typed anything other than yes say ok bye bye.
else:
print("Ok, bye bye", name)
I am fully aware that the code does not yet have the other 2 if statements for the axe or sword. What i'm having trouble with is the reward generator for killing the ghost. I think its an indention error; it says syntax error for the print line.
I know this is rather alot of code to take in but i'd really appreciate it if could help me fix this; if you see anything I could make a shortcut around that would also be helpful.
Im using python 3.4.2!

You're missing a closing parenthesis in the previous line:
reward2 =(random.choice(reward)
should be:
reward2 =(random.choice(reward))

Also, the line if choice==('yes' or 'yes ' or 'Yes' or 'Yes '): wont work.
Try this:
if choice.strip().lower() == 'yes':
# whatever
strip will remove whitespaces. lower will put the string in lowercase
The same happens with choice3

Related

I am making a game for my python class and I cannot get it to run

I am making a word python game for my class and the code does not run. I run the code on the command prompt and every time I do nothing happens and I get no errors. I am beginner at python and our assignment for our class was to come up with a game. I am trying make a word/adventure game. I know most people here know more than me so any help would be greatly appreciated!
import time
import sys
A = ["a".lower().strip()]
B = ["b".lower().strip()]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
constant = ("ONLY USE A or B!!!")
def start():
print ("After a long night of partying and drinking soda with your buds, ")
"You wake up in the middle of a lawn and that is when you see a hot chick "
"running towards you. This is a weird scenerio because no chicks have ever ran towards you! "
"what will you do!?:"
time.ZaWardo(1)
print(""" A. Ask the girl why is she running and ask if she needs help
B. Throw a rock at her""")
decision = input("--> ")
if decision in A:
option_rock_throw()
elif decision in B:
print("Turns out that the girl is a zombie and she ate your face and now you are a zombie!"
"################################ GAME OVER #####################################")
sys.exit
else:
print (constant)
start()
def option_rock_throw():
print ("You knock out the girl to realize that she is one of your classmates that you had a crush enter code hereon"
"so you decide to go check on her to realize that she is a zombie so you smash her head with"
"a rock. Now you realize that there is a horde of zombies coming for you. What will you do!?:")
time.ZaWardo(1)
print(""" A. run into the church and barricade yourself
#B. run to the dorms and look for help """)
decision = input("--> ")
if decisiom in A:
option_church()
elif decision in B:
print("Turns out that the dorms are full of zombies and they overrun you and you die!"
"################################ GAME OVER #####################################")
sys.exit
else:
print (constant)
start()
def option_church():
print ("You run into the church and barricade yourlsef just to find the priest in the church! "
"the priest is the first human you have encountered and he tells you that over night there was a "
"zombie outbreak! He then asks you if you would like to try and escape! What will your choice be!?")
time.ZaWardo(1)
decision = input("--> ")
You never call start() outside the function. Place a block like the following at the bottom of your script:
if __name__ == "__main__":
start()

I keep getting a NameError in Python, saying that things are not defined, although I did define them

So I'm creating this based of this resource, linked here: https://www.derekshidler.com/how-to-create-a-text-based-adventure-and-quiz-game-in-python/
EDIT: Here is a GitHub link to all the code: https://github.com/gabby-lucies/Quarter-1-Project/blob/master/intro.py
I'm currently stuck however, in my very first option, anytime to choose any of the options listed below, I get a NameError saying that my options are not defined. Can anyone give me any advice? Thanks! Also, sorry if this is a dumb question.
#importing
import time
#How players could respond
answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
#Objects
fwomp = 0
bownarrow = 0
sword = 0
money = 0
#playerName = input("Enter Your Name: ") #gets the player's name, obviously
required = ("\nUse only A, B, or C.\n")
#Startup
def intro():
#print("There is no saving. Sorry!")
#print("Hello! Please enter your name.")
#print("Nice to meet you!")
print("Let's begin!")
print("You wake up in a forest. You can't remember anything. You look around and find")
print("a small creek. You hear sound nearby that sounds like some sort of woodland creature.")
print("You also see some smoke in the distance. What would you like to do ?")
time.sleep(2)
#Choice 1 Options
print("A. Follow the creek.")
print("B. Follow the sound of the woodland creature.")
print("C. Walk towards the smoke.")
choice = input(">>> ") #gets choice
time.sleep(1.5)
if choice in answer_A:
option_creek() #Gives player creek option
elif choice in answer_B:
option_animal() #Give Fwomp options
elif choice in answer_C:
option_smoke() #Gives smoke options
else:
print(required)
intro()
def option_creek():
print("You follow the creek for an hour, and you eventually come across the river.")
print("You followed the river for another hour, and you found a riverside village.")
print("You walk into the village, desperately looking for food and water.")
print("You come across a large pub. It doesn't look very busy.")
print("You also come across an elegant resturant. It must be very expensive.")
print("There is also family outside of their house eating freshly picked food from their garden.")
print("Where will you go?")
print("A. Pub B. Resturant C. Family")
time.sleep(2.5)
choice = input(">>> ")
if choice in answer_A:
option_pub()
if choice in answer_B:
option_resturant()
if choice in answer_C:
option_family()
else:
print(required)
option_creek()
def option_smoke():
print("You walk towards the smoke. Eventually you find the source of the smoke.")
print("The smoke is coming from a lost and very angry tribe.")
print("They also don't speak your language.")
print("When they spot you, and you have nothing to offer them in return, so they assume you are there to kill them.")
print("Anways, fifty of them shot you with arrows all at once.")
time.sleep(2)
print("Also, you're dead!")
time.sleep(2)
option_smoke()
def option_animal():
print("Seriously, you walked towards a strange animal sound just like that?")
print("Luckily, it is only a Fwomp. It doesn't kill you, but it does glare at you strangely.")
print("Fwomps are cute, so you want to pet it.")
print("You also want to take the Fwomp.")
print("You're also hungry and horrible so you also kind of want to eat the Fwomp.")
print("What will you do?")
print("A. Pet Fwomp B. Take Fwomp C. Eat Fwomp")
time.sleep(2.5)
choice = input(">>> ")
if choice in answer_A:
fwomp = 1
option_petfwomp()
elif choice in answer_B:
fwomp = 1
option_takefwomp()
elif choice in answer_C:
option_eatfwomp()
else:
print(required)
option_animal()
I've looked over your github code, so i'm changing my answer for that
After each of your option functions, you're immediately calling it, shown here
def option_animal():
print("Seriously, you walked towards a strange animal sound just like that?")
print("Luckily, it is only a Fwomp. It doesn't kill you, but it does glare at you strangely.")
print("Fwomps are cute, so you want to pet it.")
print("You also want to take the Fwomp.")
print("You're also hungry and horrible so you also kind of want to eat the Fwomp.")
print("What will you do?")
print("A. Pet Fwomp B. Take Fwomp C. Eat Fwomp")
time.sleep(2.5)
choice = input(">>> ")
if choice in answer_A:
fwomp = 1
option_petfwomp()
elif choice in answer_B:
fwomp = 1
option_takefwomp()
elif choice in answer_C:
option_eatfwomp()
else:
print(required)
option_animal()
As python is a procedural language, only the code that is before this call in the file exists, thus, at the point where you call option_animal, option_petfwomp doesn't exist, however if you remove all of these function calls and move them to the end of the file, it should work.
Hope this helps
Your code is not wrong, it's simply incomplete. I'm assuming you're using this to learn Python. Let me ask you a quick question. When you press run, you get some options.
What will you do?
A. Pet Fwomp B. Take Fwomp C. Eat Fwomp
If I type "A" and hit enter, it runs option_petfwomp()
But in your code you haven't defined this function.
If you add:
def option_petfwomp():
print("option_petfwomp")
def option_takefwomp():
print("option_takefwomp")
def option_eatfwomp():
print("option_eatfwomp")
you'll understand how it works. Basically, you are controlling the flow of the program. If you define these functions, you can then call them from your game.
My advise:
Think about what you want your code to do.
Map it out as a diagram or psuedo-code.
Code it.
It seems like you copy-pasted the code, without knowing what it does, or knowing what you want it to do. That's all fine, but take time out to understand your code before hoping someone else will understand it for you.

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

Cannot fix python invalid syntax

import time
print("hello, do you want to play this detective game?")
choice == input( "Yes or no?")
if choice 'no' :
print: "ok then, bye"
exit
if choice'yes':
start
name == input("Enter your name")
print("hello, " + name ", in this game you are a famous detective handling a theft case."
time.sleep(1)
print(" you have gone on a holiday but ended up lost in the forest. you see a man walking up to you")
time.sleep(1)
print ("man:' hi there! you seem quite lost! Do you want to stay the night with me?'")
print(" you said:'why should i? i dont even know you'")
print(" man : ' Do as you please, but if you stay in the forest for the night here's a friendly warning: there's wild wolves in the forests.'")
choose == input( "stay the night or refuse?" )
if choose "refuse":
print("man: ' boy, you are stubborn!")
print( "the man walks away, leaving you behind" + " In the end, you got eaten by the wolves due to your stubborness. THE END")
choice == input("do you want to play again? yes or no?")
if choice "yes":
start
if choice "no":
print( "ok then, bye!")
exit
Basically my question is this ' invalid syntax' at the upper [do you want to play? ] 'no' response.
But when I erase it the problem goes to the next line. It is very annoying and i cant find how to solve it.
I tried changing between ' and " but the result is still the same.
I would be glad if any of you would take the time to response as i just started yesterday and is still not very clear about invalid syntax.
if choice 'no' :
is the culprit (and same problem on line 8 and elsewhere). The expression requires a == to make:
if choice == 'no' :
However, line 3 will cause a problem before you get there - choice is not defined. == is a logical operator, it does not mean assignment as the code would seem to need to do at that point. Change it to perform assignment with =:
choice = input( "Yes or no?")
Also, it's better to test against lower case because you don't know what combination of upper and lower case characters might be entered by the user:
if choice.lower() == 'no' :
Line 9 reads start - again. Perhaps you mean that as a comment? If so add a '#' at the start of the line.
These problems are the tip of the iceberg. Perhaps you should read a few tutorials and code in small iterative increments to build up your program.
issues:
choice == input() is wrong make it choice = input()
choice 'no' : is again in many place wrong make it choice == 'no'
start/exit is not required
print() function must have closing parenthesis
fixed code:
import time
def my_game():
print("hello, do you want to play this detective game?")
choice = input( "Yes or no?")
if choice == 'no' :
print("ok then, bye")
if choice == 'yes':
name = input("Enter your name")
print("hello, " + name + ", in this game you are a famous detective handling a theft case.")
time.sleep(1)
print(" you have gone on a holiday but ended up lost in the forest. you see a man walking up to you")
time.sleep(1)
print ("man:' hi there! you seem quite lost! Do you want to stay the night with me?'")
print(" you said:'why should i? i dont even know you'")
print(" man : ' Do as you please, but if you stay in the forest for the night here's a friendly warning: there's wild wolves in the forests.'")
choose = input( "stay the night or refuse?" )
if choose == "refuse":
print("man: ' boy, you are stubborn!")
print( "the man walks away, leaving you behind" + " In the end, you got eaten by the wolves due to your stubborness. THE END")
choice = input("do you want to play again? yes or no?")
if choice == "yes":
my_game()
if choice == "no":
print( "ok then, bye!")
if __name__ == "__main__":
my_game()
Try this:
import time
def game()
print("hello, do you want to play this detective game?")
choice == input( "Yes or no?")
if choice == 'no' :
print("ok then, bye")
break
if choice == 'yes':
name == input("Enter your name")
print("hello, " + name ", in this game you are a famous detective handling a theft case."
time.sleep(1)
print(" you have gone on a holiday but ended up lost in the forest. you see a man walking up to you")
time.sleep(1)
print ("man:' hi there! you seem quite lost! Do you want to stay the night with me?'")
print(" you said:'why should i? i dont even know you'")
print(" man : ' Do as you please, but if you stay in the forest for the night here's a friendly warning: there's wild wolves in the forests.'")
choose == input( "stay the night or refuse?" )
if choose == "refuse":
print("man: ' boy, you are stubborn!")
print( "the man walks away, leaving you behind" + " In the end, you got eaten by the wolves due to your stubborness. THE END")
choice == input("do you want to play again? yes or no?")
if choice == "yes":
game()
if choice == "no":
print("ok then, bye!")
break
else:
#continue your game here
Hope this works! This might be better.

How do I move to different parts of code in this game/story

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?

Categories