我如何说出我在类下列出的特定文本行?

2024-10-01 17:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用面向对象编程制作一部图形小说。 事实上,我关注的是战斗部分

出于某种原因,假设打印特定行的部分不起作用,它将不做任何操作而通过,否则我将得到一个错误

#Error:
Traceback (most recent call last):
  File "C:\Users\Ester\Desktop\Mercy or kill\Gamefalse.py", line 128, in <module>
    batalla_f1()
  File "C:\Users\Ester\Desktop\Mercy or kill\Gamefalse.py", line 94, in batalla_f1
    monstruo_escogido.frase_entre_atzar(7,9)
  File "C:\Users\Ester\Desktop\Mercy or kill\mercy_kill_classes.py", line 51, in frase_entre_atzar
    entre_atzar = self.frases.random.randrange (a,b)
AttributeError: 'list' object has no attribute 'random'

#Code:
Drah_krow=Personaje("Drah Krow","monstruo",12,12,5,1,1)
Drah_krow.mostrar_todo()
Drah_krow.afegeix_frase("Señor de mediana edad con un cuchillo clavado bajo el cuello... Parece desorientado.")
Drah_krow.afegeix_frase("Drah Krow- Echo de menos a alguien...")
Drah_krow.afegeix_frase("Drah Krow- ¿Quien era? ¿Eras tú?.")
Drah_krow.afegeix_frase("Drah Krow- Mi jefe me ordena cosas extrañas...")
Drah_krow.afegeix_frase("Drah Krow- Quiere que te mate...")
Drah_krow.afegeix_frase("Drah Krow- Oh, ya me acordé...¿Dondè estarà mi hija?")
Drah_krow.afegeix_frase("Drah Krow- Me siento tan perdido que podría morir...")
Drah_krow.afegeix_frase("Drah Krow- Me gustaria ir a la playa con el... ¿O era ella?")
Drah_krow.afegeix_frase("Drah Krow- ¿Me conoces?")
Drah_krow.afegeix_frase("Drah Krow- No se donde estoy...")
Drah_krow.mostra_frases()

prota = Humano("Prota")


def batalla_f1():
    Drah_krow=Personaje("Drah Krow","fantasma",20,1,0)
    monstruo_escogido=Drah_krow
    prota.mostrar_todo()
    print("")
    monstruo_escogido.mostrar_todo()
    print("")
    z=0
    d=0
    q=0
    inici_hp = prota.hp
    inicim_hp = monstruo_escogido.hp
    while not((prota.hp<=0) or (monstruo_escogido.hp<=0)):
        print("Es tu turno:")
        z=z+1
        i = input("1.atacar 2.defender 3.Comprender")
        if(i=="1"):
            print("Tu- Atacas:")
            a = (prota.atk - monstruo_escogido.defe) 
            if (prota.atk < monstruo_escogido.defe): #  Ataque del prota es mas pequeño que la defensa del monstruo = anular ataque del prota
                a = 0
            if (a > monstruo_escogido.hp): # Vida del monstruo = 0 (Evitar numeros negativos en la vida del monstruo)
                a = monstruo_escogido.hp
            print ("Haces",a," de daño.")
            monstruo_escogido.hp = (monstruo_escogido.hp-a)
            print("La vida del mosntruo se reduce a",monstruo_escogido.hp)
            d=d+1
            prota.mostrar_todo()
            monstruo_escogido.mostrar_todo()
        elif(i=="2"):
            print ("prota defiende")
            a= random.randrange(5,50)
            if(prota.hp == inici_hp): 
                print("Tu hp ya está al máximo.")
            elif (prota.hp < inici_hp):
                print (a)
                if((a+prota.hp)> inici_hp):#si la suma del hp mas lo que se cura es mas grande que el hp original:
                    aa=(inici_hp -(a+prota.hp))              #restas el nuevo hp - hp original
                    prota.hp = inici_hp
                    print ("Te curas:",aa,"hp")
                    print("Tu hp sube a",prota.hp)
                    print("")
                elif((a+prota.hp)<inici_hp):
                    print ("Te curas",a,"hp")
                    prota.hp = (prota.hp + a)
                    print("Tu hp sube a",prota.hp)
                    print("")
            prota.mostrar_todo()
            print("")
            monstruo_escogido.mostrar_todo()
        elif(i=="3"):
            print("Prota actua:")
            a=input("1.Observar 2.Hablar 3.Llorar")
            if(a=="1"):
                print("Tu- Observas detalladamente:")
                monstruo_escogido.digues_frase_concreta(0)
            elif(a=="2"):
                print("Tu- Le dice que no quieres pelear...")
                if((z==0) and (d==0)):
                    monstruo_escogido.digues_frase_concreta(1)
                if((z==0) and (d!=0)):
                    monstruo_escogido.digues_frase_concreta(3)
                if((z==2) and (d==0)):
                    monstruo_escogido.digues_frase_concreta(2)
                    q=1
                if((z==2) and (d!=0)):
                    monstruo_escogido.digues_frase_concreta(4)
                elif((z!=0) or (z!=2)):
                    monstruo_escogido.frase_entre_atzar(7,9)
                if(q==1):
                    monstruo_escogido.digues_frase_concreta(5)
            elif(a=="3"):
                print ("Drah Krow parece confundido...")
                prota.incrementa_hp(5)
                print ("Te recuperas por 5 hp.")
        if not((prota.hp<=0) or (monstruo_escogido.hp<=0) or (q==1)):
            print("")
            print("Es el turno del monstruo:")
            print("")
            print("Monstruo ataca:")
            b= (monstruo_escogido.atk - prota.defe)#Daño real producido al final 
            if (monstruo_escogido.atk < prota.defe ): # Anular ataque del monstruo
                b = 0
            if (b > prota.hp):
                b = prota.hp
            print ("Monstruo hace",b," de daño.")
            prota.hp = (prota.hp-b)
            print("")
            prota.mostrar_todo()
            print("")
            monstruo_escogido.mostrar_todo() 
            print ("")
    if (prota.hp >0):
        print ("Tu ganas.")
        prota.kill =(prota.kill+1)
    elif (q==1):
        print ("Drah Krow parece volver un poco en si.")
        print ("Drak Krow desaparece tras un destello de luz blanca.")
        prota.mercy = (prota.mercy +1)
    elif(prota.hp == 0):
        print("Game Over")

batalla_f1()

#Class:

import random
class Personaje():
    def __init__(self, nom, especie="desconeguda", hp=0, atk=0, defe=0,mercy=0, kill=0):
        self.nom= nom
        self.especie= especie
        self.hp = hp
        self.atk = atk
        self.defe = defe
        self.mercy=mercy
        self.kill=kill
        self.frases=[]
    def mostrar_todo(self):   #mostra tots els atributs d'un personatge excepte frases
        print("Nom: ", self.nom)
        print("Especie:", self.especie)
        print("Hp:",self.hp)
        print("Atk:",self.atk)
        print("Def:",self.defe)
    def mostrar_todo_prota(self):
        print("Nom: ", self.nom)
        print("Especie:", self.especie)
        print("Hp:",self.hp)
        print("Atk:",self.atk)
        print("Def:",self.defe)
        print("Mercy:",self.mercy)
        print("Kill:",self.kill)
    def incrementa_hp(self, quantitat):  #mètodes per incrementar els diferents atributs
            self.hp = self.hp + quantitat
    def incrementa_atk(self, quantitat):
            self.atk = self.atk + quantitat
    def incrementa_defe(self, quantitat):
            self.defe = self.defe+ quantitat
    def incrementa_mercy(self, quantitat):
            self.mercy = self.mercy + quantitat
    def incrementa_kill(self, quantitat):
            self.kill = self.kill + quantitat
    def afegeix_frase(self, frase):  #mètode per afegir frases a la llista del personatge en concret
            self.frases.append(frase)
    def mostra_frases(self):   #mètode per mostrar totes les frases del personatge
            for frase in self.frases:
                print(frase)
    def digues_frase(self):    #dir una frase de la llista a l'atzar
        if (len(self.frases)!= 0):
            frase = random.choice(self.frases)
        else:
            frase= ("...")
        print(frase)
    def digues_frase_concreta(self, ordre):
        if(ordre<(len(self.frases))):
            print(self.frases[ordre])
    def frase_entre_atzar(self,a,b):
        entre_atzar = self.frases.random.randrange (a,b)
        print (entre_atzar)
    def ataca(self,oponent):
        print(self.nom,"ATACA A", oponent.nom)
        if (self.atk > oponent.defe):
            oponent.hp = (oponent.hp-1)
            print("Li has fet mal a", oponent.nom)
        else:
            print("No li has fet mal a", oponent.nom)

class Humano(Personaje):
    def __init__(self, nom):
        super().__init__(nom)     #hereda el nom de la classe Personatge
        self.especie="humano"     #fixa els atributs propis de la classe Humano
        self.hp=30
        self.atk=15
        self.defe=15
        self.mercy=0
        self.kill=0
        
class Bestia(Personaje):
    def __init__(self, nom):
        super().__init__(nom)
        self.especie="bestia"
        self.hp=15
        self.atk=30
        self.defe=15
        self.mercy=0
        self.kill=0

class DemiHumano(Personaje):
    def __init__(self, nom):
        super().__init__(nom)
        self.especie="demi-humano"
        self.hp=15
        self.atk=15
        self.defe=30
        self.mercy=0
        self.kill=0

我不明白为什么它只适用于“1.2.defender”部分,而不适用于“3.Compender”部分

你能帮帮我吗

另外,你知道在战斗进行时如何计算回合数吗?在两个角色中的一个死亡之前,每次循环重新开始时,你都会说一个不同的短语

(很抱歉,如果某些部分是西班牙语,如果您不理解,请随时提问。)


Tags: selfifdefnomhpkillprintatk
1条回答
网友
1楼 · 发布于 2024-10-01 17:34:44

正如错误消息所述,以下是给出错误的行:

entre_atzar = self.frases.random.randrange (a,b)

random不是frases是其成员(显示在列表中)的类的数据成员,所以不能使用点运算符调用根本不存在的类的数据成员

通常,random.randrange(a,b)将返回一个介于a和b之间的随机数

所以你有两个选择:

1)获取a和b之间随机范围内的数字,然后使用该数字获取列表中该索引处的值:

entre_atzar = self.frases[random.randrange(a,b)]

2)只需从该范围内原始列表的子列表中获取一个随机值:

entre_atzar = random.choice(self.frases[a:b])

我推荐后一种方法,因为我认为它更干净,更直观,但是两者都会产生相同的结果。

相关问题 更多 >

    热门问题