如何在Python上修复“ IndexError:列表索引超出范围”

时间:2019-07-13 13:01:26

标签: python

我正在尝试调试一些为家庭作业编写的代码,但是无论如何尝试,我都无法修复会发生的错误。

我尝试从朋友那里复制一些代码,但是无论我尝试使用什么代码,我都会不断收到此错误。

#NEA 2019 DICE GAME
from time import sleep as wait
from random import randint as rand
#Here I have imported my modules that I will use later on.

Check1 = 0
#Here I create a check variable, for use in the usernames section.

print("welcome to Dice Game!")
print("Main Menu: \n 1. Play Game \n 2. Register User \n 3. View Leaderboard \n 4. Quit Game")
MenuChoice = int(input("Please enter the number of the option you would like to choose."))
#Nice greeting for the user, and a menu.

elif MenuChoice == 1:
    while Check1 == 0:
        Namae = input("Player One, Please enter your username: \n")
        with open('Usernames.txt') as openfile:
            if Namae in openfile.read():
                print("Username",Namae, "Valid!")
                Check1 = 1
                Pass = input("Please enter the passkey:")
                if Pass == 'VN467' or Pass == 'Backdoor':
                #This 'if' statement allows the user to log in using a universal passkey, or allows an administrator to log in using a backdoor.
                    print("User Authenticated!")
                else:
                    print("Invalid Passkey!")
            else:
                print("Username",Namae, "Invalid!")
    #This block allows a user to log in as player 1.


    while Check1 == 1:
        Namae2 = input("Player Two, Please enter your username: \n")
        if Namae == Namae2:
            print("Both players can't have the same username!")
            Namae2 = ''
        with open('Usernames.txt') as openfile:
            if Namae2 in openfile.read():
                print("Username", Namae2, "Valid!")
                Check1 = 0
                Pass = input("Please enter the passkey:")
                if Pass == 'VN467' or Pass == 'Backdoor':
                    print("User Authenticated!")
                else:
                    print("Invalid Passkey!")
            else:
                print("Username", Namae2, "Invalid!")
    #This block allows a user to log in as player 2.
    P1total = 0
    P2total = 0

    for i in range (1,5):
        print("Game starting!")
        wait(1)
        print("ROUND", i)
        print(Namae, " Press 'Enter' to roll")
        #This gives the player a message box to allow them to roll.
        Roll1 = rand(1,6)
        Roll2 = rand(1,6)
        #This is the command to roll the dice.
        if Roll1 == Roll2:
            print("Double! You get an extra dice!")
            Roll3 = rand(1,6)
            #This gives the player another dice if they roll a double.
        else:
            Roll3 = 0
            #This sets the value of Roll3 to zero, to prevent a NameError later on.

        TempTotal = Roll1 + Roll2 + Roll3
        print("The total of the dice is", TempTotal)
        #These lines add together all of the dice.
        if TempTotal%2 == 0:
            print("Even total! +10 points!")
            TempTotal = TempTotal + 10
            #These lines check if the dice total is even, then adds 10 if it is.
        else:
            print("Odd total! -5 points")
            TempTotal = TempTotal - 5
            #These lines check if the dice total is odd, then subtracts 5 if it is.
        P1total = P1total + TempTotal
        if P1total < 0:
            P1total = 0
            #These lines make sure that the total cannot go below 0, and sets it to 0 if it does.
        print(Namae, "Your total is", P1total)
        #This prints the current total for player 1.
        print(Namae2," Press 'OK' to roll")
        Roll1 = rand(1,6)
        Roll2 = rand(1,6)
        #This rolls the two dice.
        if Roll1 == Roll2:
            print("Double! You get an extra dice!")
            Roll3 = rand(1,6)
            #This adds another dice if the player rolls a double.
        else:
            Roll3 = 0
            #This sets Roll3 to 0 to prevent a NameError later on in the code.
        TempTotal = Roll1 + Roll2 + Roll3
        #This adds up the dice to create a total.
        print("The total of the dice is", TempTotal)
        #This tells the player what the dice rolled.
        if TempTotal%2 == 0:
            print("Even total! +10 points!")
            TempTotal = TempTotal + 10
            #This adds 10 points to the total if they roll an even number.
        else:
            print("Odd total! -5 points")
            TempTotal = TempTotal - 5
            #This takes away 5 points from the total if they roll an odd number.
        P2total = P2total + TempTotal
        if P2total < 0:
            P2total = 0
        print(Namae2, "Your total is", P2total)
    if P1total == P2total:
        print("There is a draw! \n Both players will roll 1 die.")
        Roll1 = rand(1,6)
        Roll2 = rand(1,6)
        #This makes it so that there cannot be a draw
        print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
        while Roll1 == Roll2:
            print("Another Draw!")
            Roll1 = rand(1,6)
            Roll2 = rand(1,6)
            #This makes it so that if the first reroll ends in a draw, there will keep being rerolls until there is no longer a draw.
            print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
        if Roll1 > Roll2:
            print(Namae, "Wins!")
            #Prints a winning message.
        else:
            print(Namae2, "Wins!")
            #This prints a winning message
    elif P1total > P2total:
        print(Namae, "wins!")
        Winner = Namae
        WinScore = P1total
        #This prints a message if player 1 wins
    else:
        print(Namae2, "wins!")
        Winner = Namae2
        WinScore = P2total
        #This prints a message if player 1 wins.
        #Winscore and Winner are used to append the winner to a file later on.

    LeaderboardFile = open("Leaderboard.txt", "a+")
    #This opens the file to be appended
    FullFileInput = Winner + "," + str(WinScore) + "\n"
    #This combines the two variables from earlier into one, to make it easier to append.
    LeaderboardFile.write(FullFileInput)
    #This appends FullFileInput to the file.
    LeaderboardFile.close
    #Closes the File.

    print("Top 5 Scores:")
    LeaderboardFile = open("Leaderboard.txt", "r")
    #Opens the file for reading.
    Array = []
    #Creates an empty array
    FileLength = len(open("Leaderboard.txt").readlines())
    #This reads how many lines the file has
    for counter in range(FileLength):
        record = LeaderboardFile.readline()
        cells = record.split(",")
        #This splits the file every time there is a comma
        Array.append(cells)
        SortedArray = sorted(Array, key = lambda x: x[1])
        #This sorts the list in descending order, using score.

        x = 1
        for counter in range(0,5):
            print(len(SortedArray))
            holder = SortedArray[(len(SortedArray)-x)]
            #This causes an error, for seemingly no reason.
            print(x, ":",holder[0], holder[1])
            #This prints the leaderboard, one line at a time.
            x = x + 1
            #Increments x by 1.

elif MenuChoice == 3:
    print("Top 5 Scores:")
    LeaderboardFile = open("Leaderboard.txt", "r")
    Array = []
    FileLength = len(open("Leaderboard.txt").readlines())
    for counter in range(FileLength):
        record = LeaderboardFile.readline()
        cells = record.split(",")
        Array.append(cells)
        SortedArray = sorted(Array, key = lambda x: x[1])

        x = 1
        for counter in range(5):
            holder = SortedArray[(len(SortedArray)-x)]
            print(x, ":",holder[0], holder[1])
            x = x + 1
#Lines 198 to 211 are all copied and pasted from the leaderboard earlier.


#This code is a formatting disaster, I'm sorry.

弄乱了游戏一段时间后,每次尝试显示排行榜时都会出现错误,我有一些文件。

Leaderboard.txt

包含得分格式:

Username1,score
Username2,score

依此类推...

Usernames.txt : 包含所有有效的用户名。

我希望结果类似于以下内容:

Top 5 Scores:

1: Alpha 100
2: Beta 91
3: Gamma 85
4: Delta 76
5: Epsilon 69

相反,代码显示:

Top 5 Scores:

1: Alpha 1

2: Alpha 1

(这始终将文件中的第一个值打印两次,而不对其进行排序。)

然后我得到错误:

Traceback (most recent call last):
  File "main.py", line 200 in <module>
    holder = SortedArray[(len(SortedArray)-x)]
IndexError: list index out of range.

2 个答案:

答案 0 :(得分:0)

“ IndexError:列表索引超出范围”表示您的列表索引超出范围。您正在尝试引用某个甚至不存在的索引。

holder = SortedArray[(len(SortedArray)-x)]
x = x + 1

例如,如果x变得大于(len(SortedArray),您将得到一个负索引,可以触发该错误。

答案 1 :(得分:0)

希望您不介意,但我重写了部分代码。

elif MenuChoice == 3:
    print("Top 5 Scores:")
    Array = []
    try:
        with open("Leaderboard.txt", "r") as LeaderboardFile:
            for l in LeaderboardFile.readlines():
                name, score = l.split(',')
                name = name.strip()
                score = int(score.strip())
                Array.append([name, score])
    except Exception:
        print('FileNotFound')

    Array = sorted(Array, key = lambda x: x[1], reverse=True)
    for i in range(5):
        print(f'{i+1}: {Array[i][0]} {Array[i][1]}')

请下次注意,由于此问题非常针对您自己的代码,因此不太适合SO,但更适合https://codereview.stackexchange.com/

祝您作业愉快。