Would appreciate any input on these building blocks functions of tic tac toe.
def display_field(cells):
print('''\
---------
| {} {} {} |
| {} {} {} |
| {} {} {} |
---------\
'''.format(*cells))
def analyze_field(cells):
"""
Args:
cells (str): a string of an XO pattern
Returns:
(str): the result of the XO field
"""
num_x = cells.lower().count('x')
num_o = cells.lower().count('o')
rows = [[cells[j] for j in range(i, i + 3)] for i in range(0, 9, 3)]
columns = [[row[i] for row in rows] for i in range(3)]
first_diagonal = rows[0][0] + rows[1][1] + rows[2][2]
second_diagonal = rows[0][2] + rows[1][1] + rows[2][0]
if abs(num_x - num_o) not in [0, 1]:
return 'Impossible'
num_winners = 0
for row, column in zip(rows, columns):
if len(set(row)) == 1:
num_winners += 1
if len(set(column)) == 1:
num_winners += 1
if num_winners > 1:
return 'Impossible'
for row in rows:
if len(set(row)) <= 1:
return f'{row[0]} wins'
for column in columns:
if len(set(column)) <= 1:
return f'{column[0]} wins'
if len(set(first_diagonal)) <= 1:
return f'{first_diagonal[0]} wins'
elif len(set(second_diagonal)) <= 1:
return f'{second_diagonal[0]} wins'
# No winner
else:
if '_' in cells or ' ' in cells:
return 'Game not finished'
else:
return 'Draw'
cells = input('Enter cells:')
display_field(cells)
print(analyze_field(cells))
Enter cells:XO_XO_XOX
---------
| X O _ |
| X O _ |
| X O X |
---------
Impossible