Advertisement
SMASIF

365 FINAL PROJECT

Dec 9th, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.98 KB | None | 0 0
  1. import random
  2. import pickle
  3. import itertools
  4.  
  5. def resetGame():
  6.    
  7.    
  8.     global base,play,count,finalResult,breaking,gameplay,player_lastmove,comp_lastmove
  9.    
  10.     base = ["0","1","2","3","4","5","6","7","8"] #Game board
  11.     play = []  
  12.     count = [0,1]
  13.     finalResult = "none"  
  14.     breaking = False
  15.     gameplay = ["n","playerturn","gamemode","default_game_name","difficulty"]
  16.     player_lastmove = []
  17.     comp_lastmove= []
  18.    
  19.        
  20. def returntoMenu():
  21.    
  22.     while True:
  23.         goback = input("Do you want to go back to main Menu? (y/n)\n")
  24.         if goback == "y":
  25.             StartGame()
  26.             break
  27.         elif goback == "n":
  28.             print("\n---------- GAME CLOSED ----------\n")
  29.             break          
  30.         else:
  31.             print("Invalid entry. Enter y or n only.")
  32.    
  33. def printgameBoard():
  34.    
  35.     print((base[0] + " | " + base[1] + " | " + base[2]).center(34))
  36.     print("-----------".center(34))
  37.     print((base[3] + " | " + base[4] + " | " + base[5]).center(34))
  38.     print("-----------".center(34))
  39.     print((base[6] + " | " + base[7] + " | " + base[8]).center(34))
  40.     print("\n")
  41.    
  42.  
  43. def gameMenu():
  44.    
  45.     print("-----------------------------------")
  46.     print(("TIC TAC TOE GAME\n"))
  47.     print("(1) Start Game ")
  48.     print("(2) Exit \n")
  49.     while True:      
  50.         try:
  51.             option = int(input("Select an option: "))
  52.             if option<=3 and option >0:
  53.                 print("-----------------------------------")
  54.                 return option
  55.             elif option == 4:
  56.                 return option
  57.             else:
  58.                 print("Invalid Option. Please try again.\n")
  59.                                      
  60.         except ValueError:
  61.             print("Invalid Option. Please try again.\n")
  62.  
  63.  
  64. def askMove(player):
  65.    
  66.     if player == 1:
  67.         string = "Player 1: "
  68.         number = 0
  69.     else:
  70.      print("Invalid Option. Please try again.\n")
  71.  
  72.     while True:
  73.         try:
  74.             selectedlocation = int(input(string+"Where do you want to place "+play[number]+"?\n"))
  75.             return selectedlocation
  76.             break
  77.         except ValueError:
  78.             print("Invalid entry.")
  79.             print("Only numbers should be entered.")
  80.             print("Please try again. \n")
  81.  
  82.  
  83.        
  84. def player1Move():
  85.    
  86.     while True:
  87.         selectedlocation = askMove(1)
  88.         if selectedlocation >=0 and selectedlocation <=8:
  89.             n = selectedlocation
  90.             if availability(n) == "y":
  91.                 base[n] = play[0]
  92.                 count[0] = count[0]+1
  93.                 player_lastmove.append(n)
  94.                 print("\n")
  95.                 break
  96.             else:
  97.                 print("It is not possible to place "+play[0]+" there.")
  98.                 print("Please try again. \n")
  99.            
  100.    
  101. def selectAI_level():
  102.    
  103.     print("Choose the difficulty level of computer: \n")
  104.     print("(1) Easy")
  105.     print("(2) Medium")
  106.     print("(3) Impossible")
  107.     while True:
  108.         try:
  109.             option = int(input("\nChoice: "))
  110.             if option == 1:
  111.                 gameplay[4] = "EASY"  
  112.                 return
  113.             elif option == 2:
  114.                 gameplay[4] = "MEDIUM"
  115.                 return
  116.             elif option == 3:
  117.                 gameplay[4] = "IMPOSSIBLE"
  118.                 return
  119.             else:
  120.                 print("Invalid Option. Please try again.")
  121.         except ValueError:
  122.             print("Invalid Option. Please try again.")
  123.  
  124. def x_or_o():
  125.    
  126.     while True:
  127.         selection = input("Player 1: Pick one x or o?\n")
  128.         if selection == "x":
  129.             play.append(selection)
  130.             play.append("o")
  131.             gameplay[1] = "p1"
  132.             break
  133.         elif selection == "o":
  134.             play.append(selection)
  135.             play.append("x")
  136.            
  137.             gameplay[1] = "comp"
  138.            
  139.             break
  140.         else:
  141.             print("Enter x or o in lower case only. \n")
  142.        
  143.        
  144.        
  145. def availability(n):
  146.    
  147.     if base[n] == "x" or base[n] == "o":
  148.         return "n"
  149.     else:
  150.         return "y"
  151.  
  152.    
  153.  
  154. def AI_corner():
  155.    
  156.     while True:
  157.         corners = [0,2,6,8]
  158.         move = corners[random.randint(0,3)]
  159.         if availability(move) == "y":
  160.             return move
  161.        
  162. def AI_Impossible():
  163.    
  164.    
  165.     if count[0]<=2: #when less than or equal to 2 moves played on board
  166.         if play[1]=="o":
  167.             if player_lastmove[0]!=4:
  168.                 return 4
  169.             else:
  170.                 move = AI_corner()
  171.                 return move
  172.         else:
  173.             if len(player_lastmove)==1 and availability(4) == "y":
  174.                 return 4
  175.             elif availability(4) == "y":
  176.                 return 4
  177.             else:
  178.                 move = AI_corner()
  179.                 return move
  180.            
  181.     if count[0]>2: #when greater than two moves played on board
  182.         for i in range(0,len(AI)):
  183.             (move1,move2,move3) = (AI[i])
  184.             if base[move1] == play[1] and base[move2] == play[1]: #Attacking
  185.                 if availability(move3)=="y":
  186.                     return move3
  187.  
  188.         for i in range(0,len(AI)):
  189.             (move1,move2,move3) = (AI[i])
  190.             if base[move1]==play[0] and base[move2] == play[0]:  #Defensive
  191.                 if availability(move3) == "y":
  192.                     return move3
  193.                
  194.         if count[0] == 3 and play[0] == "x": #to block any tricky play
  195.             if base[5] == "x" and (base[1] == "x" or base[0] == "x"):
  196.                 return 2
  197.             elif base[5] =="x" and base[7] == "x":
  198.                 return 8
  199.             elif base[1] == "x" and base[6] == "x":
  200.                 return 0
  201.             elif base[6] == "x" and base[5] == "x":
  202.                 return 8
  203.             elif comp_lastmove[0] == 4 and availability(3) == "y":
  204.                 return 3
  205.  
  206.         for i in range(0,len(AI)):
  207.             (move1,move2,move3) = (AI[i])
  208.             if base[move1] == play[0] and (move2 in [0,2,6,8]) and availability(move2)=="y": #to block any tricky play
  209.                 return move2
  210.            
  211.    
  212.         for i in range(0,len(AI)):
  213.             (move1,move2,move3) = (AI[i])
  214.             if move1 == play[1]:
  215.                 if availability(move2) == "y":
  216.                     return move2
  217.             else:
  218.                 while True:
  219.                     move = random.randint(0,8)
  220.                     if availability(move) == "y":
  221.                         return move
  222.  
  223. def AI_Easy():
  224.    
  225.     for i in range(0,len(AI)):
  226.         (move1,move2,move3) = (AI[i])
  227.         if base[move1] == play[1] and base[move2] == play[1]: #Attacking
  228.             if availability(move3)=="y":
  229.                 return move3
  230.     while True:
  231.         move = random.randint(0,8)
  232.         if availability(move) == "y":
  233.             return move
  234.  
  235. def AI_Medium():
  236.    
  237.     for i in range(0,len(AI)):
  238.         (move1,move2,move3) = (AI[i])
  239.         if base[move1] == play[1] and base[move2] == play[1]: #Attacking
  240.             if availability(move3)=="y":
  241.                 return move3
  242.            
  243.     for i in range(0,len(AI)):
  244.         (move1,move2,move3) = (AI[i])
  245.         if base[move1] == play[0] and base[move2] == play[0]: #Defense
  246.             if availability(move3)=="y":
  247.                 return move3
  248.         elif availability(move1) == "y" and move1 in [0,2,6,8]:
  249.             return move1
  250.  
  251.     while True:
  252.         move = random.randint(0,8)
  253.         if availability(move) == "y":
  254.             return move
  255.        
  256.        
  257. def computerMove():
  258.    
  259.     if gameplay[4] == "IMPOSSIBLE":
  260.         move = AI_Impossible()
  261.         base[move] = play[1]
  262.         comp_lastmove.append(move)
  263.         count[0] = count[0] + 1      
  264.     elif gameplay[4] == "MEDIUM":
  265.         move = AI_Medium()
  266.         base[move] = play[1]
  267.         count[0] = count[0]+1
  268.     else:
  269.         move = AI_Easy()
  270.         base[move] = play[1]
  271.         count[0] = count[0]+1
  272.        
  273.            
  274.  
  275. def compAI():
  276.    
  277.     global AI
  278.     winMoves = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(2,4,6),(0,4,8)]
  279.     PossibleWins = []
  280.     for i in range(0,len(winMoves)):
  281.         PossibleWins.append(list(itertools.permutations(winMoves[i])))
  282.        
  283.     AI = list(itertools.chain.from_iterable(PossibleWins))
  284.      
  285. def checkWin(n):
  286.    
  287.    
  288.     if base[0] == n and base[1] == n and base[2]==n:
  289.         return "y"
  290.     elif base[3] == n and base[4] == n and base[5]==n:
  291.         return "y"
  292.     elif base[6] == n and base[7] == n and base[8]==n:
  293.         return "y"
  294.     elif base[0] == n and base[3] == n and base[6]==n:
  295.         return "y"
  296.     elif base[1] == n and base[4] == n and base[7]==n:
  297.         return "y"
  298.     elif base[2] == n and base[5] == n and base[8]==n:
  299.         return "y"
  300.     elif base[2] == n and base[4] == n and base[6]==n:
  301.         return "y"
  302.     elif base[0] == n and base[4] == n and base[8]==n:
  303.         return "y"
  304.     elif count[0] == 9:
  305.         return "t"
  306.     else:
  307.         return "n"
  308.  
  309.  
  310. def Result(player):
  311.    
  312.     global breaking,finalResult
  313.     result = checkWin(player)
  314.     if result=="y":
  315.         finalResult = "won"
  316.         printgameBoard()
  317.         breaking = True
  318.        
  319.     elif result == "t":
  320.         printgameBoard()
  321.         finalResult = "tie"
  322.         breaking = True
  323.        
  324.     else:
  325.         pass
  326.  
  327.  
  328.  
  329.    
  330.  
  331.  
  332.  
  333.    
  334. def onePlayerGame():
  335.    
  336.     print(("  AI LEVEL: "+gameplay[4]+"\n").center(34))
  337.     compAI()
  338.     while count[0]<=9:
  339.         if gameplay[1] == "p1":
  340.             printgameBoard()
  341.             gameplay[1] = "p1"
  342.             player1Move()
  343.             Result(play[0])
  344.             if breaking == True:
  345.                 if finalResult == "tie":
  346.                     print(("It is a tie!").center(34))
  347.                 elif finalResult == "won":
  348.                     print(("Player 1 ("+play[0]+") wins!").center(34))
  349.                 print("\n--------- 1P GAME ENDED ---------\n")
  350.                 returntoMenu()
  351.                 break
  352.             else:
  353.                 gameplay[1] = "comp"
  354.         else:
  355.             gameplay[1] = "comp"
  356.             computerMove()
  357.             Result(play[1])
  358.             if breaking == True:
  359.                 if finalResult == "tie":
  360.                     print(("It is a tie!").center(34))
  361.                 elif finalResult == "won":
  362.                     print(("Computer ("+play[1]+") wins!").center(34))
  363.                 print("\n--------- 1P GAME ENDED ---------\n")
  364.                 returntoMenu()
  365.                 break
  366.             else:
  367.                 gameplay[1] = "p1"
  368.  
  369.  
  370.    
  371. def StartGame():
  372.    
  373.     option = gameMenu()
  374.     resetGame()
  375.     if option== 1:
  376.         gameplay[2] = "1p"
  377.         selectAI_level()
  378.         x_or_o()
  379.         print("\n--------- 1P GAME STARTED ---------\n")
  380.         onePlayerGame()
  381.                                        
  382.     else:
  383.         print("\n----------- TIC TAC TOE CLOSED -----------\n")
  384.  
  385.  
  386.  
  387. StartGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement