I'm a fairly new programmer, been struggling for a few years on and off with brief exposure to a few languages. I'm trying to finally get a firm grasp with Python, and to do so my current project is to design a simple text based game like "Zork".
I've successfully made an EXTREMELY simple version of this using functions for each room, however this isn't generalizable at all. Before I explain what I'm currently working on poorly, I'll link the code. Now as you can see, this is a very inefficient way of building rooms as it requires tons of code and I can't use it for anything except this exact game.
To start I created a list to be used as the player inventory
inventory = []
def addToInventory(item):
inventory.append(item)
This is the class I am using to construct weapons, and is where my trouble starts. The class works fine, and I can even add instances of it to my inventory list successfully.
class Weapon:
def __init__(self, name, damage, speed, weight):
self.name = name
self.damage = damage
self.speed = speed
self.weight = weight
sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)
This is the class I am attempting to design to create rooms. It has not been implemented yet. Right now the issue that I'm facing is that unable to add instances of the Weapon class to the argument for Roominv. So for example, I could not use the sword instance of my weapon class as an argument for the contents of a Room, it tells me that sword is undefined.
Entrance = Room("You are at an entrance", "N", "Search the ground", sword)
Now my goal with this project really is to learn, so I don't want any code, but am I going down the right path with this? How can I tie certain instances of the weapons class to certain rooms? Should I be using dictionaries to build the rooms instead? If I SHOULD be using dictionaries, do I have to create an individual dictionary for each room or are nested dictionaries a thing?
I've searched a lot for the answers to these as I'm sure similar questions have been asked, but I can't seem to find a straight answer.
class Room:
def __init__(self, description, exits, actions, Roominv): #Runs every time a new room is created
self.description = description
self.exits = exits
self.actions = actions
self.Roominv = Roominv
def GAMEOVER():
print("Oh no, it appears you have died. Press 1 to restart")
choice = input(">>> ")
if choice == "1":
intro()
def introstrt():
print("WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO")
print("PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?")
print("THEN LOOK NO FURTHER!")
print("BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,")
print("AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY")
print("THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.")
print("AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!")
print(" A A A A ooo")
print(" vvv vvv vvv vvv ooooo")
print("vvvvv vvvvv vvvvv vvvvv ooo")
print(" H H H H")
print(" A A A A")
print(" vvv vvv vvv vvv | O __")
print("vvvvv vvvvv vvvvv vvvvv +-|-(__) ")
print(" H H H H / \ ")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("PRESS 1 TO BEGIN")
choice = input(">>> ")
if choice == "1":
intro()
else:
print("I can't understand that command")
intro()
def intro():
global inventory
print("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2. Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
print("5.View Intro")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest.")
intro()
elif choice == "2":
print("Sweet backflip, what now?")
intro()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.")
print("GAME OVER.")
GAMEOVER()
elif choice == "4":
print("You move towards the clearing.")
clearing()
elif choice == "Pick up sword":
addToInventory(sword)
print("Your bag contains", inventory)
intro()
elif choice == "5":
introstrt()
else:
print("I can't understand that command")
intro()
def clearing():
print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Pick the flower")
print("2.Go towards the harp")
print("3.Curse the sun whilst masturbating vigorously")
print("4.Go back")
choice = input(">>> ")
if choice == "1":
print("You pick the white flower and put it in your bag. You notice that it glows slightly.")
clearingnofl()
elif choice == "2":
print("You can't tell which direction the music is coming from!.")
clearing()
elif choice == "3":
print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
print("The sun is deeply offended and goes away. It is dark now.")
clearingdrk()
elif choice == "4":
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
intro()
else:
print("I can't understand that command")
clearing()
def clearingnofl():
print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Go towards the harp")
print("2.Curse the sun whilst masturbating vigorously")
print("3.Go back")
choice = input(">>> ")
if choice == "1":
print("You can't tell which direction the music is coming from!.")
clearingnofl()
elif choice == "2":
print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
print("The sun is deeply offended and goes away. It is dark now.")
print("You notice the flower glowing brightly in your bag.")
clearingnofldrk()
elif choice == "3":
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
intronofl()
else:
print("I can't understand that command")
clearingnofl()
def clearingdrk():
print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Pick the flower")
print("2.Go towards the harp")
print("3.Apologize to the sun, promise that you'll change and things will be like they used to be.")
print("4.Go back")
choice = input(">>> ")
if choice == "1":
print("You pick the white flower and put it in your bag. You notice that it glows brightly in the dark.")
clearingnofldrk()
elif choice == "2":
print("You can't tell which direction the music is coming from!.")
clearingdrk()
elif choice == "3":
print("The sun reluctantly forgives you, it is sunny again.")
clearing()
elif choice == "4":
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
introdrk()
else:
print("I can't understand that command")
clearingdrk()
def clearingnofldrk():
print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Go towards the harp")
print("2.Apologize to the sun, promise that you'll change and things will be like they used to be.")
print("3.Go back")
choice = input(">>> ")
if choice == "1":
print("You can't tell which direction the music is coming from!.")
clearingnofldrk()
elif choice == "2":
print("The sun reluctantly forgives you, it is sunny again.")
clearingnofl()
elif choice == "3":
print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
intronofldrk()
else:
print("I can't understand that command")
clearingnofldrk()
def intronofldrk():
print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2.Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
intronofldrk()
elif choice == "2":
print("Sweet backflip, what now?")
intronofldrk()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
elif choice == "4":
print("You move towards the clearing.")
clearingnofldrk()
else:
print("I can't understand that command")
intronofldrk()
def introdrk():
print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2.Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
introdrk()
elif choice == "2":
print("Sweet backflip, what now?")
introdrk()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
elif choice == "4":
print("You move towards the clearing.")
clearingdrk()
else:
print("I can't understand that command")
introdrk()
def intronofl():
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2.Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest.")
intronofl()
elif choice == "2":
print("Sweet backflip, what now?")
intronofl()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
elif choice == "4":
print("You move towards the clearing.")
clearingnofl()
else:
print("I can't understand that command")
intronofl()
introstrt()
I would start by adding more structure, separating the definition of the rooms from the IO/action evaluation.
In terms of maintining state, one possibility (using introSword as an example) is to modify the containing Room within the action, changing the available future actions.
You'd have to change the input and output definitions for Python 3. Hopefully those are the only changes needed.
import traceback as tb
try:
input = raw_input
def output(*args):
print ''.join(map(str,args))
inventory = []
class Weapon:
def __init__(self, name, damage, speed, weight):
self.name = name
self.damage = damage
self.speed = speed
self.weight = weight
def __repr__(self):
return self.name
sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)
class Room:
def __init__(self,description,exits,actions,others=[]):
self.description = description
self.exits = exits
self.actions = actions
self.others = others
def render(self):
output(self.description)
if self.actions:
output('You can:')
for id,name,_ in self.actions:
output(id,'. ',name)
choice = input('>>> ').upper()
for id,_,action in self.actions:
if choice == id.upper():
action(self)
break
else:
for id,action in self.others:
if choice == id.upper():
action(self)
break
else:
output('I can\'t understand that command')
self.render()
quit = False
while not quit:
def introstrtBegin(room):
intro.render()
introstrt = Room(
'''
WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO
PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?
THEN LOOK NO FURTHER!
BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,
AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY
THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.
AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!
A A A A ooo
vvv vvv vvv vvv ooooo
vvvvv vvvvv vvvvv vvvvv ooo
H H H H
A A A A
vvv vvv vvv vvv | O __
vvvvv vvvvv vvvvv vvvvv +-|-(__)
H H H H / \
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
PRESS 1 TO BEGIN
''',
[],
[],
[('1',introstrtBegin)]
)
def gameoverRestart(_):
global quit
quit = False
def gameoverQuit(_):
global quit
quit = True
gameover = Room(
'Oh no, it appears you have died. Press 1 to restart, or 2 to quit.',
[],
[],
[('1',gameoverRestart)
,('2',gameoverQuit)
]
)
def introSticks(room):
output('You don\'t find any sticks. This is a poorly designed forest.')
room.render()
def introBackflip(room):
output('Sweet backflip, what now?')
room.render()
def introWildlife(room):
output('Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.')
output('GAME OVER.')
gameover.render()
def introClearing(room):
output('You move towards the clearing.')
clearing.render()
def introNoSword(room):
output('You already picked up the sword')
room.render()
def introSword(room):
global inventory
inventory.append(sword)
output('Your bag contains: ',inventory)
room.description = 'You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.'
room.others = [
('pick up sword',introNoSword)
]
room.render()
intro = Room(
'''
You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.
''',
[],
[('1','Look for sticks',introSticks)
,('2','Do a backflip',introBackflip)
,('3','Attempt to befriend wildlife',introWildlife)
,('4','Go to Clearing',introClearing)
,('5','View Intro',lambda _: introstrt.render())
],
[('pick up sword',introSword)]
)
def clearingFlower(room):
output('You pick the white flower and put it in your bag. You notice that it glows slightly.')
room.render()
def clearingHarp(room):
output('You can\'t tell which direction the music is coming from!.')
room.render()
def clearingCurse(room):
output('CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.')
output('The sun is deeply offended and goes away. It is dark now.')
room.render()
def clearingBack(room):
output('You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.')
intro.render()
clearing = Room(
'''
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.
''',
[],
[('1','Pick the flower',clearingFlower)
,('2','Go towards the harp',clearingHarp)
,('3','Curse the sun whilst masturbating vigorously',clearingCurse)
,('4','Go back',clearingBack)
]
)
introstrt.render()
except:
tb.print_exc()
finally:
input('#')
Related
I'm new at coding and I've been trying this text-based adventure game. I keep running into syntax error and I don't seem to know how to solve this. Any suggestions on where I could have gone wrong would go a long way to helping.
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
def game_over(reason):
print("\n", reason)
print("Game Over!!!")
play_again()
def diamond_room():
print("\nYou are now in the room filled with diamonds")
print("what would you like to do?")
print("1) pack all the diamonds")
print("2) Go through the door")
answer = input(">")
if answer == "1":
game_over("The building collapsed bcos the diamonds were cursed!")
elif answer == "2":
print("You Win!!!")
play_again()
else:
game_over("Invalid prompt!")
def monster_room():
print("\nYou are now in the room of a monster")
print("The monster is sleeping and you have 2 choices")
print("1) Go through the door silently")
print("2) Kill the monster and show your courage")
answer = input(">")
if answer == "1":
diamond_room()
elif answer == "2":
game_over("You are killed")
else:
game_over("Invalid prompt")
def bear_room():
print("\nThere's a bear in here!")
print("The bear is eating tasty honey")
print("what would you like to do?")
print("1) Take the honey")
print("2) Taunt the bear!")
answer = input(">").lower()
if answer == "1":
game_over("The bear killed you!!!")
elif answer == "2":
print("The bear moved from the door, you can now go through!")
diamond_room()
else:
game_over("Invalid prompt")
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
start()
it keeps popping error and i cant detect where the error is coming from.
You have 2 problems.
Assertion instead of Assignment.
Calling the wrong function.
For 1. You have
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
You should uuse answer = input(">") and not answer ==.
For 2. You have
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
You should call start not play_again
In this part of your code, you should change you last line:
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
to answer = input(">").lower()
use = to assign a value to a variable, and use == to check the similarity(ex. in an if)
it is better to make the user input to lower case as other parts of your code, because in next lines of you've checked its value in an if condition with lower case (r and l).
3)another problem is that in def play_again(): you have to call start() function, sth like this:
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
start()
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
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.
please i am learning to code an adventure game using python. i"m comfortable with the way the code runs, only that when the player chooses to play game again it repeats the same old choice of creature. i want it to make a new selection of creature whenever the player chooses to play game again and maintain the choice till the end of the round. here is my code:
import random
import time
creatures = ["wicked fairy","gorilla","huge beast","maskquarade","Giant"]
def get_random_creature():
creature = random.choice(creatures)
return creature
creature = get_random_creature()
def print_pause(str):
print(str)
time.sleep(2)
def print_pause_longer(str1,str2,str3):
print(str1,str2,str3)
time.sleep(3)
def intro():
print_pause("You find yourself standing in an open field")
print_pause_longer("Rumour has it that a",creature,"is somewhere around here,")
print_pause("it has been terrorizing a nearby village")
print_pause("In front of you are two passage ways.")
print_pause("Left and Right")
print_pause("Enter 'L' to go left")
print_pause("Enter 'R' to go right")
def go_left():
print_pause("You take left, and find an old cave")
print_pause("What would you like to do?")
print_pause("Enter 1 to get into the cave")
print_pause("Enter 2 to go back to the open field")
choice2 = input()
if choice2 == "1":
in_cave()
elif choice2 =="2":
open_field()
else:
go_left()
def in_cave():
print_pause("You push open the door of cave")
print_pause("The first thing you saw was a shinny sword that spinned around on its own")
print_pause("what would you like to do next?")
print_pause("Enter 1 to collect the sword")
print_pause("Enter 2 to leave the cave")
choice3 =input()
if choice3 == "1":
collect_sword()
elif choice3 == "2":
leave_cave()
else:
in_cave()
def collect_sword():
print_pause("You reach out for the sword and collect it")
print_pause("Then you walk out of the cave")
print_pause("As you moved some miles from the cave")
print_pause("You heared a loud noise")
print_pause_longer("Sounds like the",creature,"grrrrrrrrrrrrrrrrrh!!!")
print_pause("It is right behind you")
print_pause("what would you do next?")
print_pause("Enter 1 to run away")
print_pause("Enter 2 to fight")
choice4 = input()
if choice4 == "1":
run_away()
elif choice4 == "2":
win_fight()
else:
collect_sword()
def run_away():
print_pause("You make an attempt to run away")
print_pause_longer("The",creature, "catches up with you")
print_pause("You are defeated")
play_again()
def win_fight():
print_pause("You turn around to fight")
print_pause_longer("As the ",creature, "beheld your shinny sword, it fell dead")
print_pause_longer("You have rid the town of the",creature,"Yay!!")
print_pause("You are Victorious")
play_again()
def lost_fight():
print_pause_longer("You face the ", creature," with courage")
print_pause("But in no time")
print_pause("You discovered you've just engaged in a lost battle")
print_pause("You have been defeated")
play_again()
def leave_cave():
print_pause("You leave the cave")
print_pause("You take right, and find a house")
print_pause("You pushed the door open to get in")
print_pause_longer("AHHHH!!!", "it is the house of the", creature)
print_pause("You were Terrified")
print_pause("Enter 1 to run away")
print_pause("Enter 2 to fight back")
choice5 = input()
if choice5 == "1":
run_away()
elif choice5 == "2":
lost_fight()
else:
leave_cave()
def open_field():
print_pause("You hurry back to the open field")
print_pause("In front of you are two passage ways.")
print_pause("Left and Right")
print_pause("Enter 'L' to go left")
print_pause("Enter 'R' to go right")
play_game()
def go_right():
print_pause("You take right, and find a house")
print_pause("You pushed the door open to get in")
print_pause_longer("AHHHH!!!", "it is the house of the", creature)
print_pause("You were Terrified")
print_pause("Enter 1 to run away")
print_pause("Enter 2 to fight back")
choice6 = input()
if choice6 == "1":
run_away()
elif choice6 == "2":
lost_fight()
else:
go_right()
def play_game():
choice1 = input()
if choice1 == "L":
go_left()
elif choice1 == "R":
go_right()
else:
print_pause("Sorry,i don't get you")
intro()
play_game()
def play_again():
print_pause("Would you like to play again, yes or no")
play_again = input("y or n\n")
if play_again == "n":
print_pause("Thanks for playing! See you next time.")
elif play_again == "y":
print_pause("Excellent! Restarting the game...")
intro()
play_game()
else:
play_again()
intro()
play_game()
The problem is that get_random_creature() is called only once at the biggining in creature = get_random_creature().
You intro() function uses the same creature variable (already stored) every time you call it
You can easily fix this by adding creature = get_random_creature() into your intro function:
def intro():
creature = get_random_creature()
print_pause("You find yourself standing in an open field")
print_pause_longer("Rumour has it that a",creature,"is somewhere around here,")
print_pause("it has been terrorizing a nearby village")
print_pause("In front of you are two passage ways.")
print_pause("Left and Right")
print_pause("Enter 'L' to go left")
print_pause("Enter 'R' to go right")
Hope it helps
Working on Ary's answer, I would declare the creature variable as None at the start of the game, then populate it with a random value in the intro() function.
example below:
creature = None
def print_pause(str):
print(str)
time.sleep(0.1)
def print_pause_longer(str1,str2,str3):
print(str1,str2,str3)
time.sleep(0.1)
def intro():
creature = get_random_creature()
print_pause("You find yourself standing in an open field")
print_pause_longer("Rumour has it that a",creature,"is somewhere around here,")
print_pause("it has been terrorizing a nearby village")
print_pause("In front of you are two passage ways.")
print_pause("Left and Right")
print_pause("Enter 'L' to go left")
print_pause("Enter 'R' to go right")
Here is my code, if you play it, then you should see what's wrong. I am not for sure how to end the code once the player dies or wins. Play till the ending and look at the code so you can understand what may be the issue.
Thanks so much, here is the code:
def start ():
print ("Hello! Welcome to Prison Break!")
print (""""You are a very infamous spy working with a foreign government in the US. You are always successful and have never been caught...until now.""")
print ("You were captured by the FBI when you were walking down the street after a mission, and they jumped you.")
print ("You don't know what is happening!")
description_of_room()
def description_of_room ():
print ("You wake up in a prison cell. Everything seems very old, dust lies on the ground, untouched for years.")
print ("The room seems empty besides the cell bars, crumbling wall behind you, and a pile of rubble.")
room_1()
def room_1 ():
print("")
prompt_0()
def prompt_0 ():
prompt_0 = input("What do you do?.")
try:
if prompt_0 == "look":
print(" ")
description_of_room() # goes internally into room_1
if prompt_0 == "cell bars":
print("You examine the cell bars carefully.")
print("The bars are very old, a wrench could be able to rip them open")
room_1()
if prompt_0 == "rubble":
print("You closely examine the rubble. You see a metal rusty handle of something.")
print("You pull it easily out of the rubble, its a old wrench, maybe it could be used on the cell bars.")
options()
elif prompt_0 == "wall":
print("You examine the crumbling wall.")
print("It is extremely old, it seems someone has cut away at it, making it delicate, a hammer could easily take care of it.")
room_1()
else:
print("Please type in cell bars, wall, rubble, or look")
room_1()
except ValueError():
print("ARE YOU CRAZY? DON'T TYPE NUMBERS! YOU'LL CRASH MY GAME!")
print(" ")
room_1()
room_1()
options()
def options():
print()
prompt_1()
def prompt_1():
prompt_1 = input("Use wrench on bars or trade with Billy for a Hammer, who is next door.")
try:
if prompt_1 == "use wrench":
print("The wrench will be able to break open the cell bars.")
print("If you do it now you will be caught, you must wait till night.")
escape_2_mor()
if prompt_1 == "trade with billy":
print("Billy is the common trader in the prison, he will take pretty much anything.")
print("You give the rusty wrench to Billy and he gives you a decent small hammer, which can be used to smash the crumbly wall.")
failure()
elif prompt_1 == "Random":
print("RANDOM")
options()
else:
print("Type trade with billy or use on cell bars.")
options()
except ValueError():
print("NO NUMBERS!")
print(" ")
options()
def escape_2_mor():
print()
prompt_3()
def prompt_3():
prompt_3 = input("What do you do?")
try:
if prompt_3 == "wait":
print("You wait till night.")
escape_2_nih()
elif prompt_3 == "use wrench":
print("You were caught by the police, punishment is death.")
print("You died, Game Over!")
end()
else:
print("Type wait or use wrench")
escape_2_mor()
except ValueError():
print("I SAID NO NUMBERS")
print(" ")
escape_2_mor()
def escape_2_nih():
print()
prompt_4()
def prompt_4():
prompt_4 = input("It's midnight, you have the chance to use the wrench!")
try:
if prompt_4 == "use wrench":
print("You slowly break the old bars, the noise echoing throughout the halls.")
escape_2_nih_1()
elif prompt_4 == "wait":
print("You wait for no reason, it's morning again.")
escape_2_mor()
else:
print("Type use wrench or wait")
except ValueError:
print("Why do I even try...")
print(" ")
escape_2_nih()
def escape_2_nih_1():
print()
prompt_5()
def prompt_5():
prompt_5 = input("Your outside your cell bars, in a dark hallway, what do you do?")
try:
if prompt_5 == "crawl":
print("You get on your knees quietly, making sure no one can see you.")
print("You stick in the shadows and come across a guard.")
print("You hit him on the head with the wrench, luckily he is wearing a helmet, so he is just knocked out.")
escape_2_des
elif prompt_5 == "run":
print("You run quickly down the hallway, you see other cellmates sleeping.")
print("You almost reach the metal door at the end of the hallway, but a guard turns and sees you.")
print("He is so suprised that he fires his gun before you can attack him.")
print("You fall to the ground, everything goes dark, you died.")
end()
else:
print("Please type crawl or run")
escape_2_nih_1()
except ValueError:
print("Just stop")
escape_2_nih_1()
escape_2_des()
def escape_2_des():
print()
prompt_6()
def prompt_6():
prompt_6 = input("You press open the door and you see towering gates and a guard tower, what do you do?")
try:
if prompt_6 == "tower":
print("You see the tower, and slowly approach it. You reach the tower and see its made out of stone that can be easily climbed.")
print("You climb up the wall, and then reach the top. You can see that the tower is high enough to jump over the fence and escape.")
print("You take a huge leap and fall to the ground, you look behind you and see the fence and the prison.")
print("You have escaped the prison! You Win!")
end()
if prompt_6 == "fence":
print("You slowly approach the fence and put your hand on it to start climbing.")
print("You are quickly electrocuted by the electric fence, stopping your heart.")
print("You've lost!")
end()
else:
print("Type fence or tower")
escape_2_des()
except ValueError:
print("Your annoying")
escape_2_des()
def failure():
print()
prompt_7()
def prompt_7():
prompt_7 = input("You can now break open the crumbled wall")
try:
if prompt_7 == "break wall":
print("You hammer away at the wall, which is breaking down easily.")
print("All the sudden a guard comes up from behind and stares down at you.")
print("Hello Officer! How are you doing today?")
print("Please come with me inmate.")
print("He pulls you by the shoulders and walks you down into a different cell, a more clean and sturdy cell.")
print("He pushes you in and locks the cell bars behind you, you have failed and will never get out.")
end()
if prompt_7 == "wait":
print("You wait for no reason, good job!")
failure()
else:
print("Type wait or break wall")
except ValueError:
print("Whatever")
failure()
end()
def end():
print("Congrats you have either won or failed the game. I hope you enjoyed!")
print(" ")
print("Ignore the statement underneath, the code is being an idiot")
start()
It would be a huge help if anyone could help, thank you. I am not for sure if it's the input that is the issue or what, but it keeps repeating. You can use pycharm if you have it because that is what works for me, if it does not work in any of the other programs you may use to run python then just try to please use Pycharm because I know it works.
Your end function doesn't actually stop the code execution. what you need to do is this
import sys
#your code
#your code
#your code
def end():
print("Congrats you have either won or failed the game. I hope you enjoyed!")
print(" ")
print("Ignore the statement underneath, the code is being an idiot")
sys.exit()