Как я могу сказать конкретную c строку текста, которую я перечисляю в классе? - PullRequest
0 голосов
/ 08 мая 2020

Я пытаюсь написать графический c роман с объектно-ориентированным программированием. На самом деле, я сосредоточен на боевой части.

По какой-то причине часть, в которой предполагается напечатать определенную c строку, не работает, она прошла бы без каких-либо действий, или я бы получил ошибка.

#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.atacar 2.defender», но не часть «3.Comprender».

Может Помогите мне, пожалуйста?

Кроме того, знаете ли вы, как считать ходы во время битвы, чтобы произносить разные фразы каждый раз, когда l oop перезапускается перед одним из двух персонажей dies?

Спасибо за внимание.

(Извините, если некоторые детали на испанском языке sh, если что-то вы не понимаете, не стесняйтесь спрашивать.)

1 Ответ

0 голосов
/ 08 мая 2020

Как указано в сообщении об ошибке, вот строка с сообщением об ошибке:

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

random не является членом данных класса, членом которого является фраза (который отображается в списке), поэтому вы не может использовать оператор точки для вызова члена данных класса, которого просто не существует.

Обычно 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])

Я рекомендую последний метод , так как я считаю его более чистым и интуитивно понятным, но оба дадут одинаковый результат.

...