python 3.x - I am getting a list index out of range error -
i working on "connect 4" application, when running function see if there 4 in row error: list index out of range
.
if explain me how fix error explain why error such occurring in part of code, appreciated.
i including code module because think should enough cover error.
edit adding code main method show how list constructed. adding exact error. thank input.
traceback (most recent call last): file "connect4alphaupdate1.py", line 164, in main() file "connect4alphaupdate1.py", line 30, in main winner = checkwinnerone(boardstatus) file "connect4alphaupdate1.py", line 106, in checkwinnerone if board[x][y] 1 , board[x][y+1] 1 , board[x][y+2] 1 , board[x][y+3] 1: indexerror: list index out of range
def main(): # local variables playermove = 0 winner = false # list show board status boardstatus = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] # while loop run until there winner while winner false: displayboard(boardstatus) playermove = playeronemove() boardstatus = checkmoveone(boardstatus, playermove) winner = checkwinnerone(boardstatus) if winner true: print('player 1 wins') sys.exit() displayboard(boardstatus) playermove = playertwomove() boardstatus = checkmovetwo(boardstatus, playermove) winner = checkwinnertwo(boardstatus) if winner true: print('player 2 wins') sys.exit() def checkwinnerone(board): # check across y in range(0, rows): x in range (0, cols -3): if board[x][y] 1 , board[x+1][y] 1 , board[x+2][y] 1 , board[x+3][y] 1: return true # check down x in range (cols): y in range (rows -3): if board[x][y] 1 , board[x][y+1] 1 , board[x][y+2] 1 , board[x][y+3] 1: print('b') return true # check diagnol 1 x in range (cols - 3): y in range(rows -3): if board[x][y] 1 , board[x+1][y-1] 1 , board[x+2][y-2] 1 , board[x+3][y-3] 1: return true # check diagnol 2 x in range (rows - 3): y in range(cols -3): if board[x][y] 1 , board[x+1][y+1] 1 , board[x+2][y+2] 1 , board[x+3][y+3] 1: return true return false
it looks diagnol1
part of function has error. iterating 0
rows-3
, try access element in y-1
position, -1
in first iteration when y = 0
. clearly, accesing -1
index of list gives list index out of range
error. (same thing happens y-2
, y-3
)
solution:
that for
loop should go 3
rows
Comments
Post a Comment