pythonoopif-statementtext-based

Using an "if" statement in a class function to level-up Player class instance


I am working on creating a class for a Player (user) in a text-based Python game. The level is expressed as the level function in the Player class. I include a level_up() function for when users successfully complete a quest.

Completing a quest should increase the user's level and return the user's new level. However, when I run the program, the level is not increased by 1, nor does the function return the user's level.

I appreciate any feedback, suggestions, and recommendations.

class Player(object):
    def __init__(self, name:str, health:int, level:int, strength:int, quest):
        self.name = name
        self.health = health
        self.level = level
        self.strength = strength
        self.quest = False

    def __str__(self):
        return "%s stats:\n HP %s\n Level %s\n Strength %s" % (self.name, self.health, self.level, self.strength)

    def level_up(self):
        if self.quest is True:
            self.level += 1
            return "You have leveled up. You are level %s! Congratulations." % (self.level)
        else:
            pass


user = Player('User_name', 1, 1, 1, False)
print(user)

user.quest = True

user.level_up()

Solution

  • You return the "you have leveled up" string but you never print it. You have to print it for it to be visible:

    def level_up(self):
        if self.quest is True:
            self.level += 1
            print("You have leveled up. You are level %s! Congratulations." % (self.level))
    

    Or

    # Only do this if level_up returns a string instead of printing one
    print(user.level_up())