I'm having an indexing error with the following line of code, could someone please tell me what is wrong and why hopefully fix the error
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
The Full Code is:
def winner(board, EMPTY):
#If you have won
TIE = "TIE"
WAYS_TO_WIN = ((1, 2, 3),
(4, 5, 6),
(7, 8, 9),
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
(1, 5, 9),
(3, 5, 7))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
As NUM_SQUARES == 9
and python is 0 indexed, the highest index you can access from the board is board[8] (which is the ninth place on the board).
so take 1 away from all of the numbers in WAYS_TO_WIN
and it should be fine.
In more detail - the board is indexed from 0 through to 8, a total of 9 places. (0 being the first, 8 being the ninth). WAYS_TO_WIN
has a minimum value of 1, and a max of 9. 1 is equivalent to the second place on the board, and 9 would be equivalent to the non-existent 10th place, which causes the error.