列表索引超出范围,为什么会发生这种情况?

时间:2016-05-22 16:08:16

标签: python list

这是我得到的错误:

Traceback (most recent call last):
  File "E:\python\cloud.py", line 34, in <module>
    c = Cloud()
  File "E:\python\cloud.py", line 18, in __init__
    self.cweaponAttack = self.weaponAttack[0]
IndexError: list index out of range

我的代码出现问题,我检查过各处的拼写错误,但我没有找到。

class Cloud:
    def __init__(self):
        self.weaponAttack = list()
        self.cweaponAttack = self.weaponAttack[0]
        self.sp = 1
        self.armor = list()
        self.armorReduction = list()
        self.weapon = list()
        self.cweapon = self.weapon
        self.money = 10000
        self.lvl = 0
        self.exp = 0
        self.mexp = 100
        self.attackPower = 0
        addaps = self.cweaponAttack * self.attackPower
        self.dmg = self.cweaponAttack + addaps
        self.hp = 100
        self.mhp = 100
        self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")

上面的行是我肯定错误的来源,但以防万一,这是代码的其余部分。警告:这很长。

import random
import time
import sys
def asky():
    ask = input("Would you like to check you player stats and inventory or go to the next battle? Say inventory for inventory or say next for the next battle: ")
    if "inventory" in ask:
        inventory()
    elif "next" in ask:
        user()
def Type(t):
    t = list(t)
    for a in t:
        sys.stdout.write(a)
        time.sleep(.035)
class Cloud:
    def __init__(self):
        self.weaponAttack = list()
        self.cweaponAttack = self.weaponAttack[0]
        self.sp = 1
        self.armor = list()
        self.armorReduction = list()
        self.weapon = list()
        self.cweapon = self.weapon
        self.money = 10000
        self.lvl = 0
        self.exp = 0
        self.mexp = 100
        self.attackPower = 0
        addaps = self.cweaponAttack * self.attackPower
        self.dmg = self.cweaponAttack + addaps
        self.hp = 100
        self.mhp = 100
        self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
class Soldier:
    def __init__(self):
        dmg = random.randint(5,20)
        self.lvl = 0
        self.attackPower = dmg
        self.hp = 100
        self.mhp = 100
        self.name = "Soldier"
s = Soldier()
def enemy():
    ad = random.randint(0,2)
    if ad >= 1: #Attack
        Type("Soldier attacks!")
        print("")
        Type("Cloud Health: ")
        print(c.hp)
        Type("Enemy Health: ")
        print(s.hp)
        hm = random.randint(0, 2)
        if hm == 0:
            Type("Miss!")
            print("")
        elif hm > 0:
            crit = random.randint(0,10)
            if crit == 0:
                print("CRITICAL HIT!")
                crithit = int((s.attackPower) * (.5))
                c.hp = c.hp - (s.attackPower + crithit)
            elif crit >= 1:
                c.hp = c.hp - s.attackPower
            Type("Cloud Health: ")
            print(c.hp)
            Type("Enemy Health: ")
            print(s.hp)
        if c.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Lost!")
            print("")
        elif s.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Won!")
            print("")
            Type("You recieved 100 crystals to spend at the shop!")
            print("")
            c.money = c.money + 100
            asky()
            c.exp = c.exp + 100
        else:
            user()
    elif ad == 0:#Defend
        Type("Soldier Defends!")
        print("")
        Type("Cloud Health: ")
        print(c.hp)
        Type("Enemy Health: ")
        print(s.hp)
        if s.hp == s.mhp:
            print("")
        elif s.hp > (s.mhp - 15) and s.hp < s.mhp:
            add = s.mhp - s.hp
            s.hp = add + s.hp
            Type("Cloud Health: ")
            print(c.hp)
            Type("Enemy Health: ")
            print(s.hp)
        elif s.hp < (s.mhp - 15):
            s.hp = s.hp + 15
            Type("Cloud Health: ")
            print(c.hp)
            Type("Enemy Health: ")
            print(s.hp)
        if c.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Lost!")
            print("")
        elif s.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Won!")
            print("")
            Type("You recieved 100 crystals to spend at the shop!")
            print("")
            c.money = c.money + 100
            asky()
            c.exp = c.exp + 100
        else:
            user()
def user():
    User = input("attack or defend? ")
    if "attack" in User:#attack
        Type("Cloud attacks!")
        print("")
        Type("Cloud Health: ")
        print(c.hp)
        Type("Enemy Health: ")
        print(s.hp)
        hm = random.randint(0,4)
        if hm == 0:
            Type("Miss!")
            print("")
        elif hm > 0:
            crit = random.randint(0,7)
            if crit == 0:
                print("CRITICAL HIT!")
                crithit = int((c.dmg) * (.5))
                s.hp = s.hp - (c.dmg + crithit)
            elif crit >= 1:
                s.hp = s.hp - c.dmg
            Type("Cloud Health: ")
            print(c.hp)
            Type("Enemy Health: ")
            print(s.hp)
        if c.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Lost!")
            print("")
        elif s.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Won!")
            print("")
            Type("You recieved 100 crystals to spend at the shop!")
            print("")
            c.money = c.money + 100
            c.exp = c.exp + 100
            asky()
        else:
            enemy()
    elif "defend" in User:#defend
        Type("Cloud Heals!")
        print("")
        Type("Cloud Health: ")
        print(c.hp)
        Type("Enemy Health: ")
        print(s.hp)
        if c.hp == c.mhp:
            Type("You are at the maximum amount of health. Cannot add more health.")
            print("")
        elif c.hp > (c.mhp - 15) and c.hp < c.mhp:
            add = c.mhp - c.hp
            c.hp = add + c.hp
            Type("Cloud Health: ")
            print(c.hp)
            Type("Enemy Health: ")
            print(s.hp)
        elif c.hp <= (c.mhp - 15):
            c.hp = c.hp + 15
            Type("Cloud Health: ")
            print(c.hp)
            Type("Enemy Health: ")
            print(s.hp)
        if c.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("GAME OVER")
            print("")
            Type("You Lost!")
            print("")
        elif s.hp <= 0:
            adds = s.mhp - s.hp
            s.hp = s.hp + adds
            Type("Congratulations!")
            print("")
            Type("You Won!")
            print("")
            Type("You recieved 100 crystals to spend at the shop!")
            print("")
            c.money = c.money + 100
            c.exp = c.exp + 100
            asky()
        else:
            enemy()
    else:
        Type("The option you have entered is not in the game database. Please try again")
        print("")
        user()
def inventory():
    if c.exp == c.mexp:
        print("LEVEL UP!")
        c.exp = 0
        adde = int((c.mexp) * (.5))
        c.mexp = c.mexp + adde
        c.sp = c.sp + 1
        c.lvl = c.lvl + 1
        if c.lvl > s.lvl:
            s.lvl = s.lvl + 1
        print("")
        print("")
        print("Level: ", c.lvl)
        print("")
        nextlvl = c.lvl + 1
        print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
        print("")
        print("Amount of Skill Points:", c.sp)
        print("")
        for i in range(0, len(c.weapon)):
            print(i)
            print("Weapon: ", c.weapon[i])
            print("Weapon Attack Damage: ", c.weaponAttack[i])
            print("")
        for j in range(0, len(c.armor)):
            print("Armor: ", c.armor[j])
            print("Armor Damage Reduction: ", c.armorReduction[j])
            print("")
        print("Amount of Crystals: ", c.money)
        print("")
        print("")
        print("Stats:")
        print("")
        print("Maximum Health: ", c.mhp)
        print("")
        print("Current Health: ", c.hp)
        print("")
        dtop = 100 * c.attackPower
        print("Attack Power: Adds", dtop, "% of sword damage")
        print("")
        print("Overall Damage: ", c.dmg)
        print("")
        print("Your Name: ", c.name)
        print("")
        print("")
        sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say  *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), or say, *help* for help: ")
        print("")
        if "name" in sn:
            c.name = input("Enter Your name here: ")
            print("Success! Your name has been changed to ", c.name)
            inventory()
        elif "weapon" in sn:
            weapChange()
        elif "next" in sn:
            Type("3")
            print("")
            Type("2")
            print("")
            Type("1")
            print("")
            Type("FIGHT!")
            print("")
            user()
        elif "help" in sn:
            def helpp():
                Type("The goal of this game is to fight all the enemies, kill the miniboss, and       finally, kill the boss! each time you kill an enemy you gain *crystals*,        currency which you can use to buy weapons, armor, and health. You can spend     these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to            defeat. Once you level up, you gain one skill point. This skill point is then   used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack   power.")
                print("")
                continu = input("Say, *back*, to go back to your inventory screen. ")
                if "back" in continu:
                    inventory()
                else:
                    Type("The word you have entered is invalid. Please try again.")
                    print("")
                    helpp()
        elif "shop" in sn:
            shop()
        elif "level" in sn:
            skills()
    else:
        print("Level: ", c.lvl)
        print("")
        nextlvl = c.lvl + 1
        print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
        print("")
        print("Amount of Skill Points:", c.sp)
        print("")
        for i in range(0, len(c.weapon)):
            print("Weapon:", c.weapon[i])
            print("")
            print("Weapon Attack Damage: ", c.weaponAttack[i])
            print("")
        for i in range(0, len(c.armor)):
            print("Armor: ", c.armor[i])
            print("")
            print("Armor Damage Reduction: ", c.armorReduction[i])
            print("")
        print("Amount of Crystals: ", c.money)
        print("")
        print("")
        print("Stats:")
        print("")
        print("Maximum Health: ", c.mhp)
        print("")
        print("Current Health: ", c.hp)
        print("")
        dtop = 100 * c.attackPower
        print("Attack Power: Adds", dtop, "% of sword damage")
        print("")
        print("Your Name: ", c.name)
        print("")
        print("")
        sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say  *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), say, *weapon* to switch your current weapon, or say, *help* for help: ")
        if "name" in sn:
            c.name = input("Enter Your name here: ")
            print("Success! Your name has been changed to ", c.name)
            inventory()
        elif "weapon" in sn:
            weapChange()
        elif "next" in sn:
            Type("3")
            print("")
            Type("2")
            print("")
            Type("1")
            print("")
            Type("FIGHT!")
            print("")
            user()
        elif "help" in sn:
            def helpp():
                Type("The goal of this game is to fight all the enemies, kill the miniboss, and       finally, kill the boss! each time you kill an enemy you gain *crystals*,        currency which you can use to buy weapons, armor, and health. You can spend     these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to            defeat. Once you level up, you gain one skill point. This skill point is then   used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack   power. To switch out your weapons, type in, *weapon*.")
                print("")
                continu = input("Say, *back*, to go back to your inventory screen. ")
                if "back" in continu:
                    inventory()
                else:
                    Type("The word you have entered is invalid. Please try again.")
                    print("")
                    helpp()
            helpp()
        elif "shop" in sn:
            shop()
        elif "level" in sn:
            skills()
def weapChange():
    for i in range(0, len(c.weapon)):
        print("Weapon:", "To equip", c.weapon[i], ",say", i)
        print("Weapon Attack Damage: ", c.weaponAttack[i])
        print("")
    weapchoice = input("Enter the weapon ID to the sword you would like to equip, or say, *cancel*, to go back to your inventory. ")
    print("")
    if "0" in weapchoice:
        c.cweapon = c.weapon[0]
        c.cweaponAttack = c.weaponAttack[0]
        print("Success!", c.weapon[0], "is now equipped!")
        inventory()
    elif "1" in weapchoice:
        c.cweapon = c.weapon[1]
        print("Success!", c.weapon[1], "is now equipped!")
        inventory()
        c.cweaponAttack = c.weaponAttack[1]
    elif "2" in weapchoice:
        c.cweaponAttack = c.weaponAttack[2]
        c.cweapon = c.weapon[2]
        print("Success!", c.weapon[2], "is now equipped!")
        inventory()
    elif "3" in weapchoice:
        c.cweaponAttack = c.weaponAttack[3]
        c.cweapon = c.weapon[3]
        print("Success!", c.weapon[3], "is now equipped!")
        inventory()
    elif "4" in weapchoice:
        c.cweaponAttack = c.weaponAttack[4]
        c.cweapon = c.weapon[4]
        print("Success!", c.weapon[4], "is now equipped!")
        inventory()
    elif "5" in weapchoice:
        c.cweaponAttack = c.weaponAttack[5]
        c.cweapon = c.weapon[5]
        print("Success!", c.weapon[5], "is now equipped!")
        inventory()
    elif "6" in weapchoice:
        c.cweaponAttack = c.weaponAttack[6]
        c.cweapon = c.weapon[6]
        print("Success!", c.weapon[6], "is now equipped!")
        inventory()
    elif "7" in weapchoice:
        c.cweaponAttack = c.weaponAttack[7]
        c.cweapon = c.weapon[7]
        print("Success!", c.weapon[7], "is now equipped!")
        inventory()
    elif "8" in weapchoice:
        c.cweaponAttack = c.weaponAttack[8]
        c.cweapon = c.weapon[8]
        print("Success!", c.weapon[8], "is now equipped!")
        inventory()
    elif "9" in weapchoice:
        c.cweaponAttack = c.weaponAttack[9]
        c.cweapon = c.weapon[9]
        print("Success!", c.weapon[9], "is now equipped!")
        inventory()
    elif "cancel" in weapchoice:
        inventory()
    else:
        Type("The word or number you have entered is invalid. Please try again.")
        print("")
        print("")
        weapChange()
def skills():
    print("")
    print("You have", c.sp, "skill points to use.")
    print("")
    print("Upgrade attack power *press the number 1*")
    print("")
    print("Upgrade maximum health *press the number 2*")
    print("")
    skill = input("Enter the number of the skill you wish to upgrade, or say, cancel, to go back to your inventory screen. ")
    print("")
    if "1" in skill:
        sure = input("Are you sure you want to upgrade your character attack power in return for 1    skill point? *yes or no* ")
        print("")
        if "yes" in sure:
            if c.sp == 0:
                Type("I'm sorry but you do not have sufficient skill points to upgrade your attack    power. ")
                print("")
                skills()
            elif c.sp >= 1:
                c.sp = c.sp - 1
                c.attackPower = float(c.attackPower + .1)
                addsap = int(100 * c.attackPower)
                print("Your attack power has been upgraded to deal", addsap, "% more damage")
                skills()
            else:
                Type("How the fuck did you get negative skill points?! ")
                print("")
                skills()
        if "no" in sure:
            skills()
    elif "2" in skill:
        sure = input("Are you sure you want to upgrade your maximum health in return for 1 skill      point? *yes or no* ")
        print("")
        if "yes" in sure:
            if c.sp == 0:
                Type("I'm sorry but you do not have sufficient skill points to upgrade your maximum   health. ")
                print("")
                skills()
            elif c.sp >= 1:
                c.sp = c.sp - 1
                c.mhp = c.mhp + 30
                skills()
            else:
                Type("How the fuck did you get negative skill points?! ")
                print("")
                skills()
        if "no" in sure:
            skills()
    elif "cancel" in skill:
        inventory()
    else:
        Type("The word or number you have entered is invalid. Please try again.")
        print("")
        skills()
def shop():
    print("")
    Type("Welcome to Andrew's Blacksmith! Here you will find all the weapons, armor, and  health you need, to defeat the horrid beast who goes by the name of Murlor! ")
    print("")
    print("")
    print("Who's Murlor? *To ask this question, type in the number 1*")
    print("")
    print("Can you heal me? *To ask this question, type in the number 2*")
    print("")
    print("What weapons do you have? *To ask this question, type in the number 3*")
    print("")
    print("Got any armor? *To ask this question, type in the number 4*")
    print("")
    ask1 = input("Enter desired number here or say, cancel, to go back to your inventory screen. ")
    print("")
    if "1" in ask1:
        def murlor():
            Type("Murlor is a devil-like creature that lives deep among the caves of Bricegate. He has been terrorising the people of this village for centuries.")
            print("")
            print("")
            print("What is Bricegate? *To choose this option, type in the number 1*")
            print("")
            print("Got any more information about this village? *To choose this option, type in the number 2*")
            print("")
            print("Thank you! *To choose this option, type in the number 3*")
            print("")
            ask3 = input("Enter desired number here, or say, cancel, to go back to the main shop screen. ")
            print("")
            if "1" in ask3:
                def questionTown():
                    Type("That's the name of this town.")
                    print("")
                    print("")
                    town = input("Go back? *Say, yes, to go back to the previous screen*")
                    print("")
                    if "yes" in town:
                        murlor()
                    else:
                        Type("I'm sorry but the word you have entered is invalid. Please try again.")
                        print("")
                        print("")
                        questionTown()
                questionTown()
            elif "2" in ask3:
                def askquest1():
                    Type("Well I DO know that there's this secret underground dungeon. It's VERY dangerous but it comes with a huge reward. If you ever consider it, could you get my lucky axe? I dropped it down a hole leading to the dungeon and i was too afraid to  get it back. *If you accept the quest, say yes, if you want to go back, say,    no.*")
                    quest1 = input(" ")
                    print("")
                    if "yes" in quest1:
                        quest1()
                    elif "no" in quest1:
                        murlor()
                    else:
                        Type("The option you have selected is not valid. Please try again")
                        print("")
                        print("")
                        askquest1()
                askquest1()
            elif "3" in ask3:
                shop()
            else:
                Type("The number or word you have entered is invalid. please try again.")
                print("")
                print("")
                murlor()
        murlor()
    elif "2" in ask1:
        def heal():
            if c.hp == c.mhp:
                Type("I can't heal you because there's nothing to heal.")
                print("")
                print("")
                shop()
            elif c.hp > 10 and c.hp < c.mhp:
                Type("Sure! That'll be 30 crystals.")
                ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
                print("")
                if "okay" in ask2:
                    if c.money < 30:
                        Type("I'm sorry sir, but you don't have enough crystals to buy this.")
                        print("")
                        print("")
                        shop()
                    elif c.money >= 30:
                        c.money = c.money - 30
                        Type("30 crystals has been removed from your inventory.")
                        print("")
                        print("")
                        addn = c.mhp - c.hp
                        c.hp = c.hp + addn
                        Type("You have been healed!")
                        print("")
                        print("")
                        shop()
                elif "no" in ask2:
                    shop()
                else:
                    Type("The option you have chosen is invalid. Please try again")
                    print("")
                    print("")
                    heal()
            elif c.hp > 0 and c.hp <= 10:
                Type("How are you still alive?!")
                print("")
                print("")
                Type("That'll be 50 crystals.")
                ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
                print("")
                if "okay" in ask2:
                    if c.money < 30:
                        Type("I'm sorry sir, but you don't have enough crystals to buy this.")
                        print("")
                        print("")
                        shop()
                    elif c.money >= 30:
                        c.money = c.money - 30
                        Type("30 crystals has been removed from your inventory.")
                        print("")
                        print("")
                        addn = c.mhp - c.hp
                        c.hp = c.hp + addn
                        Type("You have been healed!")
                        print("")
                        print("")
                        shop()
                elif "no" in ask2:
                    shop()
                else:
                    Type("The option you have chosen is invalid. Please try again")
                    print("")
                    print("")
                    heal()
            else:
                Type("HELP!! IT'S THE WALKING DEAD!!")
                print("")
                print("")
                shop()
        heal()
user()

3 个答案:

答案 0 :(得分:1)

在首次使用 switch (cardsOnTable) { case 2: card3.textColor(UIColor.blackColor()) card3.text("Spades 2") // Something else case 3: 创建类的实例时,Cloud()为空self.weaponAttack,并且不会出现索引0这样的内容。

您可以考虑通过类构造函数将非空列表作为参数传递给list

self.weaponAttack

您的weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] c = Cloud(weaponAttacks) 变为:

class

答案 1 :(得分:1)

self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]

在第二行时,self.weaponAttack是一个空列表,因此没有任何元素。因此,索引0超出self.weaponAttack的范围。

答案 2 :(得分:1)

class Cloud:
    def __init__(self):
        self.weaponAttack = list()
        self.cweaponAttack = self.weaponAttack[0]

您将self.weaponAttack设置为列表,然后尝试将cweaponAttack指定为0中索引weaponAttack的元素 - 空列表在索引0处没有任何内容,因为它们是空的。我猜你在创建一个新的self.cweaponAttack实例时希望Cloud没有任何意义,在这种情况下,如果你需要它,你可以将它设置为None,否则你可以在需要时分配给它。

self.cweaponAttack = None