I am trying to use 2 'For Loops' to identify a win either vertically or horizontally in a game of tic tac toe. Currently, I'm using one loop that will iterate from 0 to 2, and almost hardcoding to check if its horizontal or vertical.
def check_win(game):
if game[0][0] == game[1][1] == game[2][2] or\
game[0][2] == game[1][1] == game[2][0]:
winner = game[1][1]
return str(winner)
for x in range(3):
if game[x][0] == game[x][1] == game[x][2]:
return str(game[x][0])
elif game[0][x] == game[1][x] == game[2][x]:
return str(game[0][x])
else:
continue
else:
return ''
What I want to do is this:
def check_win(game):
if game[0][0] == game[1][1] == game[2][2] or\
game[0][2] == game[1][1] == game[2][0]:
winner = game[1][1]
return str(winner)
for i in range(len(game)):
for j in range(len(game[i])):
if game[i][j] == game[i][j-1] == game[i][j+1]:
return str(game[i][j])
elif game[i][j] == game[i-1][j] == game[i+1][j]:
return str(game[i][j])
else:
continue
else:
return ''
But I know that it will hit an index out of range error.
How can I overcome this?