Python Game not going where I want it to go - python

I have finished my text game in python. But, the only problem I have is that when I type in where to go it doesn't go to that place. It goes to the place under the start not what the user inputted in... I don't see any problems with my if and elif statements but don't know where the problem is... In fact i re-did all the elif and if statements but still have the same problem...
# This displays the map for the user to follow to play the game in another window.
from tkinter import*
window = Tk()
# Name of the window that the map is displayed in.
window.title('The Map')
# Size of the window
canvas = Canvas(window, width = 500, height = 500)
canvas.pack()
# This is the file path of the map.
my_image=PhotoImage(file='C:\\Users\\Oscar\\Desktop\\Bangor Uni S2\\ICP-1025-0 Intro to Intelligent Systems 201718\\Lab4\\map.png')
# Opens the window with the map.
canvas.create_image(0,0, anchor = NW, image=my_image)
# Welcome sign to the game.
def displayIntro():
print (" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(" ~ ~")
print(" ~ ~")
print(" ~ WELCOME TO MILK ~")
print(" ~ ~")
print(" ~ MADE BY: ~")
print(" ~ OSCAR TSANG ~")
print(" ~ ~")
print (" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("")
print("")
intropic()
print("")
def intro():
print()
print(" This is the game MILK!!! ")
print("")
print(" You are Farmer Bob and your objective is to find the lost milk ")
print("")
print(" The lost milk is located somewhere on the map ")
print("")
print("Yo would need to use the map to navigate around the farm to find the precious milk ")
print("")
print(" Only you can find the precious milk ")
print("")
print(" You will be in a farm that you will have to navigate through to get to the milk ")
print("")
print(" You will have no help ")
print("")
print(" There are 9 possibility where the milk can be, but only the map has the answer ")
print("")
print(" Now goodluck in finding the milk... ")
print("")
print("")
print("")
print("")
print("")
print("")
#These are all the nodes to the game milk.
# The starting point of the game.
def start():
print(" You are at the start of the game MILK ")
print("Now you will have to use the map to navigate around the farm to find the almighty, godly, delicious MILK!!!!")
way_picked = input("Do you want to go to the Shop 1, Field , Shop , House , Farm , Dead end, Shop 1, Field 1 ???? > ")
# This is where the user picks where they want to go within the game.
if way_picked.lower() == "Shop 1":
shop1()
elif way_picked.lower() == "Field":
field()
elif way_picked.lower() == "Shop":
shop()
elif way_picked.lower() == "House":
house()
elif way_picked.lower() == "Farm":
farm()
elif way_picked.lower() == "Dead End":
deadend()
elif way_picked.lower == "Field 1":
field1()
else:
print("")
print("")
print("")
print("")
print("")
# The field node in the game.
def field():
cow()
print( "This isn't where the milk is... ")
print("This is an empty field full of grass with sheeps and cows munching on it 24/7")
print("")
print("")
way_picked = input(" Start, Shop 1 or Shop ??? > ")
# This is where the user picks where they want to go when they they reach field node.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Shop":
shop()
elif way_picked.lower == "Shop 1":
shop1()
else:
print("")
print("")
print("")
print("")
print("")
# The shop node in the game where Bob gets his eqipment from.
def shop():
print(" This isn't where the milk is... ")
print(" This is the farmers equipment shop.'.. ")
way_picked = input(" Start, Field or House ??? > ")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "House":
House()
elif way_picked.lower == "Field ":
field()
else:
print("")
print("")
print("")
print("")
print("")
# House node of the game where Bob lives.
def house():
print(" This is your house.... ")
print(" This isn't where the milk is... ")
print(" Look harder Bob!!!! ")
way_picked = input(" Start , Shop , Farm ??? > ")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Shop":
shop()
elif way_picked.lower == "Farm":
farm()
else:
print("")
print("")
print("")
print("")
print("")
# The farm node of the game
def farm():
print(" This is the farm.... ")
print(" The milk is nowhere to be seen ")
print(" This is where all the equipment is held... ")
way_picked = input(" Start , Dead End or House??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Dead End":
deadend()
elif way_picked.lower == "House":
house()
else:
print("")
print("")
print("")
print("")
print("")
# This is the dead end of the game where the player has to go back to the previous spot.
def deadend():
print(" This is DEAD END!!!!! ")
print(" You need to go back where you was.... ")
way_picked = input(" Start or Farm ??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Farm":
farm()
else:
print("")
print("")
print("")
print("")
print("")
# This is another field kind of like a duplicate to the first field.
def field1():
print(" This is another field!!!!! ")
print(" Not where the milk is!!!!!!!! ")
way_picked = input(" Start , Shop 1 or Road ??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Shop 1":
shop1()
elif way_picked.lower == "Road":
road()
else:
print("")
print("")
print("")
print("")
print("")
def shop1():
print(" This is Dominos Pizza ")
print(" This is not where the milk is Bob!!!!!! ")
print("Where do you want to go next:")
way_picked = input(" Start , Field 1 or Field ??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Field":
field()
elif way_picked.lower == "Field 1":
field1()
else:
print("")
print("")
print("")
print("")
print("")
# The main road by Bob's farm.
def road():
print(" This is the main road and certainly not whrer the milk is kept ")
print(" Try again Bob ")
print("You are very near the milk...")
print("Do you go forward or backwards????")
way_picked = input("Forwards or Backwards?? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Forwards":
start()
elif way_picked.lower() == "Backwards":
road()
else:
print("")
print("")
print("")
print("")
print("")
# This is where the milk is. When the player reaches this node they win the game.
def milk():
milk1()
print(" Finally!!! Bob you have found the missing milk!!!!! ")
print(" WELL DONE BOB!!!!!!!! ")
print(" NOW DRINK THE MILK BOB!!!!!! ")
mario()
# Prints out all the 10 nodes in my game. And is only using testing to see if every single node prints out as wanted.
displayIntro()
intro()
start()

You are converting the inputted text .lower() and you compare against text that has uppercase in it - this wont work. Fix like this:
if way_picked.lower() == "shop 1":
shop1()
elif way_picked.lower() == "field":
field()
elif way_picked.lower() == "shop":
shop()
elif way_picked.lower() == "house":
house()
elif way_picked.lower() == "farm":
farm()
elif way_picked.lower() == "dead end":
deadend()
elif way_picked.lower() == "field 1":
field1()
where ever you compare. You might also want to use a .strip() to ensure leading/trainling whitespaces are removed as well before comparing them.
Also: please read: How to debug small programs (#1) to get tips how to debug your own programms in a way to find your own errors faster then posting on SO.
One solution would be to make a small function that compares for you:
def comp(textIn, myOption):
"""Returns True if textIn.strip().lower() equals myOption.strip().lower()"""
return textIn.strip().lower() == myOption.strip().lower()
# The starting point of the game.
def start():
print(" You are at the start of the game MILK ")
print("Now you will have to use the map to navigate around the farm to find the almighty, godly, delicious MILK!!!!")
way_picked = input("Do you want to go to the Shop 1, Field , Shop , House , Farm , Dead end, Shop 1, Field 1 ???? > ")
# This is where the user picks where they want to go within the game.
if comp(way_picked,"Shop 1"):
shop1()
elif comp(way_picked,"Field"):
field()
elif comp(way_picked, "Shop"):
shop()
# etcerea ....
The function comp(userInput,"option") will take care of stripping & lowering and comparing and simply return True/False
Edit: other way to deal with this: create dictionary that holds a key (the user input) and the function to call (as value):
def func1():
print("F1")
def func2():
print("F2")
def func3():
print("F3")
def func4():
print("F4")
# function are first class citizens in python, you can store them as
# value (without parentheses) to be called later
options = { "f1" : func1, "f2" : func2, "f3" : func3, "f4" : func4}
while True:
userInput = input("F1 to F4:\n\t").strip().lower() # make input trimmed and lower
if userInput in options:
options[userInput] () # execute the stored function (use value + () to execute)
else:
print("\nWrong input!\n")

Related

I cant pick a choice after looping

def print_menu():
print('1. American')
print('2. Asian')
print('3. Indian')
print('4. Mexican')
print('5. French')
print('6. Italian')
print('7. Seafood')
print('8. Pizza')
print_menu()
menu = input('\nChoose where you want to eat from-->')
if menu == "1":
def american_menu():
print('1. Dempsey Burger Pub')
print('2. Redrock Canyon Grill-Wichita')
print("3. Cheddar's Scratch Kitchen")
print("4. Neighbors| Restaurant & Bar")
print("5. The Kitchen")
print("6. Firebirds Wood Fired Grill")
print("7. Chicken and Pickle")
american_menu()
american = input("\nChoose which American Restaurant--> ")
if american == "1":
print("\nCall Dempsey Burger Pub")
while True:
go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
print_menu()
else:
print("We'll continue with your current choice")
break
so i tried looping it so it goes back to choose again from the Cuisines and moving on to where you want to eat but so far, it just asks the go_back, after i say yes...it keeps repeating the go_back again
any help will be appreciated. Thanks. i want it to loop back to the choices, pick the choice and sub-choice i selected rather than it just picking the choice and not do anything. Thanks again
NB:this is an assignment and i am stuck plus i had a list of the choices but couldnt post it due to the site.
Write a while loop for print_menu and change continue with break
def print_menu():
while True:
#Use 2 while loops if you want. But the loop you are using is not needed
while True:
go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
print_menu()
break
else:
print("We'll continue with your current choice")
break
Second Option:
def print_menu():
while True:
#Just use "while" here instead of the second one
go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
print_menu()
else:
print("We'll continue with your current choice")
You don't need to use a while True loop at all. It might cause problems with infinite looping. You can avoid it by calling a new function check_if_wants_to_order_again after a user has chosen his menu in print_menu().
def print_menu():
print('1. American')
print('2. Asian')
print('3. Indian')
print('4. Mexican')
print('5. French')
print('6. Italian')
print('7. Seafood')
print('8. Pizza')
menu = input('\nChoose where you want to eat from-->')
if menu == "1":
american_menu()
check_if_wants_to_order_again()
def american_menu():
print('1. Dempsey Burger Pub')
print('2. Redrock Canyon Grill-Wichita')
print("3. Cheddar's Scratch Kitchen")
print("4. Neighbors| Restaurant & Bar")
print("5. The Kitchen")
print("6. Firebirds Wood Fired Grill")
print("7. Chicken and Pickle")
american = input("\nChoose which American Restaurant--> ")
if american == "1":
print("\nCall Dempsey Burger Pub")
def check_if_wants_to_order_again():
go_back = input("Will you like to try another menu option? Enter \"Yes\" or \"No\":")
if go_back == "Yes":
print_menu()
else:
print("We'll continue with your current choice")
print_menu()
When you continue your loop, you're calling print_menu() again, but you aren't doing any of the other things that need to follow print_menu() in order to prompt the user to make another choice.
Give this a shot:
# Define the menus as dictionaries.
# The key is the number that the user will pick,
# the value is the selected item.
# Main menu -- pick a cuisine.
main_menu = {
"1": "American",
"2": "Asian",
"3": "Indian",
"4": "Mexican",
"5": "French",
"6": "Italian",
"7": "Seafood",
"8": "Pizza",
}
# American restaurant menu.
american_menu = {
"1": "Dempsey Burger Pub",
"2": "Redrock Canyon Grill-Wichita",
"3": "Cheddar's Scratch Kitchen",
"4": "Neighbors| Restaurant & Bar",
"5": "The Kitchen",
"6": "Firebirds Wood Fired Grill",
"7": "Chicken and Pickle",
}
# This dict maps each cuisine name to the appropriate submenu.
cuisine_menus = {
"American": american_menu,
# "Asian": asian_menu,
# "French": french_menu,
# ...
}
# This dict maps each restaurant name to its contact info.
contact_info = {
"Dempsey Burger Pub": (
"(316) 425-3831",
"https://www.dempseysburgerpub.com/"
),
"Redrock Canyon Grill-Wichita": (
"(316) 636-1844",
"https://www.redrockcanyongrill.com/"
),
# ...
}
def print_menu(menu):
"""Print a menu, e.g. '1. American'..."""
for k, v in menu.items():
print(f"{k}. {v}")
def contact_restaurant(restaurant):
"""Contact a restaurant. Raises KeyError if we don't have contact info."""
phone, website = contact_info[restaurant]
print(restaurant)
print(f"Phone: {phone}")
print(f"Website: {website}")
# maybe do something with website to open a browser? idk
# Interactive loop. Go through the menus in turn,
# and repeat when done or when they enter something invalid.
# Break the loop once they finish picking a restaurant.
while True:
# Main menu (pick a cuisine)
print_menu(main_menu)
pick = input('\nChoose where you want to eat from-->')
# Error checking for invalid picks.
if pick not in main_menu:
print("Please select one of the listed options.")
continue
cuisine = main_menu[pick]
if cuisine not in cuisine_menus:
# This happens if they picked something that was in main_menu
# but not in cuisine_menus yet because we haven't written that part.
print("Oops! Haven't implemented that one yet.")
print(f"Try {', '.join(cuisine_menus)}")
continue
# Now we have a valid main menu pick that we can continue with.
cuisine_menu = cuisine_menus[cuisine]
# Print the menu and ask them to pick an item from that.
print_menu(cuisine_menu)
pick = input(f"\nChoose which {cuisine} Restaurant--> ")
if pick not in cuisine_menu:
print("Sorry, not an option. Let's start over.")
continue
restaurant = cuisine_menu[pick]
if restaurant not in contact_info:
print(f"Oops, we don't have contact info for {restaurant}.")
print("Let's start over...")
continue
print(f"\nCall {restaurant}")
# Prompt them to start over. If they don't, break the loop.
pick = input("Will you like to try another menu option?: ")
if pick != "Yes":
print("We'll continue with your current choice")
break
# Now the user has picked a restaurant to contact,
# so go ahead and contact them.
contact_restaurant(restaurant)
Note that all of the interaction happens inside the while True loop. Any time there's a continue within that loop, it goes back to the print_menu(main_menu) at the start, and then continues from there.

Script not looping in python

I've being making a small escape room project and when you complete an action it's supposed to loop upon completion of certain actions it is supposed to loop but my code won't do that. Can someone help me fix it? This is my code. Link: (https://replit.com/#HoloGrain/Escape-Room-or-Bigger-Project#main.py)
inventory= []
HP=100
ImplacedAnemo= False
ImplacedGeo= False
ImplacedElectro= False
print("Type every word beggining with a capital letter")
def Help():
print("Commands:")
print("Pick Up (Item))")
print("Throw (Item) At (Other item)")
print("Press (Item)")
print("Hit (Item)")
print("Open (Place)")
print("Use (Item), (Command can only be used in battles)")
print("Use (Item) On (Item or Door(ex. Room 1 Door))")
print("Inventory", "(Opens inventory)")
print("Check HP", "(Checks HP)")
def start():
print("Welcome to HoloGrain's Escape room")
print("You are locked in Tenshukaku")
def Room1():
print("Paimon: Where are we")
print("You: I don't know")
print("Paimon: We should get out")
def Room1Command():
ChainsLocked = True
print("Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)")
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
for x in inventory:
if x == "Rock":
print("Action: Hey, don't even try")
Room1Command()
elif x == "Dull Blade":
print("Hey, don't even try")
Room1Command()
else:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
elif Room1Start == "Throw Rock At Glass Cage":
for x in inventory:
if x == "Rock":
print("Action: You succesfully threw the rock it shatters the cage and you get the dull blade (6 DMG) and can ")
inventory.remove('Rock')
inventory.append("Dull Blade")
else:
print("You don't have a Rock to throw")
elif Room1Start == "Use Dull Blade On Chains":
for x in inventory:
if x == "Dull Blade":
if ChainsLocked == True:
ChainLocked = False
inventory.append("Chains")
print("You have unlocked the chains (Can stop one attack from an enemy and restarts mega-skills cooldown (One-time use)) and taken them")
else:
print("Action: You've done this already")
elif Room1Start == "Check HP":
print(HP)
Room1Command()
elif Room1Start == "Check Inventory":
print(inventory)
Room1Command()
elif Room1Start == "Use Dull Blade On Door":
for x in inventory:
if x == "Dull Blade":
if ChainLocked == False:
print("You've opened the door")
else:
print("That doesn't work")
else:
print("Action: Undefined action in current state")
Room1Command()
Help()
start()
Room1()
Room1Command()
Fo
elif Room1Start == "Throw Rock At Glass
You don't have a "Room1Commande() at the end
So the first thing I see is that you're looping through an empty list - so that's not happening.
Perhaps you mean something like this:
def Room1Command():
ChainsLocked = True
print(
"Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)"
)
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
if len(inventory) == 0 or "Rock" not in inventory:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
else:
do_something_else()
There isn't any loop in your code. It just calls all the functions once, and it's over.
If you want the Room1Command to be always running, you can just easily add Room1Command() in the last line of Room1Command function. So it would look like this :
def Room1Command():
ChainsLocked = True
print("Room 1 Tools: Glass cage (contains sword), Paimon (If you get hungry and talks), Rock, Door (locked using a sword lock), Chains (Locked using sword lock)")
print("You're chained to the floor")
Room1Start = input("What do you want to do?: ")
if Room1Start == "Pick Up Rock":
for x in inventory:
if x == "Rock":
print("Action: Hey, don't even try")
Room1Command()
elif x == "Dull Blade":
print("Hey, don't even try")
Room1Command()
else:
inventory.append("Rock")
print("You have picked up a rock")
Room1Command()
elif Room1Start == "Throw Rock At Glass Cage":
for x in inventory:
if x == "Rock":
print("Action: You succesfully threw the rock it shatters the cage and you get the dull blade (6 DMG) and can ")
inventory.remove('Rock')
inventory.append("Dull Blade")
else:
print("You don't have a Rock to throw")
elif Room1Start == "Use Dull Blade On Chains":
for x in inventory:
if x == "Dull Blade":
if ChainsLocked == True:
ChainLocked = False
inventory.append("Chains")
print("You have unlocked the chains (Can stop one attack from an enemy and restarts mega-skills cooldown (One-time use)) and taken them")
else:
print("Action: You've done this already")
elif Room1Start == "Check HP":
print(HP)
Room1Command()
elif Room1Start == "Check Inventory":
print(inventory)
Room1Command()
elif Room1Start == "Use Dull Blade On Door":
for x in inventory:
if x == "Dull Blade":
if ChainLocked == False:
print("You've opened the door")
else:
print("That doesn't work")
else:
print("Action: Undefined action in current state")
Room1Command()
Room1Command()
By doing this, everytime the user enters a command and it gets processed, your code will be waiting for the next input. Which means there would be a loop on your Room1Command function. If I've understood your issue properly, I think this would work.
Also keep in mind that the list called Inventory is empty, so you can't iterate over it. You should put some values inside it first.

simple python text adventure game errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I got this sample rpg text adventure game online and im trying to understand the codes so that i can use it as a reference to develop my own text adventure game in the future. However, i am currently facing the error "gold is not defined at line 121 and i suspect is cause by indentation error. Although this is the error im facing so far, i believed that are more mistakes in the codes which i am glad for anyone to point it out.Thanks!
# gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
While True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
From a quick glance at it. #gold = int(100) is commented out on line 1.
This causes a issue because it doesn't know what gold is. it isn't defined. remove the # before it.

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

Skipping iteration if condition not met

Currently messing around with a fantasy football program, The user is asked to first input 10 player names which are added to a list, then input values for each individual player for different variables like goals scored, goal assists etc. The first question is "did they play the match?"
If the answer is no then I am trying to skip the following questions and jump to the next player, I have been trying to use continue but it just loops and continues asking the first question to the first player.
playerList=[]
def Playeradd():
playerList.append(item)
def Playercreate():
global item
item = raw_input("Enter Player name: ")
Playeradd()
[Playercreate()for _ in range (5)]
print
print "You have selected", len(playerList), "players for your squad, Your selected squad is.."
#print playerList
for item in playerList:
print item
player =Playercreate
scorecheck=[]
x=0
totalscore=0
def pointsaward():
global scorecheck, totalscore
y=1
player=y
x=0
while x < 5:
print
print "Please enter score for ", playerList[x]
print
play = raw_input(" Did he play the match (yes or no?) ")
if play == "yes":
play1=2
else:
play1=0
goalS= int(raw_input(" Did he score, if so how many?"))
goalS=goalS*5
goalA= int(raw_input(" How many assists?"))
goalA=goalA*3
motm= raw_input(" Did he win man of the match (yes or no?) ")
if motm == "yes":
motm1=5
else:
motm1=0
yelC=raw_input(" Did he recieve a yellow card (yes or no?) ")
if yelC == "yes":
yelC1= -1
else:
yelC1=0
redC=raw_input(" Did he recieve a red card (yes or no?) ")
if redC == "yes":
redC1= -5
else:
redC1=0
PenM=raw_input(" Did he miss a peno(yes or no?) ")
if PenM == "yes":
PenM1= -3
else:
PenM1=0
playerpoint1= play1+goalS+goalA+yelC1+redC1+PenM1
PlayerandScore= [playerList[x],playerpoint1,]
scorecheck.append(PlayerandScore)
totalscore+= playerpoint1
# print "This player has scored a total of ", PlayerandScore, " this week "
x+= 1
y+= 1
print "This player has scored a total of ", PlayerandScore, " this week "
print
pointsaward()
Sorry if it was unclear,So for Player 1 If the answer to the first question is no then there is no need to ask the following questions about the player as he would not have played. So I want it to skip the following questions and start asking the input for Player 2 in the list.
I think you should put the question inside a function. This will allow you to call the function when ever you want.
and make it easier to decide when to ask the question.
Because you have raw_input I am assuming you are using python 2.X
you can add python2 or python3 to your tags to get better help from people know more about each version of python.
list_of_players = ["player 1","player 2","player 3"]
def check_player(yes_no):
if yes_no == "yes":
play1=2
goalS= int(raw_input(" Did he score, if so how many?"))
goalS=goalS*5
goalA= int(raw_input(" How many assists?"))
goalA=goalA*3
motm= raw_input(" Did he win man of the match (yes or no?) ")
if motm == "yes":
motm1=5
else:
motm1=0
yelC=raw_input(" Did he recieve a yellow card (yes or no?) ")
if yelC == "yes":
yelC1= -1
else:
yelC1=0
redC=raw_input(" Did he recieve a red card (yes or no?) ")
if redC == "yes":
redC1= -5
else:
redC1=0
PenM=raw_input(" Did he miss a peno(yes or no?) ")
if PenM == "yes":
PenM1= -3
else:
PenM1=0
else:
play1=0
return "no"
print "player did not play"
# this for statement will ask about each player in the list of players.
for player in list_of_players:
print "Did "+player+" play in the game?"
print check_player(raw_input("yes or no --->"))
here is an image of the console if you run my code.
EDIT: Ok here is your code fixed up to check each new player after you enter their info or say "no".
playerList=[]
def Playeradd():
playerList.append(item)
def Playercreate():
global item
item = raw_input("Enter Player name: ")
Playeradd()
[Playercreate()for _ in range (5)]
print "You have selected", len(playerList), "players for your squad, Your selected squad is.."
for item in playerList:
print item
player =Playercreate
scorecheck=[]
x=0
totalscore=0
def pointsaward():
global scorecheck, totalscore
y=1
player=y
x=0
while x < 5:
print "Please enter score for ", playerList[x]
for player in playerList:
print "Did "+player+" play in the game?"
play = raw_input(" Did he play the match (yes or no?) ")
if play == "yes":
play1=2
goalS= int(raw_input(" Did he score, if so how many?"))
goalS=goalS*5
goalA= int(raw_input(" How many assists?"))
goalA=goalA*3
motm= raw_input(" Did he win man of the match (yes or no?) ")
if motm == "yes":
motm1=5
else:
motm1=0
yelC=raw_input(" Did he recieve a yellow card (yes or no?) ")
if yelC == "yes":
yelC1= -1
else:
yelC1=0
redC=raw_input(" Did he recieve a red card (yes or no?) ")
if redC == "yes":
redC1= -5
else:
redC1=0
PenM=raw_input(" Did he miss a peno(yes or no?) ")
if PenM == "yes":
PenM1= -3
else:
PenM1=0
else:
play1=0
print player+" did not play"
playerpoint1= play1+goalS+goalA+yelC1+redC1+PenM1
PlayerandScore= [playerList[x],playerpoint1,]
scorecheck.append(PlayerandScore)
totalscore+= playerpoint1
x+= 1
y+= 1
print "This player has scored a total of ", PlayerandScore, " this week "
pointsaward()
As far as I can tell from your question you just need to continue as normal, naturally ending the if statement
play = input(" Did he play the match (yes or no?) ")
if play == "yes":
play1=2
else:
play1=0
print("Continue Here")

Categories