【问题标题】:Why am i getting this error trying to add trap to my textRPG为什么我在尝试向我的 textRPG 添加陷阱时收到此错误
【发布时间】:2020-09-16 11:57:14
【问题描述】:

我一直在尝试在我的 TextRPG 中添加陷阱

TypeError: init() 应该返回 None,而不是 'str'

错误来自这个。

 class TrapRoomTile(MapTile):
def __init__(self, x, y):
    r = random.randint(1,2)
    if r == 1:
        self.trap = items.PitFall()

        self.tripped_text = "The open hole of a Pit Fall trap obstructs the tunnel."

        self.set_text = "The floor in this hallway is unusually clean."

    else:
        return"""
        Looks like more bare stone...
        """
    super().__init__(x, y)

def modify_player(self,player):
    if not self.trap.is_tripped():
        player.hp = player.hp - self.items.damage
        print("You stumbled into a trap!")
        time.sleep(1)
        print("\nTrap does {} damage. You have {} HP remaining.".
              format(self.items.damage, player.hp))

def intro_text(self):
    text = self.tripped_text if self.items.is_tripped() else self.set_text
    time.sleep(0.1)
    return text

当我注释掉这段代码时,一切都会正常运行。我不知道该怎么办。生病发布到 github repo 的链接,代码在 world.py 从第 146 行开始。

https://github.com/GusRobins60/AdventureGame.git

【问题讨论】:

    标签: python text adventure


    【解决方案1】:

    python 中的__init__ 方法只能用于初始化类变量。您正在从中返回一个字符串,您不应该这样做

    您可以删除 return 语句或将字符串设置为另一个变量。下面是一个你可以做的例子:

    class TrapRoomTile(MapTile):
    def __init__(self, x, y):
        r = random.randint(1,2)
        if r == 1:
            self.trap = items.PitFall()
    
            self.tripped_text = "The open hole of a Pit Fall trap obstructs the tunnel."
    
            self.set_text = "The floor in this hallway is unusually clean."
    
        else:
            self.set_text = "Looks like more bare stone..."
        super().__init__(x, y)
    
    def modify_player(self,player):
        if not self.trap.is_tripped():
            player.hp = player.hp - self.items.damage
            print("You stumbled into a trap!")
            time.sleep(1)
            print("\nTrap does {} damage. You have {} HP remaining.".
                  format(self.items.damage, player.hp))
    
    def intro_text(self):
        text = self.tripped_text if self.trap.is_tripped() else self.set_text
        time.sleep(0.1)
        return text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2012-05-16
      相关资源
      最近更新 更多