I made a tic tac toe win checker that represents a 3 x 3 board as a list of list with variables X O B as 'X', 'O' and ' '. However the input can be any valid and invalid board of tic tac toe game. e.g.
board = [[X,X,X],
[X,X,X],
[O,O,B]]
board = [[X,O,X],
[X,O,X],
[O,O,B]]
I've created a checker that works perfect for ever possible board however it's very inefficient and long. I've tried to simplify it myself with limited succes. Any help making it more compact and effienct would be much appreciated.
# 'X wins''O wins''draw''no winner'
X,O,B = 'X', 'O', ' '
def tictactoe(board):
N = 'no winner'
D = 'draw'
# row operation
for i in range(0,3):
if (board[i][0]==board[i][1]==board[i][2]) and board[i][0] is not B:
for k in range(0,3):
if i!=k and (board[k][0]==board[k][1]==board[k][2]) and board[k][0] is not B:
if (board[0] == board[1] and not board[2][0]==board[2][1]==board[2][2] and board[2][0] is not B)\
or (board[1] == board[2] and not board[0][0]==board[0][1]==board[0][2] and board[0][0] is not B)\
or (board[0] == board[2] and not board[1][0]==board[1][1]==board[1][2] and board[1][0] is not B):
return(board[i][0]+" wins")
return D
return(board[i][0]+" wins")
# changes the columns to rows - needed for the column operation
boardc = [[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]]]
# column operation
for j in range(0,3):
if (board[0][j]==board[1][j]==board[2][j]) and board[0][j] is not B:
for l in range(0,3):
if j!=l and (board[0][l]==board[1][l]==board[2][l]) and board[0][l] is not B:
#does the same as above in the row operation but uses the rotated board
if (boardc[0] == boardc[1] and not boardc[2][0]==boardc[2][1]==boardc[2][2] and boardc[2][0] is not B)\
or (boardc[1] == boardc[2] and not boardc[0][0]==boardc[0][1]==boardc[0][2] and boardc[0][0] is not B)\
or (boardc[0] == boardc[2] and not boardc[1][0]==boardc[1][1]==boardc[1][2] and boardc[1][0] is not B):
return(board[0][j]+" wins")
return D
return(board[0][j]+" wins")
#diagonal winners
if (board[0][0]==board[1][1]==board[2][2]) and board[0][0] is not B:
return(board[0][0]+" wins")
if (board[2][0]==board[1][1]==board[0][2]) and board[2][0] is not B:
return(board[2][0]+" wins")
#no winner - if there's no winner yet and there's empty spaces
for a in range(0,3):
for b in range(0,3):
if board[a][b] == B:
return N
#where the came has finished and it's a draw
else:
return D
I tried to simplify the row and column operation that differenciates the double line win from the double line draw using for loops however it came out longer than the current solution.
I'm very new to coding and a friend told me of possible way to do it with arrays. Would this be possible?