Search code examples
pythondebuggingindexingindex-error

Whenever I run this file I get a IndexError: string index out of range, not sure where I'm going wrong here


First, post so sorry if this isn't the right way to format everything but I'm trying to make a connect 4 game for two players and I can't figure out why I'm getting this error.

#Creates the board
def Boardmaker(field):
    for row in range(12): #0,1,2,3,4,5,6,7,8,9,10,11
        NewRow = int(row/2)
        if row%2 == 0:
            for column in range(13):
                NewColumn = int(column/2)
                if column%2 == 0:
                    if column != 12:
                        print(field[NewColumn][NewRow],end="")
                    else:
                        print(field[NewColumn][NewRow])
                else:
                    print("|",end="")
        else:
            print("-------------")

#Play space
player = 1       #0    1    2    3    4    5    6
Currentfield = [[" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "]]

#Player Controller and turn allocator
Boardmaker(Currentfield)
while(True):
    MoveColumn = int(input("Please enter a column"))
    if player == 1:
        #if Currentfield[MoveColumn] == " ":
            Currentfield[MoveColumn] = "X"
            player = 2
    else:
        #if Currentfield[MoveColumn] == " ":
            Currentfield[MoveColumn] = "O"
            player = 1
    Boardmaker(Currentfield)

Solution

  • In the code

    if player == 1:
        #if Currentfield[MoveColumn] == " ":
            Currentfield[MoveColumn] = "X"
            player = 2
    

    you are replacing one of the lists of Currentfield with the string "X" since you are not specifying the row index. Then, while printing the game board you iterate over this string, and since this is a string of length 1 you get the index error.