Advertisement
pawlack

tictactoe with minmax

Jan 21st, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.65 KB | None | 0 0
  1.  
  2. #another tic tac toe game
  3. import random
  4. from random import randint
  5. #gameboard interface
  6.  
  7. gameboard = [[" "] * 3, [" "] * 3, [" "] * 3] # 2d Array
  8. aigameboard = [[" "] * 3, [" "] * 3, [" "] * 3] # 2d Array for ai minmax sim
  9. input_var1 = [["a1", "b1", "c1"], ["a2", "b2", "c2"], ["a3", "b3", "c3"]]
  10. available_moves = ["a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3"]
  11. potential_moves = ["a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3"] #for minmax use
  12. rows = 3
  13. columns = 3
  14. player_symbols = ["_", "X", "O"]
  15. current_player = 1
  16.  
  17. def end_game():
  18.  
  19.     global gameboard
  20.     global aigameboard
  21.     global potential_moves
  22.     global available_moves
  23.     global current_player
  24.  
  25.     print("We have a winner ", "Player ", current_player, " has won!")
  26.     draw_gameboard()
  27.  
  28.     replay = input("Do you want to play again? Y/N: ")
  29.  
  30.     if replay == "Y" or replay == "y":
  31.         gameboard = [[" "] * 3, [" "] * 3, [" "] * 3] # 2d Array
  32.         aigameboard = [[" "] * 3, [" "] * 3, [" "] * 3]
  33.         available_moves = ["a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3"]
  34.         potential_moves = ["a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3"]
  35.         current_player = 1
  36.         main_game_loop(False)
  37.    
  38.  
  39.     else:
  40.         quit()
  41.  
  42. def draw_gameboard(): #this is our game output
  43.     print("    A    B    C")
  44.     for i in range(len(gameboard)):
  45.         print(i+1, (gameboard[i]))
  46.  
  47. def draw_fake_gameboard(board): #this is debug tool
  48.     print("    A    B    C <- fake ai gameboard")
  49.     for i in range(len(board)):
  50.         print(i+1, (board[i]))
  51.  
  52. def get_player_input():
  53.     print("It's your turn, proper input example is 'a3', or 'b1'. Enter 'x' to quit")
  54.     pos = input("Enter position you want to take:")
  55.     if pos == "x":
  56.         quit()
  57.     return pos
  58.  
  59. def get_ai_input():
  60.     global aigameboard
  61.     global gameboard
  62.     global potential_moves
  63.     global available_moves
  64.     score = []
  65.  
  66.     for i in range(len(available_moves)):
  67.         score.append(mini_max(available_moves[i], aigameboard, True))
  68.         aigameboard = gameboard
  69.        
  70.    
  71.     print(score)
  72.     pos = available_moves[score.index(max(score))]
  73.  
  74.  
  75.     #pos = available_moves[randint(0, (len(available_moves))-1)]
  76.     return pos
  77.  
  78. def mini_max(position, board, isMaximizing):
  79.  
  80.     global input_var1
  81.     global potential_moves
  82.  
  83.     score = 0
  84.     scores = []
  85.     winner = 3
  86.     probed_position_x = 0
  87.     probed_position_y = 0
  88.     player = 1
  89.     value = 0
  90.     position_index = 0
  91.     internal_board = board
  92.     next_player = not isMaximizing
  93.  
  94.     #draw_fake_gameboard(board)
  95.     #print(position)
  96.  
  97.     if isMaximizing == True:
  98.         player = 2
  99.         value = 1
  100.     else:
  101.         player = 1
  102.         value = -1 #we wil multiply check for winners by value to get us -1 in case of minimizing
  103.  
  104.     for x in range(len(input_var1)):
  105.         for y in range(len(input_var1[x])):
  106.             if input_var1[x][y] == position:
  107.                 board[x][y] = player_symbols[player]
  108.                 probed_position_x = x
  109.                 probed_position_y = y
  110.  
  111.     position_index = potential_moves.index(position)
  112.     potential_moves.remove(position)
  113.     winner =  check_for_winners(board, potential_moves)
  114.     if winner == 1 or winner == 0:
  115.         #there is a winner here
  116.         score = winner*value
  117.         board[probed_position_x][probed_position_y] = " "
  118.         potential_moves.insert(position_index, position)
  119.         return score
  120.     else:
  121.         for i in range(len(potential_moves)):
  122.             scores.append(mini_max(potential_moves[i], internal_board, next_player))
  123.             internal_board = board
  124.         if isMaximizing:
  125.             score = min(scores)
  126.         else:
  127.             score = max(scores)
  128.  
  129.         board[probed_position_x][probed_position_y] = " "
  130.         potential_moves.insert(position_index, position)
  131.  
  132.         return score
  133.        
  134.  
  135.  
  136.  
  137.  
  138.  
  139. def update_game(player_number):
  140.     global gameboard
  141.     global input_var1
  142.     global current_player
  143.  
  144.     if player_number == 1:
  145.         pos = get_player_input()
  146.     else:
  147.         pos = get_ai_input()
  148.  
  149.     if pos in available_moves:
  150.         available_moves.remove(pos)
  151.         potential_moves.remove(pos)
  152.  
  153.         for x in range(len(input_var1)):
  154.             for y in range(len(input_var1[x])):
  155.                 if input_var1[x][y] == pos:
  156.                     gameboard[x][y] = player_symbols[player_number]
  157.                     print(" ")
  158.                     print("Player", player_number, "move: ")
  159.     else:
  160.         print("this position is invalid or already taken")
  161.         update_game(player_number)
  162.  
  163.            
  164. def check_for_winners(gameboard_state, moves):
  165.     column_check = []
  166. #horizontal
  167.     for x in range(len(gameboard_state[0])):
  168.         if gameboard_state[x].count(gameboard_state[x][0]) == len(gameboard_state[x]) and gameboard_state[x][0] != " ":
  169.             #there is horizontal winner
  170.             return 1
  171. #vertical
  172.     for i in range(len(gameboard_state)):
  173.         for row in gameboard_state:
  174.             column_check.append(row[i])
  175.         if column_check.count(column_check[0]) == len(column_check) and column_check[0] != " ":
  176.             #there is vertical winner
  177.             return 1
  178.         else:
  179.             column_check.clear()
  180. #diagonal right
  181.     for counter, row in enumerate(gameboard_state):
  182.         column_check.append(row[counter])
  183.     if column_check.count(column_check[0]) == len(column_check) and column_check[0] != " ":
  184.             #there is diagonal winner
  185.             return 1
  186.     else:
  187.         column_check.clear()
  188.  
  189. #diagonal left
  190.     for counter, row in enumerate(gameboard_state):
  191.         column_check.append(row[-counter-1])
  192.     if column_check.count(column_check[0]) == len(column_check) and column_check[0] != " ":
  193.             #there is diagonal winner
  194.             return 1
  195.     else:
  196.         column_check.clear()
  197.  
  198. #check for TIE
  199.     if len(moves) == 0:
  200.         return 0
  201.  
  202.     return -3
  203.  
  204. def change_player():
  205.     global current_player
  206.  
  207.     if current_player == 1:
  208.         current_player = 2
  209.     else:
  210.         current_player = 1
  211.  
  212. def main_game_loop(game_ended):
  213.     global aigameboard
  214.     while game_ended == False:
  215.        
  216.         draw_gameboard()
  217.         update_game(current_player)
  218.         if check_for_winners(gameboard, available_moves) != -3:
  219.             game_ended = True
  220.         else:
  221.             aigameboard = gameboard
  222.             change_player()
  223.  
  224.     else:
  225.         end_game()
  226.  
  227. main_game_loop(False)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement