# Compute winning move, assuming X starts
def win(board,player): # check if player has three in a row
def rotate(b): # rotate board 90 deg clockwise
return ''.join([b[i] for i in [6,3,0,7,4,1,8,5,2]])
def wins(p,b): # check horizontal lines and one diagonal
return b[0:3]==p or b[3:6]==p or b[6:9]==p or b[0]+b[4]+b[8]==p
return wins(player*3,board) or wins(player*3,rotate(board))
def tic(b):
player, opponent = ('X','O') if b.count('X') == b.count('O') else ('O','X')
if win(b, opponent): # nothing to do if already lost
return opponent,b
if b.find(' ') == -1: # nothing to do if board is full. Tie.
return ' ',b
tie = None
def new_boards(b,player):
for i in xrange(9): # replace empty slot with 'player'
if b[i] == ' ': yield b[:i]+player+b[i+1:]
for b2 in new_boards(b,player):
winner,b3 = tic(b2)
if winner == player: # If I can win, I have won.
return player,b2
if winner == ' ': # If I need to tie, I can do that with b2.
tie = b2
if tie:
return ' ', tie
else:
return opponent, b2
# try it out on some boards
for b in [' '*9, 'XO ']:
while not (win(b,'X') or win(b,'O')) and b.find(' ') != -1:
w,b=tic(b)
for i in [0,3,6]: print b[i:i+3].replace(' ',':')
print
print 'done\n'