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.
Related
This is a multi-choice quiz for kids where they input their age and the algorithm determines what quiz they do (A or B). People less than 8 will do Quiz A but people less than 5 will get a warning message that they are too young to play but can play if they want to. People older than 8 do Quiz B but people who are older than 11 get a warning message stating that they are too old to play but can play if they want to. Note: I don't really care about the repeats/play again right now just want a way to simplify the base structure of the code without using complicated stuff and classes. Thanks for reading!
questions = ["What is 1 + 1",
"Who is the 45th president of the United States?",
"True or False... The Toronto Maple Leafs have won 13 Stanley Cups?",
"What was the last year the Toronto Maple Leafs won the Stanley Cup?",
"True or False... The current Prime Minister of Canada is Pierre Elliot Tredeau?"]
answer_choices = ["a)1\nb)2\nc)3\nd)4\n:",
"a)Barack Obama\nb)Hillary Clinton\nc)Donald Trump\nd)Tom Brady\n:",
":",
"a)1967\nb)1955\nc)1987\nd)1994\n:",
":"]
correct_choices = [{"b", "2"},
{"c", "donald trump"},
{"true", "t"},
{"a", "1967"},
{"false", "f"}]
answers = ["1 + 1 is 2",
"The 45th president is Donald Trump",
"",
"The last time the Toronto Maple Leafs won the Stanley Cup was 1967",
"The current Prime Minster of Canada is Justin Tredeau"]
questions_b = ["Who painted the Mona Lisa",
"Which planet is closest to the sun?",
"How many valves does the heart have?",
"What nut is in the middle of a Ferrero Rocher?",
"How many minutes in a game of rugby league?"]
answer_choices_b = ["a)Vincent Van Gogh\nb)Leonardo da Vinci\nc)Michelangelo\nd)Pablo Picasso\n:",
"a)Mercury\nb)Venus\nc)Mars\nd)Neptune\n:",
"a)Three\nb)One\nc)Five\nd)Four\n:",
"a)Walnut\nb)Hazelnut\nc)Almond\nd)Macadamias\n:",
"a)80 minutes\nb)60 minutes\nc)40 minutes\nd)20 minutes\n:"]
correct_choices_b = [{"b", "Leonardo da Vinci"},
{"a", "Mercury"},
{"d", "Four"},
{"b", "Hazelnut"},
{"a", "80 minutes"}]
answers_b = ["Leonardo da Vinci painted the Mona Lisa",
"Mercury is the planet closest to the sun",
"The heart has four valves",
"A hazelnut is in the middle of a Ferrero Rocher",
"There are 80 minutes in a game of rugby league"]
run = "y"
def quiz_a():
score = 0
for question, choices, correct_choice, answer in zip(questions, answer_choices, correct_choices, answers):
print(question)
user_answer = input(choices).lower()
if user_answer in correct_choice:
print("Correct")
score += 1
else:
print("Incorrect", answer)
print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%")
def quiz_b():
score = 0
for question, choices, correct_choice, answer in zip(questions_b, answer_choices_b, correct_choices_b, answers_b):
print(question)
user_answer = input(choices).lower()
if user_answer in correct_choice:
print("Correct")
score += 1
else:
print("Incorrect", answer)
print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%")
#start of program
#Quiz B is people age 8 to 11
#Quiz A is people less than 8
age = int(input("How old are you?: "))
while run == "y":
if age <= 5:
leave = input("You are too young. Do you still want to play? y/n: ")
if leave == "n":
print("Goodbye")
break
elif leave == "y":
print("Starting now. You will be doing Quiz A")
quiz_a()
else:
break
elif age > 11:
leave = input("You are too old. Do you still want to play? y/n: ")
if leave == "n":
print("Goodbye")
break
elif leave == "y":
print("Starting now. You will be doing Quiz B")
quiz_b()
play_again = input("Do you want to do the other quiz? y/n: ")
if play_again.lower() == "y":
print("Okay starting Quiz A")
quiz_a()
print("Thanks for playing! Goodbye")
break
else:
print("Goodbye")
break
else:
break
elif age <= 5 and age < 8:
print("Starting now. You will be doing Quiz A")
quiz_a()
else:
if age <= 8:
print("Starting now. You will be doing Quiz B")
quiz_b()
You can easily solve this using OOP. As you could see you can have Quiz class which represent a Quiz question, and to hold all questions you can create list of Quiz objects.
class Quiz(object):
"""docstring for Quiz."""
def __init__(self, question, options, answer):
super(Quiz, self).__init__()
self.question = question
self.options = options;
self.answer = answer
def show(self):
print(self.question, self.options, self.answer)
q = Quiz("this is question", ["apple", "banana", "cherry"], 1)
q.show()
I am writing a program (for no specific purpose), where I take orders from users, which run the program. At some point, I ask them if they are happy with their decision. They have the option to "say" Yes or No. If their answer is no, I need the program to loop back to a specific point in the code. How can I do that?
Here's the code:
import datetime
import calendar
import time
import colorsys
import math
# Definitions
date = time.strftime("%A")
MenuItems = {0:["Beef steak (0.5 kg) with french fries or basmati rice and mushroom sauce.","Patata con pollo (potato slices with chicken and cooked cream) with cooked vegetables.","Moussaka with green beans, carrots and broccoli \033[92m(vegeterian)\033[37m."],
1:["Beef stroganoff with noodles.","Risotto with pork meat and cooked vegatables.","Gratinated cottage cheese pancakes \033[92m(vegeterian)\033[37m."],
2:["Spaghetti carbonara.","Noodle soup with cut up parsley.","Gnocchi with tomato sauce and sauteed vegetables \033[92m(vegeterian)\033[37m."],
3:["Fried hake with cooked potatoes.","Pizza Palermo (tomato sauce, cheese, ham, pancetta and mushrooms.","Pizza Margherita (tomato sauce, cheese, olives) \033[92m(vegeterian)\033[37m."],
4:["Warm salad with octopus.","Chicken filet with paears in spicy sauce.","Gratinated cheese tortellini with spinach, sour cream and an egg \033[92m(vegeterian)\033[37m."],
5:["Black angus burger with cheddar.","Macaroni with beef filet and tomatoes.","Spaghetti with vegetable sauce \033[92m(vegeterian)\033[37m."]}
DrinkItems = {0:["Soft beverages","Carbonated beverages","Alcoholic beverages","Hot beverages"],
1:["Cedevita (0,5l)","Ice Tea (0,5l)","Water (0,5l) \033[92m(FREE)\033[37m","Apple juice (0,25l)","Orange juice (0,25l)","Strawberry juice (0,25l)","Peach juice (0,25l)","Lemonade (0,5l)","Water with taste (0,5l)"],
2:["Coca Cola (0,25l)","Coca Cola Zero (0,25l)","Coca Cola Zero Lemon (0,25l)","Cockta (0,25l)","Fanta (0,25l)","Schweppes Bitter Lemon (0,25l)","Schweppes Tonic Water (0,25l)","Schweppes Tangerine (0,25l)","Radenska (0,25l)","Sprite (0,25l)","Red Bull (0,25l)"],
3:["Laško beer (0,33l)","Union beer (0,33l)","Malt (0,33l)","Non-alcoholic beer (0,33l)","Corona Extra (0,33l)","Guiness Extra Stout (0,33l)","Sparkling wine (0,10l)","White wine (0,10l)","Red wine (0,10l)","Blueberry Schnapps (0,03l)","Grappa (0,03l)","Stock (0,3l)","Jägermeister (0,03l)","Liquer (0,03l)","Rum (0,03l)","Tequila (0,03l)","Vodka (0,03l)","Gin (0,03l)","Whiskey (0,03l)","Cognac (0,03l)"],
4:["Coffee","Coffee with milk","Cocoa","Hot Chocolate","Irish Coffee","Tea (green, black, herbal, chamomile)"]}
MenuPrices= {0:[6.00, 4.50, 4.50],
1:[5.00, 4.50, 4.00],
2:[5.00, 4.00, 4.50],
3:[4.50, 4.50, 4.50],
4:[4.50, 5.00, 4.00],
5:[5.00, 5.00, 4.00]}
# Introduction of the Bartender
print ("Hello! Welcome to the e-Canteen!")
print ("")
time.sleep(1)
print ("Today is \033[1m" + (date) + "\033[0m.")
time.sleep(1)
# Menus available for current day
todayWeekday = datetime.datetime.today().weekday()
if todayWeekday < 6:
print ("We are serving:")
for x in MenuItems[todayWeekday]:
print(str(MenuItems[todayWeekday].index(x)+1)+".", x)
time.sleep(0.5)
# Canteen is closed on Sunday
else:
print ("Sorry, we're closed.")
exit()
# Ordering the menus
print ("")
time.sleep(1)
menu = int(input("Please choose a menu item by typing in a number from 1 to 3: "))-1
print ("")
if menu < int(3):
print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Person chooses higher menu item than 3
else:
print("Sorry, we do not have more than 3 menu items per day. Please choose a menu item from 1 to 3.")
time.sleep (1)
while menu >= 3:
menu = int(input("Please choose a menu by typing in a number from 1 to 3: "))-1
# Person chooses a menu item from 1 to 3
if menu < 3:
print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Any additional orders
# Choosing beverage category
print ("------------------------------------------------------------")
print ("")
time.sleep(2)
category = DrinkItems[0]
print("Please choose a type of beverage you would like to order:")
time.sleep(1)
for x in DrinkItems[0]:
print(str(DrinkItems[0].index(x)+1)+".", x)
print("")
time.sleep(0.5)
# Choosing beverage
category = int(input("Enter your number here: "))
print("")
print("You chose \033[1m" +DrinkItems[0][category-1] +"\033[0m. Here is a list:")
for x in DrinkItems[category]:
print(str(DrinkItems[category].index(x)+1)+".", x)
print("")
time.sleep(0.5)
drink = int(input("Please choose a beverage by entering the number in front of your desired beverage: "))-1
# User deciding if she/he is happy with her/his decision
decision = input("\nYou chose " +DrinkItems[category][drink] +". Are you happy with your decision? ").lower()
if decision == 'yes':
additional = input("Great! Would you like to order anything else? ").lower()
if additional == "yes":
what = input("What else would you like to order (menu, drink or both)? ").lower()
if what == "menu":
print("I understand. The program will return you to the menus.")
elif what == "drink":
print("I understand. The program will return you to the drinks.")
elif what == "both":
print("I understand. The program will return you back to the menus (no orders until now will be lost).")
elif additional == "no":
print("Awesome! The program will now summ up your price. Please wait a moment...")
time.sleep(2)
elif decision == "no":
change = input("I'm sorry to hear that. What else would you like to change (menu, drink or both)? ").lower()
if change == "menu":
print("I understand. The program will return you to the menus.")
elif change == "drink":
print("I understand. The program will return you to the drinks.")
elif change == "both":
print("I understand. The program will return you back to the menus.")
# Any additional beverages
# Billing
print(sum(DrinkItems[category][drink]))
# End
I am new relatively new to the coding scene.
Thank you in advance for any answers.
You can wrap your code inside a while loop:
while True:
// your code
// at some point in the code:
happiness = input("Are you happy?")
if happiness == "yes":
break
To go to a specific point in the code, you will have to use this pattern (or something similar) several times.
You can use break statement to stop the(infinite)loop while continue is used to skip something that is what you're looking for here.
So, your code needs to be like this
# User deciding if she/he is happy with her/his decision
while True:
decision = input("\nYou chose "+". Are you happy with your decision? ").lower()
if decision == 'yes':
additional = input("Great! Would you like to order anything else? ").lower()
if additional == "yes":
what = input("What else would you like to order (menu, drink or both)? ").lower()
if what == "menu":
print("I understand. The program will return you to the menus.")
elif what == "drink":
print("I understand. The program will return you to the drinks.")
elif what == "both":
print("I understand. The program will return you back to the menus (no orders until now will be lost).")
break
elif additional == "no":
print("Awesome! The program will now summ up your price. Please wait a moment...")
time.sleep(2)
break
elif decision == "no":
continue
Im new to coding, and pretty confused by the concept of class 's and how to use them. Im making a zork game as a practice exercise and have the following as part of my code:
def buildCharacter():
return(Hero(input("What is your name, traveler? \n> ")))
class Hero(object): #creates class Hero, Hero has-a name and has-a health
def __init__(self, name, health=10):
self.name = name
self.health = health
Later in the code, if the player gets 'hurt' I want to be able to reduce health, until its 0 and they 'die'.
I tried doing:
self.health -= 5
if self.health <=0:
exit(0)
but that doesn't work, saying 'self' not defined. How do I call on self.health to change it?
Edit: Ive been told that the whole code should be posted, so here it is:
from sys import exit
import time #Lets you pause the command window for a sec
have_sword = False
gate_unlocked = False
class Hero(object): #creates class Hero, Hero has-a name and has-a health
def __init__(self, name, health=10):
self.name = name
self.health = health
def take_dammage(self, dammage):
self.health -= dammage
def getHealth(self):
return self.health
#first room: sphynx with riddle, door with password
def sphynx():
print("You enter a room with a sphynx and a door.")
while True: #create infinite loop to begin again if password unknown
print("What do you do?")
choice = input("\n1) Fight the sphynx \n2) Speak to the sphynx \n3) try the door \n>")
if "attack" in choice or "fight" in choice or "1" in choice:
MyName.health -= 5
print(f"You can't beat a sphynx unarmed! \nHealth is now {MyName.health}")
if MyName.health <= 0:
dead()
elif "speak" in choice or "talk" in choice or "ask" in choice or "question" in choice or "2" in choice:
print("""The sphynx is board, instead of telling you the password easily, it asks you a riddle:
'First think of the person who lives in disguise,
who deals in secrets and tells only lies.
Next, tell me what's always the last thing to mend,
the middle of middle and the end of end?
Fianally, give me a sound often heard
durring the search for a hard to find word.
Now string them together, and answer me this,
what creature would you be unwilling to kiss?'
OK, but how is that going to help you??
"""); time.sleep(1)
elif "door" in choice or "open" in choice or "try" in choice or "3" in choice:
print("What's the password?")
password = input("> ")
if password == "spider":
print("Correct! You go through the open door")
room2()
else: #starts while loop ovewr again
print("Nope. \nTry again. \nMaybe the sphynx knows...")
continue
else: #starts while loop ovewr again
print("naw mate, try again")
def room2():
print("You enter a room with a red door and a blue door.")
global have_sword
while True: #create infinite loop to begin again if door not chosen
choice = input("Which do you enter?\n>")
if "red" in choice:
print("You enter a pitch black room. What do you do?")
darkChoice = input("\n1) Feel for a light swith \n2) Turn around and leave \n3) \"the dark doesn's scare me, I venture forward into the gloom\" \n> ")
while True: #create infinite loop to begin again if no option chosen
if "feel" in darkChoice or "light" in darkChoice or "1" in darkChoice:
print("You find a light switch and turn it on. \nIn the room, you see a small box and a large one.")
while True: #create infinite loop to begin again if no option chosen
print("Which box do you open?")
boxChoice = input("> ")
if "small" in boxChoice or "little" in boxChoice:
print("you open the small box to find a wormhole. \nIt sucks you in and you find yourself BACK in the second room.")
room2()
elif "big" in boxChoice or "large" in boxChoice:
print("You find a sword. \nStow it for later use. \nFor now, go back to the second room")
have_sword = True
room2()
else: #starts while loop over again
print("You gotta pick one.")
else:
dead("you get lost in the darkness and starve.")
elif "b" in choice:
oldShack()
else: #starts while loop ovewr again
print("naw mate, try again")
def oldShack():
print("You enter and old, rickety shack. \nThe paint is peeling, the floorboards sticking up, and ceiling caving in. \nThere's a rusty gate at the back.")
global gate_unlocked
while True: #create infinite loop to begin again if no option chosen
print("What do you do in the shack? ")
choice = input("1) Search under the floorboards \n2) Try the gate \n3) Go back \n> ")
if "check" in choice or "floor" in choice or "board" in choice or "1" in choice:
print("You find a key under the floorboards!")
gate_unlocked = True
elif "door" in choice or "gate" in choice or "2" in choice and gate_unlocked == True:
print("You use the key you found, it works!")
cave()
elif "Push really hard" in choice:
print("Damn, you're really strong!")
cave()
elif "door" in choice or "gate" in choice or "2" in choice and gate_unlocked != True:
print("the gate is locked.")
elif "3" in choice or "back" in choice:
room2()
else:
print("naw mate, try again")
def cave():
print("You find yourself in a cave that is home to a collosal, sleeping red dragon. ")
global have_sword
while True:
choice = input("How do you deal with the dragon? \n1) Attack with your sword \n2) Attack unarmed \n3) Speak to the dragon \n4) Run before the dragon wakes \n>")
if "1" in choice and have_sword == True:
print("A mighty battle ensures. \n Using your sword, you slay the dragon \nBefore you stands a great pile of generations of dragon treasure; gold and juels and riches beyond your wildest dreams. \nAt the end of the cave lies a small brown chest. \nDo you: \n1) Take the treasure \n2) Open the box")
rich = input("> ")
while True:
if "1" in rich or "gold" in rich:
dead("A deep voice echos from the depths of the cave: \n'Greed is the downfall of man.' \nThe cave rumbles and collaples around you.")
elif "2" in rich or "box" in rich or "brown" in rich:
print("You open the box to find the deep crimson Dream Stone. \nYou have succesded in your quest, 1) this could save King Arthurs kingdom from *vague, unspecified threat* \nOr... \n2) Or you could sell if and buy a kingdom of you very own!")
success = input("> ")
if "1" in success:
win("You successfully passed all the chalanges!\n")
else:
dead("You walk out of the cave, daydreaming about what life will be like as a king \nWhile you are distracted by your thoughts, you trip over the dead dragons tail and hit your head")
else:
print("Naw mate, try again")
elif ("1" in choice or "sword" in choice) and have_sword != True:
dead("What sword? The dragon eats your face.")
elif "2" in choice and have_sword == True:
dead("Use the damn sword next time...")
elif "2" in choice:
dead("Mate, you think you can take a dragon unarmed and alone?")
elif "3" in choice:
dead("Shoulda invested in some lessons in dragon language;")
elif "4" in choice:
oldShack()
else:
print("naw mate, try again")
def dead(why):
print(why, "you died. well done...")
print(open("DEAD.txt").read()); time.sleep(2) #prints the text of DEAD.txt as an outro to the game
exit(0)
def win(how):
print(how, "You return triumphant to Kind Arthur. \nThe Kingdom shall live in peace another day.")
print(open("WIN.txt").read()); time.sleep(2) #prints the text of WIN.txt as an outro to the game
exit(0)
#intro story, do you accept quest? yes -> sphynx room, no-> are u sure?
def start():
print(open("README.txt").read()); time.sleep(2) #prints the text of README.txt as an into to the game
character = buildCharacter() #goes to the buildCharacter funtion, and assigns the results the name character
print(f"You are {character.name}, a night of King Arther's round table. \nYou have been tasked with finding the Dream Stone \nThe search has clamined many lives. \nYou have 10 health points.")
time.sleep(1/2)
choice = input("\nDo you accept?\n> ")
if "y" in choice:
sphynx()
elif "n" in choice:
print("are you sure?")
sure = input("> ")
if "y" in sure:
print("well that was boring.")
print(open("DEAD.txt").read()); time.sleep(2)
elif "n" in sure:
print("good")
sphynx()
else:
print("Mate, its a yes or no question; are you sure")
elif "Cheet code" in choice:
win("You don't deserve this, but fair is fair. \n")
else:
start("Only you can decide. Now decide.")
def buildCharacter(): #goes to the class Hero (line 8), and creates the hero.name given by the user
MyName = input("What is your name, traveler? \n> ")
return(Hero(MyName, 10)) #takes input and uses that as the object for class Hero
print(Hero())
start()
Define a method in your class named hurt and a getter for health, like this :
class Hero(object): #creates class Hero, Hero has-a name and has-a health
def __init__(self, name, health=10):
self.name = name
self.health = health
def hurt(self,damage):
self.health-= damage
def get_health(self):
return self.health
Then later in the code you can call these methods like this :
hero = Hero("mohsen")
hero.hurt(5)
if hero.get_health()<=0:
exit(0)
I believe this example gets at the question you asked.
class Hero:
def __init__(self):
self.health = 100
Jon = Hero()
Jon.health -= 20
print(Jon.health)
The print statement outputs: 80
What you tried would work in another method within your class Hero:
class Hero(object):
def __init__(self, name, health=10):
self.name = name
self.health = health
self.alive = True
def take_damage(self):
self.health -= 5
if self.health <= 0:
self.alive = False
def is_alive(self):
return self.alive == True
If you are trying to reduce the health of an object of type Hero, you need to do it via the object reference like this:
my_hero = Hero()
my_hero.take_damage()
print(my_hero.is_alive())
Or you can access self.health directly (but better to do it via a method like I showed above):
my_hero = Hero()
my_hero.health -= 5
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")
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")