[Python] Why is this method from the parent class functioning different between children...

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I'm coding a text-based RPG and I set up three classes: a character class, a player, and an enemy. I have a method called "attack" that takes in a target, then removes from its health a certain number. It works perfectly when the player is attacking the enemy, but when the enemy attacks the player, it adds to the players health instead of taking away. Both attacks happen simultaneously, maybe that's part of the problem, but I don't see how that would be the case. I want both health stats to go down per attack sequence.

    import random
    class Character():

    #initialize a blank character
    def __init__(self, level, health, strength, defense):
    self.level = level
    self.health = health * 100
    self.strength = strength
    self.defense = defense

    def attack(self, target):
    target.health = target.health-(self.strength * 1.5 - target.defense)


    class Player(Character):

    #initialize the constructor of the player
    def __init__(self, level, health, strength, defense):
    self.level = level
    self.health = health * 100
    self.strength = strength
    self.defense = defense

    def get_xp(self):
    pass

    def walk():
    pass

    class Enemy(Character):

    #initialize the constructor of the enemy
    def __init__(self, level, health, strength, defense):
    self.level = level
    self.health = health * 100
    self.strength = strength
    self.defense = defense



    import time
    import random
    from character import *

    #creating a player

    new_player = Player(1,10,10,10)

    #establishing enemy stats
    enemy_level_mod = random.randint(1,5)

    if new_player.level > 5:
    enemy_level = new_player.level - random.randint(1,5)
    else:
    enemy_level = 1

    enemy_health = enemy_level * random.randint(1,4)
    enemy_strength = enemy_level * random.randint(1,4)
    enemy_defense = enemy_level * random.randint(1,4)

    #running the game loop
    while True:
    new_enemy = Enemy(enemy_level,enemy_health,enemy_strength,enemy_defense)
    while new_enemy.health > 0:
    print(f"Player Health is:{new_player.health}")
    print(f"Enemy Health is: {new_enemy.health}")
    new_player.attack(new_enemy)
    new_enemy.attack(new_player)
    time.sleep(1)
    else:
    print("Enemy has been vanquished")
    time.sleep(1)


    Originally I didn't have a parent class, but I figured since they're both going to attack it would make more sense to have them be children of a class with common methods.

    Continue reading...

Compartilhe esta Página