Below a function which answers: is there a winner in tic-tac-toe game?
Also, there is a test suite I wrote for it.
def is_win(field):
# check horizontal
N = len(field)
for i in range(N):
if field[i][0] != 0 and len(set(field[i])) == 1:
return True
vertical = [field[j][i] for j in range(N)]
if vertical[0] != 0 and len(set(vertical)) == 1:
return True
# check diagonal
diagonal = [field[i][i] for i in range(N)]
if diagonal[0] != 0 and len(set(diagonal)) == 1:
return True
o_diagonal = [field[N-i-1][i] for i in range(N)]
if o_diagonal[0] != 0 and len(set(o_diagonal)) == 1:
return True
return False
assert is_win(
[
[0, 0, 0],
[2, 2, 2],
[0, 0, 0],
]) == True
print(1)
assert is_win(
[
[0, 2, 0],
[0, 2, 0],
[0, 2, 0],
]) == True
print(2)
assert is_win(
[
[0, 0, 2],
[2, 2, 1],
[0, 0, 1],
]) == False
print(3)
assert is_win(
[
[2, 0, 0],
[0, 2, 0],
[0, 0, 2],
]) == True
print(4)
assert is_win(
[
[0, 0, 2],
[0, 2, 0],
[2, 0, 0],
]) == True
print(5)
```