Advertisement
sajid006

AI Game

Nov 17th, 2021
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.96 KB | None | 0 0
  1. from math import inf as infinity
  2. board = [['X', 'X', 'X'],
  3. [' ', ' ', ' '],
  4. ['O', 'O', 'O']]
  5.  
  6.  
  7. def replacer(s, newstring, index, nofail=False):
  8. # raise an error if index is outside of the string
  9. if not nofail and index not in range(len(s)):
  10. raise ValueError("index outside given string")
  11.  
  12. # if not erroring, but the index is still not in the correct range..
  13. if index < 0: # add it to the beginning
  14. return newstring + s
  15. if index > len(s): # add it to the end
  16. return s + newstring
  17.  
  18. # insert the new string between "slices" of the original
  19. return s[:index] + newstring + s[index + 1:]
  20.  
  21.  
  22.  
  23. str = "| |--| |--| |\n | \ | / | \n | \ | / | \n| |--| |--| |\n | / | \ | \n | / | \ | \n| |--| |--| |\n"
  24. values = [1,6,11,43,48,53,85,90,95]
  25. '''
  26. valid_moves = dict([(1, [2,4,5]), (2, [1,3,5]) , (3, [2,5,6]) , (4, [1,5,7]) , (5, [1,2,3,4,6,7,8,9]) ,
  27. (6, [3,5,9]) , (7, [4,5,8]), (8, [5,7,9]) , (9, [5,6,8])
  28. ])
  29. '''
  30. valid_moves = dict([(0, [1,3,4]), (1, [0,2,4]) , (2, [1,4,5]) , (3, [0,4,6]) , (4, [0,1,2,3,5,6,7,8]) ,
  31. (5, [2,4,8]) , (6, [3,4,7]), (7, [4,6,8]) , (8, [4,5,7])
  32. ])
  33.  
  34.  
  35. print(valid_moves)
  36.  
  37. def print_board():
  38. global str
  39. for i in range(0,3):
  40. for j in range(0,3):
  41. str = replacer(str, board[i][j],values[3*i+j])
  42. print(str)
  43.  
  44.  
  45. def take_input():
  46. pos_old, pos_new = input("Enter old and new Position (ex:8 5) : ").split(' ')
  47. try:
  48. pos_old = int(pos_old) - 1
  49. pos_new = int(pos_new) - 1
  50.  
  51. if(pos_old>=0 and pos_old<9 and pos_new>=0 and pos_new<9):
  52. return pos_old, pos_new
  53. else:
  54. return 0,0
  55. except:
  56. print("Invalid Input")
  57. return 0,0
  58.  
  59. def place_player(pos_old, pos_new, player):
  60. row_old = pos_old // 3
  61. column_old = pos_old % 3
  62.  
  63. row_new = pos_new // 3
  64. column_new = pos_new % 3
  65. if(board[row_old][column_old] == player and board[row_new][column_new]==" " and pos_new in valid_moves[pos_old]):
  66. board[row_old][column_old] = " "
  67. board[row_new][column_new] = player
  68. return 1
  69. else:
  70. print("Invalid Move")
  71. return 0
  72.  
  73. def check_row(i):
  74. x = 0
  75. o = 0
  76. for j in range(3):
  77. if board[i][j] == 'X':
  78. if(i==0):
  79. continue
  80. x += 1
  81.  
  82. if board[i][j] == 'O':
  83. if(i==2):
  84. continue
  85. o += 1
  86. if x == 3:
  87. print_board()
  88. print("X won")
  89. quit()
  90.  
  91. elif o == 3:
  92. print_board()
  93. print("O won")
  94. quit()
  95.  
  96. def check_column(j):
  97. x = 0
  98. o = 0
  99. for i in range(3):
  100.  
  101. if board[i][j] == 'X':
  102. x += 1
  103.  
  104. if board[i][j] == 'O':
  105. o += 1
  106.  
  107. if x == 3:
  108. print_board()
  109. print("X won")
  110. quit()
  111.  
  112. elif o == 3:
  113. print_board()
  114. print("O won")
  115. quit()
  116.  
  117. def check_diagonals(a, b, c):
  118. var = [a, b, c]
  119. x = 0
  120. o = 0
  121. for i in var:
  122. if i == 'X':
  123. x += 1
  124.  
  125. if i == 'O':
  126. o += 1
  127.  
  128. if x == 3:
  129. print_board()
  130. print("X won")
  131. quit()
  132.  
  133. elif o == 3:
  134. print_board()
  135. print("O won")
  136. quit()
  137. #Checking which player 'X'/'O' win in a board.
  138. #returns true or False
  139. def checkWhichPlayerWin(player):
  140. #cnt = 0
  141. for i in range(0,3):
  142. if i==0 and player=='X':
  143. continue
  144. if i==2 and player=='O':
  145. continue
  146. cnt = 0
  147. for j in range(0,3):
  148. if board[i][j] == player:
  149. cnt =cnt+1
  150. if cnt==3:
  151. return True
  152. for i in range(0,3):
  153. cnt = 0
  154. for j in range(0,3):
  155. if board[j][i] == player:
  156. cnt =cnt+1
  157. if cnt==3:
  158. return True
  159. if(board[0][0]==player and board[0][0]==board[1][1] and board[0][0]==board[2][2]):
  160. return True
  161. if(board[0][2]==player and board[0][2]==board[1][1] and board[0][2]==board[2][0]):
  162. return True
  163. return False
  164.  
  165. def best_move(ai):
  166. bestScore = -infinity
  167. bestMove_old, bestMove_new = 0,0
  168. for i in range(0,3):
  169. for j in range(0,3):
  170. if(board[i][j]==ai):
  171. pos_old = 3*i + j
  172. #print(pos_old)
  173. for pos_new in valid_moves[pos_old]:
  174. row_old = pos_old//3
  175. column_old = pos_old%3
  176. row_new = pos_new//3
  177. column_new = pos_new%3
  178. if(board[row_new][column_new]==" "):
  179. board[row_old][column_old] = " "
  180. board[row_new][column_new] = ai
  181. score = minimax(board,0,False)
  182. if(score>bestScore):
  183. bestScore = score
  184. bestMove_old, bestMove_new = pos_old, pos_new
  185. board[row_old][column_old] = ai
  186. board[row_new][column_new] = " "
  187. return bestMove_old, bestMove_new
  188.  
  189. def minimax(board, depth, isMaximizing):
  190. #return 1
  191. #print(depth)
  192. human = 'O'
  193. ai ='X'
  194. #return 1
  195. if (checkWhichPlayerWin('X')):
  196. #print("ovi")
  197. #print_board()
  198. return 10
  199. elif (checkWhichPlayerWin('O')):
  200. return -10
  201. #print_board()
  202. #return 1
  203.  
  204. if depth == 8:
  205. return 0
  206. if(isMaximizing):
  207. #finding valid moves
  208. bestScore = -infinity
  209. #bestMove_old, bestMove_new = 0,0
  210. for i in range(0,3):
  211. for j in range(0,3):
  212. if(board[i][j]==ai):
  213. pos_old = 3*i + j
  214. for pos_new in valid_moves[pos_old]:
  215. row_old = pos_old//3
  216. column_old = pos_old%3
  217. row_new = pos_new//3
  218. column_new = pos_new%3
  219. if(board[row_new][column_new]==" "):
  220. board[row_old][column_old] = " "
  221. board[row_new][column_new] = ai
  222. score = minimax(board,depth+1,False)
  223. if(score>bestScore):
  224. bestScore = score
  225. #bestMove_old, bestMove_new = pos_old, pos_new
  226. board[row_old][column_old] = ai
  227. board[row_new][column_new] = " "
  228. return bestScore
  229. else:
  230. bestScore = infinity
  231. #bestMove_old, bestMove_new = 0,0
  232. for i in range(0,3):
  233. for j in range(0,3):
  234. if(board[i][j]==human):
  235. pos_old = 3*i + j
  236. for pos_new in valid_moves[pos_old]:
  237. row_old = pos_old//3
  238. column_old = pos_old%3
  239. row_new = pos_new//3
  240. column_new = pos_new%3
  241. if(board[row_new][column_new]==" "):
  242. board[row_old][column_old] = " "
  243. board[row_new][column_new] = human
  244. score = minimax(board,depth+1,True)
  245. if(score<bestScore):
  246. bestScore = score
  247. #bestMove_old, bestMove_new = pos_old, pos_new
  248. board[row_old][column_old] = human
  249. board[row_new][column_new] = " "
  250. return bestScore
  251.  
  252. '''
  253. def main():
  254. print_board()
  255. print(checkWhichPlayerWin('X'))
  256. pos_old,pos_new = best_move('X')
  257. #print(pos_old,pos_new)
  258. place_player(pos_old, pos_new,'X')
  259. print_board()
  260.  
  261. '''
  262.  
  263. def main():
  264. print_board()
  265. smove= input("Want to start first move? (yes/no): ")
  266. if(smove=='yes' or smove=='Yes' or smove=='YES' or smove=='y'):
  267. p = ['O','X']
  268. else:
  269. p = ['X','O']
  270. '''
  271. print_board()
  272. player = 'O'
  273. print("Player "+player+"(your's) Turn")
  274. pos_old,pos_new = take_input()
  275. place_player(pos_old, pos_new,player)
  276. '''
  277. global game_on
  278. game_on = True
  279. count = 0
  280. while game_on:
  281. if count % 2 == 0:
  282. player = p[0]
  283. else:
  284. player = p[1]
  285. print_board()
  286. print("Player "+player+"'s Turn")
  287. if player=='X':
  288. pos_old,pos_new = best_move(player)
  289. else:
  290. pos_old,pos_new = take_input()
  291. count += place_player(pos_old, pos_new,player)
  292. #print(checkWhichPlayerWin(player))
  293. for j in range(3):
  294. check_column(j)
  295. check_row(j)
  296. check_diagonals(board[0][0], board[1][1], board[2][2])
  297. check_diagonals(board[0][2], board[1][1], board[2][0])
  298.  
  299.  
  300. if __name__ == '__main__':
  301. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement