我对Python和OOP比较陌生,我试图用类写一个迷你冒险游戏,并且被困在我的BattleEngine类中。 这个想法是有选择根据你的角色和对手的实力和智慧来对抗或战胜对手。 我得到一个错误,当我尝试打电话给我的攻击方法在这里:外部类python的调用方法
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'
一旦我在我的程序这一点是接收错误:'攻击全局名称未定义' 我不确定我在做什么错误。任何帮助将是太棒了!
解决此问题后,您的'player_wins'处理不当。我想在'enter'里面你要设置'player_wins'为调用'attack'的结果,然后检查它;而在'攻击'中,如果玩家获胜,你想返回'True'而不是一些名为'player_wins'的全局变量,否则返回'False'而不是''death''。 – abarnert 2013-04-09 21:58:41
另外,你几乎肯定希望'strength'和'wit'是'Player'类的实例属性,而不是class属性。如果有多个玩家,他们每个人都有不同的“强度”值,对吧?例如,如果我完成游戏并重新开始作为新角色,我将不会像上次那样拥有同样的力量。 – abarnert 2013-04-09 22:00:16
我安排代码的方式是,如果用户选择玩新游戏,那么'strength'和'wit'属性会重置。 – twillw 2013-04-09 22:14:25