我无法在此找到错误。它给出的错误是您没有创建函数life_left,或者它无法找到它。
你想让他们打多少次? 5
Traceback (most recent call last): File "main.py", line 42, in <module> start(7) File "main.py", line 39, in start arr[number].attack(guns[guns_number]) File "main.py", line 19, in attack life_left(self.life) NameError: name 'life_left' is not defined
import random
class Enemy:
def __init__(self):
self.life = 20
def attack(self,gun):
if (self.life <= 0):
print("Dead")
else:
if gun is "AK47":
self.life = self.life - 5
life_left(self.life)
elif gun is "Magnum":
self.life = self.life - 4
life_left(self.life)
else:
self.life = self.life - 1
life_left(self.life)
def life_left(life):
print ("Life : " , str(life))
def start(players):
a = 1
arr = []
while a <= players:
arr.append("player" + str(a))
arr[a-1] = Enemy()
#print (arr[a-1])
a += 1
enemy = int(input("How many times do you want them to fight ? "))
fight = 1
guns = ["AK47" , "Magnum" , "other"]
while fight <= enemy:
number = random.randint(0,players-1)
guns_number = random.randint(0,len(guns)-1)
arr[number].attack(guns[guns_number])
fight += 1
start(7)
答案 0 :(得分:0)
您必须在方法定义中使用self
并调用类中的方法。这是固定代码:
import random
class Enemy:
def __init__(self):
self.life = 20
def attack(self,gun):
if (self.life <= 0):
print("Dead")
else:
if gun is "AK47":
self.life = self.life - 5
self.life_left(self.life)
elif gun is "Magnum":
self.life = self.life - 4
self.life_left(self.life)
else:
self.life = self.life - 1
self.life_left(self.life)
def life_left(self,life):
print ("Life : " , str(life))
def start(players):
a = 1
arr = []
while a <= players:
arr.append("player" + str(a))
arr[a-1] = Enemy()
#print (arr[a-1])
a += 1
enemy = int(input("How many times do you want them to fight ? "))
fight = 1
guns = ["AK47" , "Magnum" , "other"]
while fight <= enemy:
number = random.randint(0,players-1)
guns_number = random.randint(0,len(guns)-1)
arr[number].attack(guns[guns_number])
fight += 1
start(7)