2016-09-15 122 views
-1
import random 

class game: 

    def __init__(self): 
     self.hp = random.randint(1,20) 
     self.dmg = random.randint(1,15) 
     self.regn = random.randint(1,3) 

     self.stab = 3-self.hp 
    def player(self): 
     print("Health") 
     print(self.hp) 
     print("Damage") 
     print(self.dmg) 
     print("Regen") 
     print(self.regn) 

    def Mob_1(self): 
     hit = self.hp - 3 

     if 1 == 1 : 
      print("you were hit") 
      hit 

     self.mob1_hp=8 
     self.mob1_dmg=4 
     while self.mob1_hp <= 0: 
      hit 
      self.mob1_hp -= self.dmg 
     print(self.mob1_hp) 

    goblin = Mob_1('self') 


    def day_1(self,goblin): 
     print("\nIt day one") 
     goblin 

第一個功能工作正常player(self),而是試圖做另外一個時,我得到一個斷言錯誤。爲了解釋我製作妖精的原因,我可以一次性調用整個功能(或者這就是它所要做的)。特別的錯誤是形成hit = self.hp - 3代碼行。更多的澄清這裏是錯誤消息:我得到斷言錯誤,我不知道爲什麼

Traceback (most recent call last): 
    line 3, in <module> 
    class game: 
    line 33, in game 
    goblin = Mob_1('self') 
line 20, in Mob_1 
    hit = self.hp - 3 
AttributeError: 'str' object has no attribute 'hp' 

PS我很新的這個網站我已經看過過去的問題尋求幫助,但我似乎無法找到一種方法來解決它

+1

的'AttributeError'是不是'AssertionError'不同的事情。 – Blckknght

回答

1

goblin = Mob_1('self')沒有任何意義。你直接調用你的game對象的方法,但是傳遞字符串'self'而不是實例game類。這將打破各種事情。

我不完全知道如何解決它,因爲你的代碼不作一大堆的感覺,我真的不知道你想做什麼。如果你重新命名了一些你正在創建和重組的東西,也許你可以更接近你想要的東西。目前,你正在嘗試在game課中做一些看起來並不合適的事情。例如,你正在跟蹤兩套hp統計數據,看起來更像是戰鬥角色的統計數據,而不是遊戲本身的統計數據。

所以不是一個game類,我建議你創建一個Creature類,將跟蹤統計的一個生物(無論是玩家,還是敵人):

class Creature: 
    def __init__(self, name, hp, damage, regen): 
     self.name = name 
     self.hp = hp 
     self.damage = damage 
     self.regen = regen 

    def __str__(self): 
     return "{} (Health: {}, Damage: {}, Regen: {})".format(self.name, self.hp, 
                   self.dmg, self.regen) 

玩家和怪物會該類的實例(或者可能是子類的實例,如果您需要能夠更多地定製它們)。您可以編寫一個函數來讓他們兩個自相殘殺:

def fight(creature1, creature2): 
    while creature1.hp > 0 and createure2.hp > 0: 
     creature1.hp -= creature2.damage 
     creature2.hp -= creature1.damage 
     # do something with regen here? 
     # report on damage? 

    if creature1.hp < 0 and creature2.hp < 0: 
     print("Both {} and {} have died".format(creature1.name, creature2.name)) 
    else: 
     print("{} has died".format((creature1 if creature1.hp < 0 
            else creature2).name.capitalize()) 

這樣稱呼它:

player = Creature("the player", 
        random.randint(1,20), 
        random.randint(1,15), 
        random.randint(1,3)) 
goblin = Creature("the goblin", 8, 4, 0) 

print("Battle between {} and {}:".format(player, goblin)) # uses __str__ 

fight(player, goblin)