Advertisement
SMASIF

Tic Tac Toe *saved games cleared

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