Tic Tac Toe

 

  1. # Tic Tac Toe
  2. import random
  3.  
  4. def drawBoard(board):
  5.     # This function prints out the board that is was passed.
  6.     # "board" is a list of 10 strings representing the board
  7.     print '   |    |'
  8.     print ' ' + board[7] + ' | ' + board[8] + '  | ' + board[9]
  9.     print '   |    |'
  10.     print '------------'
  11.     print '   |    |'
  12.     print ' ' + board[4] + ' | ' + board[5] + '  | ' + board[6]
  13.     print '   |    |'
  14.     print '------------'
  15.     print '   |    |'
  16.     print ' ' + board[1] + ' | ' + board[2] + '  | ' + board[3]
  17.     print '   |    |'
  18.  
  19. def inputPlayerLetter():
  20.     # Let's the player type which letter they want to be.
  21.     # Returns a list with the player's letter as the first
  22.     # item, and the computer's letter as the second.
  23.     letter = ''
  24.     while not (letter == 'X' or letter == 'O'):
  25.         print 'Do you want to be X or O?'
  26.         letter = raw_input().upper()
  27.  
  28.     if letter == 'X':
  29.         return ['X', 'O']
  30.     else:
  31.         return ['O', 'X']
  32.  
  33. def whoGoesFirst():
  34.     # Randomly choose the player who goes first.
  35.     if random.randint(0, 1) == 0:
  36.         return 'computer'
  37.     else:
  38.         return 'player'
  39.  
  40. def playAgain():
  41.     print 'Do you want to play again?'
  42.     return raw_input().lower().startswith('y')
  43.  
  44. def makeMove(board, letter, move):
  45.     board[move] = letter
  46.  
  47. def isWinner(bo, le):
  48.     # Given a board and a player's letter, this function returns
  49.     # True if that player has won.
  50.     return ((bo[7] == le and bo[8] == le and bo[9] == le) or
  51.             (bo[4] == le and bo[5] == le and bo[6] == le) or
  52.             (bo[1] == le and bo[2] == le and bo[3] == le) or
  53.             (bo[7] == le and bo[5] == le and bo[3] == le) or
  54.             (bo[9] == le and bo[5] == le and bo[1] == le) or
  55.             (bo[7] == le and bo[4] == le and bo[1] == le) or
  56.             (bo[8] == le and bo[5] == le and bo[2] == le) or
  57.             (bo[9] == le and bo[6] == le and bo[3] == le))
  58.  
  59. def getBoardCopy(board):
  60.     # Make a duplicate of the board
  61.     dupBoard = []
  62.  
  63.     for i in board:
  64.         dupBoard.append(i)
  65.     return dupBoard
  66.  
  67. def isSpaceFree(board, move):
  68.     return board[move] == ' '
  69.  
  70. def getPlayerMove(board):
  71.     move = ' '
  72.     while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,
  73.                                                                  int(move)):
  74.         print 'What is your next move?(1-9)'
  75.         move = raw_input()
  76.     return int(move)
  77.  
  78. def chooseRandomMoveFromList(board, moveList):
  79.     # Returns a valid move from the passed list on the passed board
  80.     # return None if there is no valid move
  81.     possibleMoves = []
  82.     for i in moveList:
  83.         if isSpaceFree(board, i):
  84.             possibleMoves.append(i)
  85.  
  86.     if len(possibleMoves) != 0:
  87.         return random.choice(possibleMoves)
  88.     else:
  89.         return None
  90.  
  91. def getComputerMove(board, computerLetter):
  92.     # Given a board and the computer's letter, determine
  93.     # where to move and return  that move.
  94.     if computerLetter == 'X':
  95.         playerLetter = 'O'
  96.     else:
  97.         playerLetter = 'X'
  98.  
  99.  
  100.         # Here is our algorithm for our Tic Tac Toe AI:
  101.         # First, check if we can win in the next move.
  102.     for i in range(1, 9):
  103.         copy = getBoardCopy(board)
  104.         if isSpaceFree(copy, i):
  105.             makeMove(copy, computerLetter, i)
  106.             if isWinner(copy, computerLetter):
  107.                 return i
  108.         # Check if the player could win on their next move, and block them.
  109.     for i in range(1, 9):
  110.         copy = getBoardCopy(board)
  111.         if isSpaceFree(copy, i):
  112.             makeMove(copy, playerLetter, i)
  113.             if isWinner(copy, playerLetter):
  114.                 return i
  115.  
  116.         # Try to take one of the corners, if they are free.
  117.     move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
  118.     if move != None:
  119.         return move
  120.  
  121.     # Try to take the center, if it is free.
  122.     if isSpaceFree(board, 5):
  123.         return 5
  124.         # Move on one of the sides.
  125.     return chooseRandomMoveFromList(board, [2, 4, 6, 8])
  126.        
  127. def isBoardFull(board):
  128.     # Return True if every space on the board has been
  129.     # taken.Otherwise return False.
  130.     for i in range(1, 10):
  131.         if isSpaceFree(board, i):
  132.             return False
  133.     return True
  134.  
  135. print 'Welcome to the Hell of Tic Tac Toe!'
  136.  
  137. while True:
  138.     # Reset the board
  139.     theBoard = [' '] * 10
  140.     playerLetter, computerLetter = inputPlayerLetter()
  141.     turn = whoGoesFirst()
  142.     print 'The ' + turn + ' will go first.'
  143.     gameIsPlaying = True
  144.  
  145.     while gameIsPlaying:
  146.         if turn == 'player':
  147.             # Player's turn.
  148.             drawBoard(theBoard)
  149.             move = getPlayerMove(theBoard)
  150.             makeMove(theBoard, playerLetter, move)
  151.             #drawBoard(theBoard)
  152.            
  153.             if isWinner(theBoard, playerLetter):
  154.                 drawBoard(theBoard)
  155.                 print 'Hooray! you have won the game!'
  156.                 gameIsPlaying = False
  157.             else:
  158.                 if isBoardFull(theBoard):
  159.                     drawBoard(theBoard)
  160.                     print 'The game is a tie!'
  161.                     break
  162.                 else:
  163.                     turn = 'computer'
  164.                     #drawBoard(theBoard)
  165.  
  166.         else:
  167.             # Computer's turn.
  168.             #drawBoard(theBoard)
  169.             move = getComputerMove(theBoard, computerLetter)           
  170.             makeMove(theBoard, computerLetter, move)
  171.             print 'Computer is moving'
  172.             if isWinner(theBoard, computerLetter):
  173.                 drawBoard(theBoard)
  174.                 print 'The computer has beaten you!You lose.'
  175.                 gameIsPlaying = False
  176.             else:
  177.                 if isBoardFull(theBoard):
  178.                     drawBoard(theBoard)
  179.                     print 'The game is a tie!'
  180.                     break
  181.                 else:
  182.                     turn = 'player'
  183.                     #drawBoard(theBoard)
  184.     if not playAgain():
  185.         break
  186.