Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1.  
  2. # Compute winning move, assuming X starts
  3.  
  4. def win(board,player): # check if player has three in a row
  5.     def rotate(b): # rotate board 90 deg clockwise
  6.         return ''.join([b[i] for i in [6,3,0,7,4,1,8,5,2]])
  7.     def wins(p,b): # check horizontal lines and one diagonal
  8.         return b[0:3]==p or b[3:6]==p or b[6:9]==p or b[0]+b[4]+b[8]==p
  9.     return wins(player*3,board) or wins(player*3,rotate(board))
  10.  
  11. def tic(b):
  12.     player, opponent = ('X','O') if b.count('X') == b.count('O') else ('O','X')
  13.     if win(b, opponent): # nothing to do if already lost
  14.         return opponent,b
  15.     if b.find(' ') == -1: # nothing to do if board is full. Tie.
  16.         return ' ',b
  17.     tie = None
  18.     def new_boards(b,player):
  19.         for i in xrange(9): # replace empty slot with 'player'
  20.             if b[i] == ' ': yield b[:i]+player+b[i+1:]
  21.     for b2 in new_boards(b,player):
  22.         winner,b3 = tic(b2)
  23.         if winner == player: # If I can win, I have won.
  24.             return player,b2
  25.         if winner == ' ': # If I need to tie, I can do that with b2.
  26.             tie = b2
  27.     if tie:
  28.         return ' ', tie
  29.     else:
  30.         return opponent, b2
  31.  
  32. # try it out on some boards
  33. for b in [' '*9, 'XO       ']:
  34.     while not (win(b,'X') or win(b,'O')) and b.find(' ') != -1:
  35.         w,b=tic(b)
  36.         for i in [0,3,6]: print b[i:i+3].replace(' ',':')
  37.         print
  38.     print 'done\n'