當使用戶與騎士戰鬥時,我正在努力創造一個健康/憤怒(變量)下降。我定義了一個叫kingsmen的類,這個類很簡單,並且用於每個騎士,但是我總是被告知我沒有正確地調用這個類。我不確定如何解釋它。以下是班級和騎士的代碼,錯誤消息將位於底部。某些打印間距很奇怪(帶有'''''的打印間距),因爲該網站很困難。 謝謝!如何從一個類調用一個統計到一個函數 - Python
類:
class kingsmen:
def __init__(self):
self.stats = {}
def attributes(self):
health=15
anger=7
self.stats["health"] = 15 #storing default health count
self.stats["anger"] = 7
return self.stats
def warning(self): #players will see this message when meeting a knight
print ('A kingsmen! Prepare for battle!')
def noise(self):
print ("H e y , i t ' s a v i l l a g e r !") #have these attributes later.
def death(self):
if healh == 0:
print ('''DEFEATED''')
騎士:
def rknightOne(kingsmen): #r stands for random, he will be one of 5 random villains you can face
rknightOne=kingsmen()
#while health in kingsmen.stats()!= 0 and anger != 0:
if action == 'attack':
for health in rknightOne.attributes:
health=health-1
print health
print_slowly ('I did not feel a thing. Ha ha ha!')
healthDrop(user)
elif action == 'mercy':
for anger in rknightOne.attributes:
anger=anger-1
print_slowly ('Huh. I feel something warm inside.')
elif action=='run':
print_slowly ('Not so fast!')
else:
print_slowly ("Jeez this guy is looney. I CAN'T UNDERSTAND YOU!")
錯誤:
Traceback (most recent call last):
File "C:/Python27/REDEMPTION/Redemption Game V1.py", line 678, in <module>
print randomKnight()
File "C:/Python27/REDEMPTION/Redemption Game V1.py", line 440, in randomKnight
print random.choice([rknightOne(kingsmen), rknightTwo(kingsmen), rknightThree(kingsmen), rknightFour(kingsmen), rknightFive(kingsmen)])
File "C:/Python27/REDEMPTION/Redemption Game V1.py", line 178, in rknightOne
for health in rknightOne.attributes:
TypeError: 'instancemethod' object is not iterable
它說的是剛剛經歷5個騎士,可以彈出循環隨機函數。這是在情況下,它是有幫助的代碼:
def randomKnight():
print random.choice([rknightOne(kingsmen), rknightTwo(kingsmen), rknightThree(kingsmen), rknightFour(kingsmen), rknightFive(kingsmen)])
我建議不要使用'self.stats = {}'和一個'def stats(self)'方法。你應該改變其中一個的名字。一旦清除了當前的錯誤,由於名稱衝突,您很可能會面臨另一個錯誤。 – idjaw
我固定了壓痕。還在習慣這個網站。對不起,現在有什麼是我的IDLE – salexand82m