Reputation: 67
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')
Upvotes: 0
Views: 311
Reputation: 67
I figured another solution:
arr = ['X', 'X', 'O', 'O', 'O', 'X', 'X', 'O', 'X']
I determine a nested list of possible wins
matches = [[0, 1, 2], [3, 4, 5],
[6, 7, 8], [0, 3, 6],
[1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]
for i in range(8):
if(arr[matches[i][0]] == 'X' and
arr[matches[i][1]] == 'X' and
arr[matches[i][2]] == 'X'):
print(X wins)
else:
print(O wins)
and now i'm trying to figure out the other possibilities for example if the game not finished if the there is 3 Xs and Os in row then the game is impossible...
Upvotes: 0
Reputation: 40481
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")
Upvotes: 1