Python text RPG error [closed] - python

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 7 years ago.
Improve this question
I'm making a textual RPG, and I'm running into a problem. So in the code below, mobHP is a global variable, which is equal to 20000. This is only a part of the code. So what's happening is that once the attack takes place, the new HP of the monster is shown, but then by the second attack, the HP again becomes 20000 and then the damage is subtracted, and again another value is shown, it isin't subtracting from the new value itself. battlem() is the battle menu from where you can attack, use potions and run. win() is a def function to what to show when the user wins.
For example if a player hits the monster by 1000, then the currentHP will show as 19000, but then when I attack again, say hit by 1400, instead of 19000-1400, it subtracts from the original value, and becomes 18600.
Help would really be appreciated
def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -= damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
death()
elif mobHP <= 0:
win()
else:
battlem()
currentHP=mobHP;
while(currentHP>0):
battlem()
However, this doesn't work as the output is
You swing your sword at the enemy!
Inflicted damage: 95 enemy HP: -95
This was a solution that was given, but then removed, and when I further asked for a solution nobody replied again.
FULL CODE:
import random
import time
global playerHP
global inventory
global mobHP
global mobSpeed
global mob
global boss
global level
global strength
global speed
global potions
global exp
global mithril
playerHP= 28000
level = 74
strength = 80
speed = 120
potions = 3
exp = 0
mithril = 10000
mobHP = 20000
mobstrength = 120
mobSpeed = 180
inventory = []
def prompt():
command = input("What action will you perfrom?")
return command
def death():
if playerHP== 0:
print("Your HP has been depleted completely")
input()
print("You are now dead")
input()
print("You will be respawned at the Misgauka")
input()
townone()
def townoned():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
print("You are now at the Inn, what do you wish to do?")
input()
print("""You can do the following:
Rest
""")
command = prompt()
if command == "Rest":
rest()
if command == "Store":
print("You make your way to the store")
input()
print("Welcome to Tonajta's Weapon and Supplies shop")
input()
print("""You can do the following:
Display Catalogue
Exit store
""")
command = prompt()
if command == "Display" or "display":
print("Open the Weapons Catalogue or the Supplies catalogue")
input()
command = prompt()
if command == "Weapons":
wepmenu()
if command == "Supplies":
supplymenu()
elif command == "Exit":
print("Thanks for coming")
input()
print("Please do visit again")
input
townone()
def Grasslands():
print(" You have already cleared the Grasslands")
input()
print("You may go there to gain more experience")
input()
print("Y/N")
input()
command = prompt()
if command == "Y" or "y":
print("You proceed to the grasslands")
input()
elif command == "N" or "n":
townoned()
else:
print("You seem to be pressing the wrong command")
Grasslands()
def win():
print("You have managed to slain the enemy")
input()
print("You now must dwell further within the greenlands")
input()
def battles():
print("A wild boar appears in front of you")
input()
print("What do you choose to do?")
input()
print("Fight or Run?")
input()
command = prompt()
if command == "Fight" or "fight":
print("Good work senpai")
input()
battlem()
elif command == "Run" or "run":
print("You turn to run")
time.sleep(1)
print("The pathway behind you is now blocked")
input()
print("Thus, you must fight")
battlem()
else:
battles()
def boss_battle():
print("Let's fight")
input()
command = prompt()
if command == "Fight" or "fight":
print("You unsheath your sword")
input()
boss_battle_m()
else:
print("You can't run away from this")
input()
boss_battle_m()
def boss_battle_m():
print("""
1. Attack
2. Potions
""")
command = prompt()
if command == "1":
boss_battle_s()
if command == "2":
if potions > 0:
print("You take a potion bottle")
input()
print("..........")
input()
pHP = playerHP +200
print("Your HP has been refilled to",pHP)
pHP = playerHP
else:
print("You have no potions left!")
input()
boss_battle_s()
def boss_battle_s():
bossdamage = random.randint(80, 220)
bossHP = 4000
bossHP = bossHP - bossdamage
print("Boss HP is now:", bossHP)
input()
if bossHP <= 0:
win()
elif playerHP <= 0:
death()
else:
boss_battle_m()
def battlem():
print("""
1. Attack 3. Run
2. Use potion
""")
command = prompt()
if command == "1":
Attack()
elif command == "2":
Potiondesu()
elif command == "3":
Run()
else:
battlem()
#CURRENT DAMAGE BY THE CURRENT HEALTH
def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -= damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
death()
elif mobHP <= 0:
win()
else:
battlem()
currentHP=mobHP;
while(currentHP>0):
battlem()
def wepmenu():
print("""
1. Glorion Blades - 200 Mithril
2. Light Sword - 120 Mithril
3. Rapier - 200 Mithril
4. Dagger - 100 Mithril
Supplies Catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
print("The Glorion Blades cost 200 mithril")
input()
if mithril>=200:
print("You buy the blades")
input()
wepmenu()
elif mithril<200:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "2":
print("The light sword costs 120 mithril")
input()
if mithril>=150:
print("You buy the sword")
input()
wepmenu()
elif mithril<150:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "3":
print("The Rapier costs 200 mithril")
input()
if mithril>=200:
print("You buy the Rapier")
input()
wepmenu()
elif mithril<200:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
if command == "4":
print("The Dagger costs 100 mithril")
input()
if mithril>=100:
print("You buy the blades")
input()
wepmenu()
elif mithril<100:
print("You cannot afford this weapon")
input()
print("Choose another weapon")
wepmenu()
print("Gotta implement weapon stats")
if command == "Supplies" or "supplies":
supplymenu()
elif command == "Exit":
townone()
def supplymenu():
print("""
1. HP potion - 20 Mithril
2. Large HP Potion - 40 Mithril
Weapons catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
print("The HP Potion costs 20 mithril")
input()
if mithril>=20:
print("You have brought the potion")
input()
supplymenu()
elif mithril<20:
print("You cannot afford this potion")
input()
print("Choose another supply")
input()
supplymenu()
elif command == "2":
print("The Large HP potion costs 40 mithril")
input()
if mithril>=40:
print("You have brought the large potion")
input()
supplymenu()
elif mithril<40:
print("You cannot afford this potion")
input()
print("Choose another supply")
supplymenu()
elif command == "Weapons":
wepmenu()
elif command == "Exit":
townone()
def rest_inn():
print("It will cost 20 mithril to rest at this inn for tonight")
input()
if mithril>=20:
print("You check in")
elif mithril<20:
print("You can't afford to rest here")
input()
print("Kill some monsters for some mithril")
input()
print("You exit the inn")
input()
townone()
print("Your HP has been reset to",HP,"HP")
input()
print("Please press enter to exit the inn")
input()
townone()
def townone():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
print("You are now at the Inn, what do you wish to do?")
input()
print("""You can do the following:
Rest
""")
command = prompt()
if command == "Rest":
rest()
if command == "Store":
print("You make your way to the store")
input()
print("Welcome to Tonajta's Weapon and Supplies shop")
input()
print("""You can do the following:
Display Catalogue
Exit store
""")
command = prompt()
if command == "Display" or "display":
print("Open the Weapons Catalogue or the Supplies catalogue")
input()
command = prompt()
if command == "Weapons":
wepmenu()
if command == "Supplies":
supplymenu()
elif command == "Exit":
print("Thanks for coming")
input()
print("Please do visit again")
input
townone()
if command == "Grasslands":
print("All of us have to go into the different pathways I guess")
input()
print("Three paths to each")
input()
print("Alright then, I'll take north, east and then the north pathway")
input()
print("Let's meet back here and gather intel")
input()
print("You make your way to the Grasslands")
input()
print("The pathway goes NORTH")
battles()
print("You will now proceed to the next part of the grasslands")
input()
print(".............")
input()
print("The ground rumbles.....")
input()
print("Another steel-plated guardian appears")
input()
battles()
print("The path is finally clear")
input()
print("You proceed towards the EAST pathway")
input()
print("An approximate of two monsters will spawn here")
input()
print("WHOOSH")
input()
print("A rogue warrior emerges from within the huge bushes")
input()
battles()
print("You run forward")
input()
print("Two more rogue warriors run towards you")
input()
battles()
print("Now remains the last stage of the deadly grasslands")
input()
print("You make the turn")
input()
print("You see the other end of the Grasslands")
input()
print("There is a chair at a high position")
input()
print("Two figures seem to be running towards you")
input()
print("Prepare for combat")
battles()
input()
battles()
input()
print("You seem to have beat the two orcs")
input()
print("Well, seems like it's time")
input()
print("IT's ONE OF THE HACKERS")
input()
print("Fight me, and I take this mask off")
input()
boss_battle()
print("Ahhhhhhhhhhhhhhhhhh")
input()
print("This can't be happening")
input()
print("Now that we're done here..")
input()
print("Show me your face!")
input()
print("Pfff..")
input()
print("TAKES MASK OFF")
input()
print("Oh, so it's you Chaps")
input()
print("You know you won't win right")
input()
print("Even though you defeated me, you can't get past shad....")
input()
print("Who?")
input()
print("NOTHING, now as promised, I'll give you the location of the next town")
input()
print("Where can I find the others in your pathetic group")
input()
print("Huh, you have a big mouth don't you")
input()
print("hehehehehhehhe......")
input()
print("HAHHAHAHHAHAHAHHAHA")
input()
print("A flash of blue light and the player vanishes.........")
input()
print("Well, he's done for")
input()
print("TING TING TING")
input()
print("Huh, what's th..........")
input()
print('{:^80}'.format("SERVER ANNOUNCEMENT"))
time.sleep(2)
print('{:^80}'.format("TOWN OF REPLAUD NOW AVAILABLE TO ALL PLAYERS"))
time.sleep(2)
print('{:^80}'.format("TO REACH, PLEASE CLEAR DUNGEON"))
time.sleep(2)
input()
elif command == "Dungeon":
print("The dungeon cannot be accessed yet")
input()
print("To unlcok the dungeon, you must clear the grasslands")
input()
else:
print("You seem to have entered a wrong command")
input()
print("""Please enter either of these:
1. Inn
2. Store
3. Greenlands
4. Dungeon
""")
townone()
townone()

It's not clear what's causing the error from the code you posted, but from the behavior you describe it sounds like you're not defining mobHP as a global. Here's some example code.
mobHP = 20000
playerHP = 30000
def check_hps():
if mobHP <= 0:
win()
if playerHP <= 0:
lose()
def broken_attack():
attack_value = 100 # how hard you hit
mobHP -= attack_value
check_hps()
def fixed_attack():
global mobHP
attack_value = 100
mobHP -= attack_value
check_hps()
To demonstrate:
>>> mobHP
20000
>>> broken_attack()
>>> mobHP
20000
>>> fixed_attack()
>>> mobHP
19900
>>> fixed_attack()
>>> mobHP
19800
This code is, of course, really difficult to maintain. It is, however, pretty easy to implement. Contrast with:
class Actor(object):
def __init__(self, name, maxHP, min_dmg, max_dmg):
self.name = name
self.maxHP = maxHP
self.currentHP = maxHP
self.roll_dmg = lambda: random.randint(min_dmg, max_dmg)
def attack(self, other, retaliation=False):
other.currentHP -= self.roll_dmg()
if not retaliation:
other.attack(self, retaliation=True)
def run(self, other):
if random.random() >= 0.5:
return True
return False
class Battle(object):
def __init__(self, *actors, location=None):
self.actors = actors
self.location = location
def do_round(self):
for actor in self.actors:
choice, target = self.make_choice(actor)
self.do_choice(choice, target)
yield self.check_battle_over()
def check_battle_over(self):
for actor in self.actors:
if actor.currentHP <= 0:
return actor
return None
def do_choice(self, func, target):
return func(target)
def make_choice(self, actor):
print("1. Attack\n"
"2. Run away\n")
choice = input(">> ")
if choice == '1':
action = actor.attack
elif choice == '2':
action = actor.run
actor_mapping = {num:act for num,act in enumerate(
filter(lambda a: a is not actor), start=1}
print("Target:")
print("\n".join(["{}. {}".format(*target) for target in actor_mapping.items()]))
target = actor_mapping[input(">> ")]
return (action, target)
def start(self):
while True:
loser = do_round()
if loser:
print(loser.name + " is dead!")
return
player = Actor(name="Player", maxHP=30000,
min_dmg=80, max_dmg=200)
monster = Actor(name="Monster", maxHP=20000,
min_dmg=50, max_dmg=100)
battle = Battle(player, monster)
battle.start()

Related

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.

How do you call on an attribute of a class, as if its a variable (in python)?

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

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

Rock Paper Scissors Running Twice Error

I'm new to programming. I have written code for the rock paper scissors game but there is one bug that I can't seem to fix. When the game closes, the user is asked if he wants to play again. If the user answers yes the first time, then plays again then answers no the second time, the computer for some reason asks the user again if he wanted to play again. The user must enter no in this case. This is because although the user answers no, the answer gets reset to yes and goes over again. How can this be fixed?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
This is because of the way the call stack is created.
The First time you play and enter yes to play again, you are creating another function call to theGame(). Once that function call is done, your program will continue with the while loop and ask if they want to play again regardless if they entered no because that input was for the second call to theGame().
To fix it, add a break or set playAgain to no right after you call theGame() when they enter yes
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
break ## or playAgain = "no"
You should break out of the loop after calling theGame. Imagine you decided to play again 15 times. Then there are 15 replay loops on the stack, waiting to ask you if you want to play again. Since playAgain is "yes" in each of these loops, each is going to ask you again, since playAgain is not "no"

Categories