This is a basic Tic-Tac-Toe game with a minimal interface. The only concessions to ease of use are input validation (7 lines) and 1-indexed rows and columns (a few bytes). I've been trying to tighten it up while still maintaining readability and PEP-8 style.
I'm pretty happy with most of it, except for printing the board: I'd like to do it at the beginning, between each move, and at the end, but I don't see how to manage that without either repeating the formatted print()
call or turning it into a function and calling it twice. As you can see, my current compromise omits the empty starting board in favor of the more interesting ending board.
This printing issue is my focus at the moment, but I'm also interested in any other suggestions for improvement.
board = [['*' for i in range(3)] for j in range(3)]
def askmove(piece):
while True:
try:
x,y = map(int, input('\n> '))
if board[x-1][y-1] == '*':
board[x-1][y-1] = piece
else:
continue
except (ValueError, IndexError):
pass
else:
break
print('', *(' '.join(row) for row in board), sep='\n')
if ([piece] * 3 in board or
(piece,) * 3 in zip(*board) or
all(board[i][i] == piece for i in range(3)) or
all(board[i][2-i] == piece for i in range(3))):
print(piece, 'wins.')
return True
elif all(p!='*' for row in board for p in row):
print('Tie.')
return True
while True:
if askmove('X') or askmove('O'):
break