0

I am quite new programming and have been learning Python, i decided to try and create a text-based adventure through OOP, so far I've managed to overcome issues on my own but I'm stuck on this one problem i just cannot solve, here's the code:

class player:
    def __init__(self, name, health):
        self.name = name
        self.health = health

Player_1 = player ('Bob', 80)

class enemies:
    def __init__ (self, description, health, damage):
        self.description = description
        self.health = health
        self.damage = damage

    def __str__ (self):
        return '{} , {} , {}'.format (self.description, self.health, self.damage)

    def enemy_damage (self):
        Player_1.health - random_enemy1
        return Player_1.health

random_enemy1 = enemies ('Goon', 40, 5)

At the moment I'm just testing this code before applying it fully in the game, when calling the enemy_damage method (random_enemy1.enemy_damage) i can successfully lower the players health by 5, but the issue is that the players health isn't updated, so the next time the enemy_damage method is run, the players health is back to 80.

Can someone please help? How would i get the players health to update here? I have looked at numerous videos and whatnot about class methods etc but cannot wrap my head around this, i know the code is probably terrible for what i'm trying to do, but i'm just looking to get the thing to work at the moment, after which i will use other means to reduce the amount of code and improve on it.

Many thanks

2
  • You'll have to pass the instance (Player_1) to enemy_damage as an argument. Commented May 30, 2018 at 15:11
  • 1
    Player_1.health - random_enemy1 doesn't update Player_1.health (and actually it should even raise a TypeError). Commented May 30, 2018 at 15:21

1 Answer 1

1

You can define enemy_damage like this:

def enemy_damage(self, enemy):
    enemy.health -= self.damage
    return enemy.health

Then use it like this:

print("Player_1's health before damage: " + Player_1.health)

Player_1 = player('Bob', 80)
random_enemy1 = enemies('Goon', 40, 5)
random_enemy1.enemy_damage(Player_1)

print("Player_1's health after damage: " + Player_1.health)

Aside from that, I would recommend using one common class for both enemies and players, named Player.

According to PEP8, class names should normally use CapWords convention. See the docs here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.