你如何调用一个类的属性,就好像它是一个变量(在 python 中)?

杰里米

我是编码新手,对 class 的概念以及如何使用它们感到非常困惑。我正在制作一个 zork 游戏作为练习练习,并将以下内容作为我的代码的一部分:

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

在代码的后面,如果玩家“受伤”,我希望能够降低生命值,直到它为 0 并且他们“死亡”。我试着做:

self.health -= 5
if self.health <=0:
      exit(0)

但这不起作用,说“自我”未定义。我如何调用 self.health 来改变它?

编辑:我被告知应该发布整个代码,所以这里是:

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

在您的类中定义一个名为的方法hurt和一个 for 的 getter health,如下所示:

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

然后在后面的代码中,您可以像这样调用这些方法:

hero = Hero("mohsen")
hero.hurt(5)
if hero.get_health()<=0:
    exit(0)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Forth中执行字符或字符串,就好像它是一个单词一样

SELECT 语句的 UPDATE 结果就好像它是一个视图并在 MySQL 中显示结果

从python中的另一个类调用变量

如何打印列表项,就好像它们是 python 中的打印内容一样?

你知道如何在 python 中从同一个类中输入对象吗?

缩小接口的通用并集属性,就好像它是打字稿中的局部变量一样

你如何在python中调用一个实例“内部”和“外部”的方法?

当程序在 python 中运行时,你如何创建一个新变量?

如何在python中获取另一类中一个类的一个变量的引用?

如何在 Python 中的另一个类中使用一个类中的变量?

如何从另一个 python 文件中的一个 python 文件中的类调用方法

python的什么功能使该表达式有效,方括号包含一个布尔表达式,就好像它是索引或键一样有效?

Python3如何从另一个类中的一个类调用方法

汇编:使用两个32位寄存器中的值进行除法,就好像它们是一个64位整数一样

Python:在另一个类中调用一个类

从Python 2.7中的另一个类方法调用一个类方法

如何在python中轻松地将一个变量的属性传递给另一个变量?

如何在同一个类中的另一个 api 中调用 python api 方法?

在Python中从一个类到另一个类访问变量

在一个类中调用一个函数,在另一个类python中调用一个函数

Python:使用类来处理方法调用,就好像类属性是方法参数一样

从python中的另一个函数调用变量

在类python中创建一个新的字典变量

如何从python中的另一个变量中减去一个变量

如何在python中的类中的任何函数中创建一个可访问的变量?

Python从类中的另一个函数调用一个函数

基于Python中的另一个对象属性创建一个类的对象

Python-如何从另一个新修改的python文件中调用类方法

你如何从同一个类中调用一个方法?