pythontextadventure

Why am i getting this error trying to add trap to my textRPG


I have been trying to add traps to my TextRPG I have something I think will work with a little bit of debugging but the first bug that I ran into is.

TypeError: init() should return None, not 'str'

the error is coming from this.

 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

when i comment out this block of code everything runs as it should. I'm at a loss as to what to do about it. ill post a link to the github repo the code is in world.py starts on line 146.

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


Solution

  • The __init__ method in python should only used be used to initialize the class variables. You are returning a string from it, which you should not do.

    You can either remove the return statement or set the string to another variable. Here is an example of what you can probably do:

    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