Guest User

Untitled

a guest
Jan 14th, 2017
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.13 KB | None | 0 0
  1. import os, random
  2.  
  3. def printBoard(board, players=None, instructions=False):
  4. # This function prints out the board that it was passed.
  5. clear_screen = os.system('cls' if os.name == 'nt' else 'clear')
  6.  
  7. # If instructions are to be displayed
  8. if (instructions == True):
  9. print('Welcome to Tic Tac Toe!\n')
  10. else:
  11. print('Computer - ' + players[1] + '\tPlayer - ' + players[0] + '\n')
  12.  
  13. # "board" is a list of 10 characters representing the board (ignore index 0)
  14. for i in xrange (1,9,3):
  15. print(' | |')
  16. print(' ' + board[i] + ' | ' + board[i+1] + ' | ' + board[i+2])
  17. print(' | |')
  18. print(' -----------')
  19.  
  20. def inputPlayerLetter():
  21. # Assigns X or O for player letter. Return list with [playerLetter,computerLetter]
  22. print('Do you want to be X or O?')
  23. letter = raw_input().upper()
  24. while not (letter == 'X' or letter == 'O'):
  25. print('Invalid input. 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 toss():
  34. # Toss to find who goes first, computer or player.
  35. if random.randint(0, 1) == 0:
  36. return 'computer'
  37. else:
  38. return 'player'
  39.  
  40. def playAgain():
  41. # Returns whether user wants to continue playing.
  42. print('Do you want to play again? (Y/N)')
  43. return not raw_input().lower().startswith('n')
  44.  
  45. def inputPlayerMove(board):
  46. # Let the player type in his move.
  47. print('What is your next move? (1-9)')
  48. move = raw_input()
  49. while move not in '1 2 3 4 5 6 7 8 9'.split() or not isEmpty(board, int(move)):
  50. print('Invalid input! What is your next move? (1-9)')
  51. move = raw_input()
  52. return int(move)
  53.  
  54. def isBoardFull(board):
  55. # Return True if every space on board (except index 0) is non-empty.
  56. for i in range(1, 10):
  57. if isEmpty(board, i):
  58. return False
  59. return True
  60.  
  61. def isEmpty(board, move):
  62. # Return True if the passed move index in board list is empty.
  63. return board[move] == ' '
  64.  
  65. def checkWin(board, letter):
  66. # Returns True if three continuous letters found on board.
  67. return ((board[7] == letter and board[8] == letter and board[9] == letter) or # bottom row
  68. (board[4] == letter and board[5] == letter and board[6] == letter) or # middle row
  69. (board[1] == letter and board[2] == letter and board[3] == letter) or # top row
  70. (board[1] == letter and board[4] == letter and board[7] == letter) or # left column
  71. (board[2] == letter and board[5] == letter and board[8] == letter) or # middle column
  72. (board[3] == letter and board[6] == letter and board[9] == letter) or # right column
  73. (board[3] == letter and board[5] == letter and board[7] == letter) or # left diagonal
  74. (board[1] == letter and board[5] == letter and board[9] == letter)) # right diagonal
  75.  
  76. def chooseRandomMoveFromList(board, movesList):
  77. # Returns a valid move from the passed list on the passed board.
  78. # Returns None if there is no valid move.
  79. possibleMoves = []
  80. for i in movesList:
  81. if isEmpty(board, i):
  82. possibleMoves.append(i)
  83.  
  84. if len(possibleMoves) != 0:
  85. return random.choice(possibleMoves)
  86. else:
  87. return None
  88.  
  89. def getComputerMove(board, players):
  90. # Given a board and the computer's letter, determine where to move and return that move.
  91. playerLetter, computerLetter = players
  92.  
  93. # Tic Tac Toe AI:
  94. # Win: Check if computer can win on next move
  95. for i in range(1, 10):
  96. copyBoard = board[:]
  97. if isEmpty(copyBoard, i):
  98. copyBoard[i] = computerLetter
  99. if checkWin(copyBoard, computerLetter):
  100. return i
  101.  
  102. # Block: Check if the player could win on next move
  103. for i in range(1, 10):
  104. copyBoard = board[:]
  105. if isEmpty(copyBoard, i):
  106. copyBoard[i] = playerLetter
  107. if checkWin(copyBoard, playerLetter):
  108. return i
  109.  
  110. # Random moves
  111. # Choose a random free corner
  112. move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
  113. if move != None:
  114. return move
  115.  
  116. # Choose center if free
  117. if isEmpty(board, 5):
  118. return 5
  119.  
  120. # Choose random free edge centre
  121. return chooseRandomMoveFromList(board, [2, 4, 6, 8])
  122.  
  123. if __name__ == "__main__":
  124. while True:
  125. board = [' '] + '1 2 3 4 5 6 7 8 9'.split()
  126. printBoard(board, None, True)
  127. board = [' '] * 10
  128. players = inputPlayerLetter()
  129. playerLetter, computerLetter = players
  130. turn = toss()
  131. print('The ' + turn + ' will go first. \nPress ENTER to continue.')
  132. raw_input()
  133. gameOver = False
  134.  
  135. while not gameOver:
  136. if turn == 'player':
  137. printBoard(board, players)
  138. move = inputPlayerMove(board)
  139. board[move] = playerLetter
  140.  
  141. if checkWin(board, playerLetter):
  142. printBoard(board, players)
  143. print('Congratulations! You have won the game!')
  144. gameOver = True
  145. else:
  146. if isBoardFull(board):
  147. printBoard(board, players)
  148. print('The game is a tie!')
  149. break
  150. else:
  151. turn = 'computer'
  152.  
  153. else:
  154. move = getComputerMove(board, players)
  155. board[move] = computerLetter
  156.  
  157. if checkWin(board, computerLetter):
  158. printBoard(board, players)
  159. print('The computer won the game.')
  160. gameOver = True
  161. else:
  162. if isBoardFull(board):
  163. printBoard(board, players)
  164. print('The game is a tie!')
  165. break
  166. else:
  167. turn = 'player'
  168.  
  169. if not playAgain():
  170. break
Add Comment
Please, Sign In to add comment