I want to make a tic tac toe game user enter input one line string of all columns and rows of Xs and Os like this 'O_OOXOOXX' i turn them into nested list like this [['O', '_', 'O'], ['O', 'X', 'O'], ['O', 'X', 'X']]
My question is how can replace all the if elif below? because it seems a lot.
for i in range(3):
if nested_list[i][0] == nested_list[i][1] == nested_list[i][2] == 'O':
print('O wins')
elif nested_list[0][i] == nested_list[1][i] == nested_list[2][i] == 'O':
print('O wins')
elif nested_list[0][0] == nested_list[1][1] == nested_list[2][2] == 'O':
print('O wins')
elif nested_list[0][2] == nested_list[1][1] == nested_list[2][0] == 'O':
print('O wins')
elif nested_list[i][0] == nested_list[i][1] == nested_list[i][2] == 'X':
print('X wins')
elif nested_list[0][i] == nested_list[1][i] == nested_list[2][i] == 'X':
print('X wins')
elif nested_list[0][0] == nested_list[1][1] == nested_list[2][2] == 'X':
print('X wins')
elif nested_list[0][2] == nested_list[1][1] == nested_list[2][0] == 'X':
print('X wins')
CodePudding user response:
Probabily there's a nicer solution, but maybe something like this?
for i in range(3):
a = set(nested_list[i,:])
b = set(nested_list[:,i])
if(len(a) == 1 && nested_list[i,0] != '_')
print(nested_list[i,0], " wins")
elif(len(b) == 1 && nested_list[0,i] != '_')
print(nested_list[0,i], " wins")
if (((nested_list[0][0] == nested_list[1][1] == nested_list[2][2]) || nested_list[2][0] == nested_list[1][1] == nested_list[0][2])) && nested_list[1][1] != '_'):
print(nested_list[1][1], " wins")
CodePudding user response:
Base on what i've read i managed to do this, i will try and improve it more
for i in range(3):
if nested_list[i][0] == nested_list[i][1] == nested_list[i][2]:
print(nested_list[i][0], ' wins')
elif nested_list[0][i] == nested_list[1][i] == nested_list[2][i]:
print(nested_list[0][i], ' wins')
elif nested_list[0][0] == nested_list[1][1] == nested_list[2][2]:
print(nested_list[0][0], ' wins')
elif nested_list[0][2] == nested_list[1][1] == nested_list[2][0]:
print(nested_list[0][2], ' wins')
