Angus Ryan
Angus Ryan

Reputation: 151

Indexerror in Python for unknown reason

I made connect 4, and Im trying to work out an algorithm to determine the winner. The one below determines the horizontal winner although for some reason an error occurs when the counters are positioned vertically like this. What causes this error and how do I fix it?

board[5][5] == 1 (red chip)

board[4][5] == 1 (red chip)

board[3][5] == 1 (red chip) WHEN THIS IS PLACED ERROR CAUSED

#Check for horizontal win   
 for y in range(6):
        for x in range(7 - 3):
            if board[x][y] == 1 and board[x+1][y] == 1 and board[x+2][y] == 1 and board[x+3][y] == 1:
                return True

Game ImageERROR:

  if board[x][y] == 1 and board[x+1][y] == 1 and board[x+2][y] == 1 and board[x+3][y] == 1:
    IndexError: list index out of range

UPDATE: That worked but now the vertical test isn't working, what have I done?

# check vertical spaces
for x in range(6):
    for y in range(7 - 3):
        if board[x][y] == 1 and board[x][y+1] == 1 and board[x][y+2] == 1 and board[x][y+3] == 1:
            return True

UPDATE 2: Index error when I arranaged vertical, occurs when chips are in same position as below

check vertical spaces

for x in range(6):

    for y in range(7 - 3):

        if board[y][x] == 1 and board[y+1][x] == 1 and board[y+2][x] == 1 and board[y+3][x] == 1:

            return True

Upvotes: 0

Views: 192

Answers (1)

Rockybilly
Rockybilly

Reputation: 4510

It seems like the dimensions of your board is mixed. The picture you posted gives the inserted chips inserted in a vertical order with changing y.

board[5][5] == 1 (red chip)

board[4][5] == 1 (red chip)

board[3][5] == 1 (red chip) # Like so

So your board layout should actually be accessed with Board[y][x].

But when you are searching the horizontal space, you look the Board up with Board[x][y]. Try changing that to

#Check for horizontal win   
 for y in range(6):
        for x in range(7 - 3):
            if board[y][x] == 1 and board[y][x + 1] == 1 and board[y][x + 2] == 1 and board[y][x + 3] == 1:
                return True

Edit: To fix vertical, just switch x and y as we solved horizontal check problem

Edit2: Make sure to print and check the indices while using negative terms, too big numbers would give you index error but negative numbers would not give you any errors in list indices. And you would not realize the problem until your win check fails.

Upvotes: 1

Related Questions