我對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