简体   繁体   中英

Can't seem to pass class variables through functions

I'm relatively new to coding and wanted to try my hand at a longer project - A text based RPG game - and I'm scratching my head at classes and objects, can someone point me in a better direction?

>> Error: enemy has no attribute 'attack'
class Character(object):
    def __init__(self, name):
        self.name = name
        self.maxHealth = health
        self.health = self.maxHealth
        self.attack = attack
        self.AC = AC
        self.armour = armour
        self.strength = strength
        self.equipped_weapon = equipped_weapon
        self.xp = xp

class player(Character):
    def __init__(self, name):
        self.name = "KD"
        self.maxHealth = 100
        self.health = self.maxHealth
        self.attack = 15
        self.AC = 15
        self.armour = 0
        self.strength = 15
        self.equipped_weapon = "Pistol"
        self.xp = 0

class enemy(Character):
    def __init__(self, name):
        self.name = "X"
        self.maxHealth = 60
        self.health = self.maxHealth
        self.attack = 8
        self.AC = 8
        self.armour = 0
        self.strength = 5
        self.xp = 25

enemyIG = enemy
playerIG = player

def player_combat(player, enemy):

    in_combat = 1

    while in_combat == 1 and player.health > 0:

        player_ac_check = (random.randint(0, player.attack + 1))
        enemy_ac_check = (random.randint(0, enemy.attack + 1))...



player_combat(playerIG, enemyIG)

You haven't initialized the objects, just passed references to the classes. You have to instantiate like so:

enemyIG = enemy(name="Bad Guy")
playerIG = player(name="Good Guy")

An uninitialized class doesn't have attributes unless they're defined outside of __init__

You need to instantiate to the class, not assign it.

Change this:

enemyIG = enemy
playerIG = player

to this:

enemyIG = enemy(name = 'enemy1')
playerIG = player(name = 'player1')

This would still endup in an infinite loop, you need some logic for a meaningful end, perhaps decreasing the player health.

while in_combat == 1 and player.health > 0:    
    player_ac_check = (random.randint(0, player.attack + 1))
    enemy_ac_check = (random.randint(0, enemy.attack + 1))
    player.health -= 10  # once the health goes below 0, it would end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM