Advertisement
AyanUpadhaya

Tic Tac Toe Game in python

May 7th, 2021
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.99 KB | None | 0 0
  1. #Tic-tac-toe Man vs Ai game
  2.  
  3. #keyboard moves player
  4. #7-top left corner
  5. #8-top middle
  6. #9-top right corner
  7. #4-left side
  8. #5-middle
  9. #6-right
  10. #1-bottom left
  11. #2-bottom middle
  12. #3-bottom right
  13.  
  14. import random
  15.  
  16. #we need to draw board first
  17.  
  18. def drawBoard(board):
  19. #this function points out the board that it was passed
  20. #"board" is a list of 10 strings representing the board(ignore index 0)
  21.  
  22. print(board[7]+'|'+board[8]+'|'+board[9])
  23. print('-+-+-')
  24. print(board[4]+'|'+board[5]+'|'+board[6])
  25. print('-+-+-')
  26. print(board[1]+'|'+board[2]+'|'+board[3])
  27. print('-+-+-')
  28.  
  29. def inputPlayerLetter():
  30. #lets the player type which letter they want to be
  31. #returns a list with player's letter as the first item and the computer's letter as the second
  32.  
  33. letter=''
  34. while not(letter=='X' or letter=='O'):
  35. print('Do you want to be X or O:')
  36. letter=input().upper()
  37.  
  38. #the first element in the list is player's letter and second one is computer's letter
  39. if letter=='X':
  40. return['X','O']
  41. else:
  42. return['O','X']
  43.  
  44. def whoGoesFirst():
  45. #randomly choices which player goes first
  46.  
  47. if random.randint(0,1)==0:
  48. return 'computer'
  49. else:
  50. return 'player'
  51.  
  52. def makeMove(board,letter,move):
  53.  
  54. board[move]=letter
  55.  
  56. def isWinner(bo,le):
  57. #given a board to check if player wins returns true
  58. #bo for board and le- letter
  59.  
  60. return((bo[7]==le and bo[8]==le and bo[9]==le) or #accross top
  61. (bo[4]==le and bo[5]==le and bo[6]==le) or #Across the middle
  62. (bo[1]==le and bo[2]==le and bo[3]==le) or #Across the bottom
  63. (bo[7]==le and bo[4]==le and bo[1]==le) or #Across left side
  64. (bo[8]==le and bo[5]==le and bo[2]==le) or #Across the middle
  65. (bo[9]==le and bo[6]==le and bo[3]==le) or #Across the right side
  66. (bo[7]==le and bo[5]==le and bo[3]==le) or #Across the diagonal
  67. (bo[9]==le and bo[5]==le and bo[1]==le ))#Diagonal
  68.  
  69. def getBoardCopy(board):
  70. #make a copy of the board list and return it
  71.  
  72. boardCopy=[]
  73. for i in board:
  74. boardCopy.append(i)
  75. return boardCopy
  76.  
  77. def isSpaceFree(board,move):
  78. #return True if the passed move is free on the passed board
  79. return board[move]==' '
  80.  
  81. def getPlayerMove(board):
  82. #let the player enter their move
  83. move=' '
  84. while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,int(move)):
  85. print('What is your next move?(1-9)')
  86. move=input()
  87. return int(move)
  88. def chooseRandomMovesFromList(board,movesList):
  89. #returns a valid move from movesList
  90. #returns none if there is no valid moves
  91.  
  92. possibleMoves=[]
  93. for i in movesList:
  94. if isSpaceFree(board,i):
  95. possibleMoves.append(i)
  96.  
  97. if len(possibleMoves)!=0:
  98. return random.choice(possibleMoves)
  99. else:
  100. return None
  101.  
  102. def getComputersMove(board,computerLetter):
  103. #given a board and the computer's letter,determine where to move
  104. #and return that move
  105. if computerLetter=='X':
  106. playerletter='O'
  107. else:
  108. playerletter='X'
  109. #here is the algorithm for our Tic-Tac-Toe Ai:
  110. #first check if we can win in the next move
  111.  
  112. for i in range(1,10):
  113. boardCopy=getBoardCopy(board)
  114. if isSpaceFree(boardCopy,i):
  115. makeMove(boardCopy,computerLetter,i)
  116. if isWinner(boardCopy,computerLetter):
  117. return i
  118. #check if the player could win on their next move and block them
  119. for i in range(1,10):
  120. boardCopy=getBoardCopy(board)
  121. if isSpaceFree(boardCopy,i):
  122. makeMove(boardCopy,playerletter,i)
  123. if isWinner(boardCopy,playerletter):
  124. return i
  125. #try to take one of the corner if they are free
  126. move=chooseRandomMovesFromList(board,[1,3,7,9])
  127.  
  128. if move!=None:
  129. return move
  130.  
  131. #try to take the center if it is free.
  132.  
  133. if isSpaceFree(board,5):
  134. return 5
  135.  
  136. #move on one of the sides
  137.  
  138. return chooseRandomMovesFromList(board,[2,4,6,8])
  139.  
  140. def isBoardFull(board):
  141. #return true if every space on the board has been taken
  142. #else return false
  143.  
  144. for i in range(1,10):
  145. if isSpaceFree(board,i):
  146. return False
  147.  
  148. return True
  149.  
  150.  
  151.  
  152.  
  153.  
  154. print("Welcome to tic tac toe:")
  155.  
  156. #mainloop
  157. while True:
  158. #reset the board
  159. theBoard=[' ']*10
  160. playerletter,computerLetter=inputPlayerLetter()
  161. turn=whoGoesFirst()
  162.  
  163.  
  164. print('The '+turn+'will go first.')
  165.  
  166. gameIsPlaying=True
  167.  
  168. while gameIsPlaying:
  169. if turn=="player":
  170. #player's turn
  171. drawBoard(theBoard)
  172. move=getPlayerMove(theBoard)
  173. makeMove(theBoard,playerletter,move)
  174.  
  175. if isWinner(theBoard,playerletter):
  176. drawBoard(theBoard)
  177. print("Hurray you have won the game")
  178. break
  179. else:
  180. if isBoardFull(theBoard):
  181. drawBoard(theBoard)
  182. print("The game is a tie")
  183. break
  184. else:
  185. turn="computer"
  186. else:
  187. #computer's turn
  188. move=getComputersMove(theBoard,computerLetter)
  189. makeMove(theBoard,computerLetter,move)
  190.  
  191. if isWinner(theBoard,computerLetter):
  192. drawBoard(theBoard)
  193. print("The computer has beaten you")
  194. break
  195. else:
  196. if isBoardFull(theBoard):
  197. drawBoard(theBoard)
  198. print('The Game is a tie')
  199. break
  200. else:
  201. turn='player'
  202.  
  203. print("Do you want to play again(yes or no)")
  204. if not input().lower().startswith('y'):
  205. break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement