Issue
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')
Solution
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...
Answered By - Zakaria Hamane
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.