0

我对 Python 和 OOP 比较陌生,我正在尝试编写一个带有类的迷你冒险游戏,并且已经被我的 BattleEngine 类卡住了。这个想法是根据你的角色和对手的“力量”和“智慧”来选择与对手战斗或智胜对手。当我尝试在这里调用我的攻击方法时出现错误:

class Armory(Scene):

    def enter(self):
        print "This room appears to be some kind of armory. There are shelves full of weaponry lining"
        print "the walls. You walk around admiring the shiny weapons, you reach out to pick up a"
        print "massive battleaxe. Right as your fingers touch it you hear voices from behind the"
        print "next door. They sound like they're getting closer. As the voices grow nearer you must make"
        print "a decision. Will you stand and fight (enter 'fight') or will you use your wit to outsmart"
        print "your opponent(enter 'wit')?"
        decision = raw_input("> ")
        battle = BattleEngine()
        if decision == "fight":
            attack(self, Player.strength, 3)
            if player_wins:
                print "A man in light armour walks in and sees you with your sword drawn. A look of"
                print "shock and disbelief is on his face. You act quickly and lunge at him."
                print "The soldier struggles to unsheath his sword as you run him through."
                print "He collapses to the ground wearing the same look of disbelief."
                print "Your strength has increased by 1."
                Player.strength += 1
        elif decision == "wit":
            outwit(self, Player.wit, 3)    

这是我定义我的 BattleEngine 类的地方:

class BattleEngine(object):

    def attack(self, player_strength, nonplayer_strength):
        player_roll = randint(1,6)
        nonplayer_roll = randint(1,6)
        if (player_roll + player_strength) >= (nonplayer_roll + nonplayer_strength):
            return player_wins
        else: 
            return 'death'

    def outwit(self, player_wit, nonplayer_wit):
        player_roll = randint(1,6)
        nonplayer_roll = randint(1,6)
        if (player_roll + player_wit) >= (nonplayer_roll + nonplayer_wit):
            return player_wins
        else: 
            return 'death'     

一旦我在程序中到达这一点,就会收到错误消息:“未定义攻击全局名称”我不确定我到底做错了什么。任何帮助都会很棒!

4

1 回答 1

4

您需要调用您的attack 实例BattleEngine,并且不需要传入self

battle = BattleEngine()
if decision == "fight":
    player_wins = battle.attack(Player.strength, 3)

请注意,您需要接收.attack()方法的返回值。

这同样适用于.outwit()进一步的方法:

elif decision == "wit":
    player_wins = battle.outwit(Player.wit, 3)    

您可能需要修复.attack()and.outwit()方法中的返回值;而不是return player_winsand return 'death',返回True或者False也许。

self参数由 Python 为您处理,并将引用特定BattleEngine实例。

并不是说您真的需要这里的课程,例如,您的BattleEngine()课程目前没有每个实例的状态。您不会self在任何方法中使用,因为实例上没有任何东西可以引用

于 2013-04-09T21:52:41.070 回答