2016-09-15 102 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) 
相关问题