“如何修复”;索引器:列表索引超出范围“;关于Python

“如何修复”;索引器:列表索引超出范围“;关于Python,python,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

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

我试着从我的朋友那里复制一些代码,但是无论我尝试什么代码,我总是会遇到这个错误

#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.
等等

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.
回溯(最近一次呼叫最后一次):
文件“main.py”,第200行
支架=分拣机阵列[(透镜(分拣机阵列)-x]
索引器错误:列表索引超出范围。

索引器:列表索引超出范围表示列表索引超出范围。您试图引用一些甚至不存在的索引

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

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

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

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]}')
请注意,因为这个问题非常特定于您自己的代码,所以不太适合这样做,但更适合您自己


祝你的家庭作业顺利。

在错误发生之前,你是否尝试过使用调试器或打印语句检查数组的内容?@CaptainWhippet我不知道为什么我一开始没有想到这一点。我得到了输出:
[['Chromablast',2\n']]
这是否意味着错误是在我组合字符串时出现的,还是其他原因?对于一个简单的索引器来说,这太多的代码了。顺便说一句,为什么要使用
len(SortedArray)-x
当您可以只使用
-x
时?我理解这一点,但我不知道如何解决这个问题。x应该只上升到5,但在崩溃发生之前它只上升到2。而且列表中应该至少有5项,所以我看不出错误来自何处。在Python中,负索引是有效的,所以这不是问题。
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]}')