from math import inf
lines = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def result(b):
    for i,j,k in lines:
        if b[i]!=' ' and b[i]==b[j]==b[k]: return b[i]
    return 'Draw' if ' ' not in b else None

def minimax(b,maximizing):
    winner=result(b)
    if winner is not None: return {'O':1,'X':-1,'Draw':0}[winner]
    scores=[]
    for i in range(9):
        if b[i]==' ':
            b[i]='O' if maximizing else 'X'
            scores.append(minimax(b,not maximizing))
            b[i]=' '
    return max(scores) if maximizing else min(scores)

def computer_move(b):
    best_score,best_move=-inf,None
    for i in range(9):
        if b[i]==' ':
            b[i]='O'; score=minimax(b,False); b[i]=' '
            if score>best_score: best_score,best_move=score,i
    return best_move

def show(b):
    for r in range(0,9,3): print(' | '.join(b[r:r+3]))

def play():
    b=[' ']*9
    while result(b) is None:
        show(b)
        try: i=int(input('X: position 1-9: '))-1
        except ValueError: print('Enter a number'); continue
        if not 0<=i<9 or b[i]!=' ': print('Invalid move'); continue
        b[i]='X'
        if result(b) is None: b[computer_move(b)]='O'
    show(b); print('Result:',result(b))


print("You are X; the computer is O. Enter board positions 1 through 9.")
play()
