在声明的函数之外调用类函数

时间:2019-02-25 00:21:30

标签: python

我试图在另一个未声明类的函数中调用类函数 player.Decide()。我收到错误消息“播放器未定义。我将如何解决这个问题?

def BattleLogic():
    global enemy, enemy_race, name, level, strength, dexterity, cunning, enemy_speed, player_speed, type_speed
    global move, turn, prefix
    if enemy in ['deer']:
        enemy_race = 'animal'
    if enemy_race == 'animal':
        chance = random.randint(1,1000)
        if chance <= 10:
            prefix = 'crippled'
        elif chance > 10 and chance <= 50:
            prefix = 'old'
        elif chance >50 and chance <= 250:
            prefix = 'young'
        elif chance > 250 and chance <= 750:
            prefix = None
        elif chance > 750 and chance <= 950:
            prefix = 'strong'
        elif chance > 950 and chance <= 990:
            prefix = 'alpha'
        elif chance > 990 and chance <= 999:
            prefix = 'possessed'
        elif chance == 1000:
            prefix = '*CONVERTED*'
        else:
            prefix = 'error'
        opponent = Enemy(str(prefix),str(enemy),str(enemy_race))

    player = Player(str(name),level,strength,dexterity,cunning)
    player.Initiative()
    opponent.Initiative()
    if enemy_speed > player_speed:
        move = 0
    elif player_speed > enemy_speed:
        move = 1
    else:
        move = random.randint(0,1)
    turn = 0
    Battle()

def Battle():
    global turn, move, prefix, enemy, type_speed, enemy_title
    if turn == 0:
        print('\n\n')
        if prefix == None:
            enemy_title = enemy.capitalize()
        else:
            enemy_title = prefix.capitalize()+' '+enemy.capitalize()
        SlowPrint('A '+enemy_title+' gets into position for battle',type_speed,0.5)
        if move == 1:
            SlowPrint(enemy_title+' makes the first move',type_speed,0.25)
        else:
            SlowPrint('You make the first move',type_speed,0.25)
    if move == 0:
        turn += 1
        move = 1
        player.Decide()
    else:
        turn += 1
        move = 0
        opponent.Decide()

1 个答案:

答案 0 :(得分:0)

只需将播放器对象传递到函数中即可。您可以自由使用player.Decide()。

我个人认为,编码的主要问题是您没有习惯将某些东西传递给函数,因此迫使您声明太多的全局变量。

一个简单的示例(在您的情况下,您希望该对象成为播放器)

def Battle(obj):
    return obj.Decide()