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
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

board[y][x]instead ofboard[x][y]?x,, strangely, seems to indicate the vertical axis. That said: you should find the lowest red disk and then check up, not down. Change your tests tox-1and so on.