Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在类中列出索引超出范围_Python_Python 3.x - Fatal编程技术网

Python 在类中列出索引超出范围

Python 在类中列出索引超出范围,python,python-3.x,Python,Python 3.x,所有代码 import random import time class Enemy(): def __init__(self): self.health = 100 self.power = random.randint(10,20) def hit(self, player): player.health -= self.power class player(): def __init__(self):

所有代码

import random
import time

class Enemy():
    def __init__(self):
        self.health = 100
        self.power = random.randint(10,20)

    def hit(self, player):
        player.health -= self.power


class player():
    def __init__(self):
        self.health = 300
        self.power = 50

    def hit(self, Enemy):
        Enemy.health -= self.power


player1 = player()
enemies = []
for i in range(5):  # create 5 enemy
    enemies.append(Enemy())
print("Play - Help - Quit")
action1 = input("Type 'hit' for enemies\n>>>> ")

while action1 != 'q':
    print("---------------")
    for i in range(len(enemies)):
        print("#{}.enemy heatlh-->{}".format(i, enemies[i].health))
    print("----------------")
    random_enemy = random.randint(1, 5)
    action = input(">>>> ")
    if action == 'hit':
        which = int(input("Which enemy? there are {} enemies\n>>>>".format(len(enemies))))
        if enemies[which].health == 0:
            enemies[which].health = 0
            print("\nThis is a death enemy")
        else:
            player1.hit(enemies[which])
            damage_enemy = random.randint(1,5)
            
            if enemies[random_enemy].health == 0:
                continue
            else:
                if damage_enemy == 1 or damage_enemy == 3 or damage_enemy == 4:
                    if enemies[which].health == 0 or enemies[which].health <= 0:
                        enemies[which].health = 0
                        print("{}. enemy death HP: {} ".format(which, enemies[which].health))
                    else:
                        enemies[random_enemy].hit(player1)
                        print("{}. enemy hit you {} damage, your HP: {} ".format(random_enemy,enemies[random_enemy].power,player1.health))


                elif enemies[which].health != 0 or enemies[which].health >= 0:
                    print("{}. enemy HP: {} ".format(which, enemies[which].health))
    elif action == 'q':
        break
random.randint(1,5)可以返回5。您的列表有5个元素,但索引从0到4


另外,你得到的最小值是1。不是0。

randint函数也包括上限整数。尝试设置
random\u敌方=random.randint(0,4)
if enemies[random_enemy].health == 0:
                continue