You could use this compact Computer player function as your AI:
from random import sample
axes = [(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 isWin(board):
return any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)
#level 3**3=Naive, 3**4=beginner, 3**5=intermediate, 3**6=good, 3**7=expert
def rating(position,play,board,level=3**6):
if board[position] != " " or level < 3: return 0
newBoard = board[:position]+[play]+board[position+1:]
if isWin(newBoard): return level*2
nextRatings = [rating(p,"XO"[play=="X"],newBoard,level/3) for p in range(9)]
return level-max(nextRatings,key=abs)
To make the computer play (with some randomness), use this line where computer
is the letter that the computer plays ("X" or "O") and board is a list of board positions (indexed from 0 to 8) containing "X", "O" or a space character:
position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
Here is some sample code using the computer playing function:
while True:
board = [" "]*9
player,computer = sample("XOXO",2)
player = computer
print(player,computer)
while True:
for r in range(0,9,3):
print("("+") (".join(board[r:r+3])+")",list(range(r+1,r+4)))
available = [str(p+1) for p in range(9) if board[p] == " "]
if isWin(board) or not available : break
player = "XO"[player=="X"]
if player == computer:
position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
print(f"Computer plays {player} at {position+1}")
else:
while True:
position = input(f"Position to play for {player}: ")
if position not in available: print("Invalid position")
else : position = int(position)-1; break
board[position] = player
print( f"{player}'s WIN !!!
" if isWin(board) else "DRAW.
")