-1
votes

Comment appelez-vous un attribut d'une classe, comme si sa variable (en python)?

IM Nouveau pour coder et assez confus par le concept de classe et comment les utiliser. Je fais un jeu de zork comme un exercice de pratique et possède ce qui suit dans mon code: xxx pré>

plus loin dans le code, si le joueur est "blessé", je veux être capable de réduire la santé , jusqu'à ce que c'est 0 et ils "meurent". J'ai essayé de faire: p> xxx pré>

mais cela ne fonctionne pas, disant "soi" non défini. Comment puis-je appeler Self.Health de le changer? P>

Edit: Ive a été informé que l'ensemble du code doit être affiché, voici: P>

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


5 commentaires

Est "plus tard dans le code ..." dans la même classe?


Mettre le code entier.


Modifier la question à expliquer "ne fonctionne pas". Que se passe-t-il, que devrait-il arriver? Afficher les messages d'erreur (le cas échéant) comme texte correctement formaté dans la question.


Déjà trois réponses tandis que l'OP n'a même pas clarifié la question. J'admire les tentatives mais ...


Vous devez fournir un exemple de reproductible minimal et une description adéquate du problème. "Cela ne fonctionne pas" n'est pas adéquat. Qu'est-ce que ne fonctionne pas et Comment ne fonctionne-t-il pas? Qu'avez-vous attendre et qu'avez-vous eu ?


3 Réponses :


1
votes

Définir une méthode de votre classe nommée blessé et un getter pour Santé , comme ceci: xxx

puis plus tard dans le code Vous pouvez appeler ces méthodes telles que ceci: xxx


0 commentaires

0
votes

Je crois que cet exemple devient à la question que vous avez posée. XXX

L'instruction Imprimer sorties: 80


0 commentaires

0
votes

Ce que vous avez essayé fonctionnerait dans une autre méthode dans votre classe héros : xxx

si vous essayez de réduire la santé d'un objet de type Héros , vous devez le faire via la référence d'objet comme ceci: xxx

ou vous pouvez accéder à auto.Health directement (mais Mieux vaut le faire via une méthode comme je l'ai montrée ci-dessus): xxx


0 commentaires