Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import pickle
- import itertools
- def resetGame():
- global base,play,count,finalResult,breaking,gameplay,player_lastmove,comp_lastmove
- base = ["0","1","2","3","4","5","6","7","8"] #Game board
- play = []
- count = [0,1]
- finalResult = "none"
- breaking = False
- gameplay = ["n","playerturn","gamemode","default_game_name","difficulty"]
- player_lastmove = []
- comp_lastmove= []
- def returntoMenu():
- while True:
- goback = input("Do you want to go back to main Menu? (y/n)\n")
- if goback == "y":
- StartGame()
- break
- elif goback == "n":
- print("\n---------- GAME CLOSED ----------\n")
- break
- else:
- print("Invalid entry. Enter y or n only.")
- def printgameBoard():
- print((base[0] + " | " + base[1] + " | " + base[2]).center(34))
- print("-----------".center(34))
- print((base[3] + " | " + base[4] + " | " + base[5]).center(34))
- print("-----------".center(34))
- print((base[6] + " | " + base[7] + " | " + base[8]).center(34))
- print("\n")
- def gameMenu():
- print("-----------------------------------")
- print(("TIC TAC TOE GAME\n"))
- print("(1) Start Game ")
- print("(2) Exit \n")
- while True:
- try:
- option = int(input("Select an option: "))
- if option<=3 and option >0:
- print("-----------------------------------")
- return option
- elif option == 4:
- return option
- else:
- print("Invalid Option. Please try again.\n")
- except ValueError:
- print("Invalid Option. Please try again.\n")
- def askMove(player):
- if player == 1:
- string = "Player 1: "
- number = 0
- else:
- print("Invalid Option. Please try again.\n")
- while True:
- try:
- selectedlocation = int(input(string+"Where do you want to place "+play[number]+"?\n"))
- return selectedlocation
- break
- except ValueError:
- print("Invalid entry.")
- print("Only numbers should be entered.")
- print("Please try again. \n")
- def player1Move():
- while True:
- selectedlocation = askMove(1)
- if selectedlocation >=0 and selectedlocation <=8:
- n = selectedlocation
- if availability(n) == "y":
- base[n] = play[0]
- count[0] = count[0]+1
- player_lastmove.append(n)
- print("\n")
- break
- else:
- print("It is not possible to place "+play[0]+" there.")
- print("Please try again. \n")
- def selectAI_level():
- print("Choose the difficulty level of computer: \n")
- print("(1) Easy")
- print("(2) Medium")
- print("(3) Impossible")
- while True:
- try:
- option = int(input("\nChoice: "))
- if option == 1:
- gameplay[4] = "EASY"
- return
- elif option == 2:
- gameplay[4] = "MEDIUM"
- return
- elif option == 3:
- gameplay[4] = "IMPOSSIBLE"
- return
- else:
- print("Invalid Option. Please try again.")
- except ValueError:
- print("Invalid Option. Please try again.")
- def x_or_o():
- while True:
- selection = input("Player 1: Pick one x or o?\n")
- if selection == "x":
- play.append(selection)
- play.append("o")
- gameplay[1] = "p1"
- break
- elif selection == "o":
- play.append(selection)
- play.append("x")
- gameplay[1] = "comp"
- break
- else:
- print("Enter x or o in lower case only. \n")
- def availability(n):
- if base[n] == "x" or base[n] == "o":
- return "n"
- else:
- return "y"
- def AI_corner():
- while True:
- corners = [0,2,6,8]
- move = corners[random.randint(0,3)]
- if availability(move) == "y":
- return move
- def AI_Impossible():
- if count[0]<=2: #when less than or equal to 2 moves played on board
- if play[1]=="o":
- if player_lastmove[0]!=4:
- return 4
- else:
- move = AI_corner()
- return move
- else:
- if len(player_lastmove)==1 and availability(4) == "y":
- return 4
- elif availability(4) == "y":
- return 4
- else:
- move = AI_corner()
- return move
- if count[0]>2: #when greater than two moves played on board
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if base[move1] == play[1] and base[move2] == play[1]: #Attacking
- if availability(move3)=="y":
- return move3
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if base[move1]==play[0] and base[move2] == play[0]: #Defensive
- if availability(move3) == "y":
- return move3
- if count[0] == 3 and play[0] == "x": #to block any tricky play
- if base[5] == "x" and (base[1] == "x" or base[0] == "x"):
- return 2
- elif base[5] =="x" and base[7] == "x":
- return 8
- elif base[1] == "x" and base[6] == "x":
- return 0
- elif base[6] == "x" and base[5] == "x":
- return 8
- elif comp_lastmove[0] == 4 and availability(3) == "y":
- return 3
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if base[move1] == play[0] and (move2 in [0,2,6,8]) and availability(move2)=="y": #to block any tricky play
- return move2
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if move1 == play[1]:
- if availability(move2) == "y":
- return move2
- else:
- while True:
- move = random.randint(0,8)
- if availability(move) == "y":
- return move
- def AI_Easy():
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if base[move1] == play[1] and base[move2] == play[1]: #Attacking
- if availability(move3)=="y":
- return move3
- while True:
- move = random.randint(0,8)
- if availability(move) == "y":
- return move
- def AI_Medium():
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if base[move1] == play[1] and base[move2] == play[1]: #Attacking
- if availability(move3)=="y":
- return move3
- for i in range(0,len(AI)):
- (move1,move2,move3) = (AI[i])
- if base[move1] == play[0] and base[move2] == play[0]: #Defense
- if availability(move3)=="y":
- return move3
- elif availability(move1) == "y" and move1 in [0,2,6,8]:
- return move1
- while True:
- move = random.randint(0,8)
- if availability(move) == "y":
- return move
- def computerMove():
- if gameplay[4] == "IMPOSSIBLE":
- move = AI_Impossible()
- base[move] = play[1]
- comp_lastmove.append(move)
- count[0] = count[0] + 1
- elif gameplay[4] == "MEDIUM":
- move = AI_Medium()
- base[move] = play[1]
- count[0] = count[0]+1
- else:
- move = AI_Easy()
- base[move] = play[1]
- count[0] = count[0]+1
- def compAI():
- global AI
- 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)]
- PossibleWins = []
- for i in range(0,len(winMoves)):
- PossibleWins.append(list(itertools.permutations(winMoves[i])))
- AI = list(itertools.chain.from_iterable(PossibleWins))
- def checkWin(n):
- if base[0] == n and base[1] == n and base[2]==n:
- return "y"
- elif base[3] == n and base[4] == n and base[5]==n:
- return "y"
- elif base[6] == n and base[7] == n and base[8]==n:
- return "y"
- elif base[0] == n and base[3] == n and base[6]==n:
- return "y"
- elif base[1] == n and base[4] == n and base[7]==n:
- return "y"
- elif base[2] == n and base[5] == n and base[8]==n:
- return "y"
- elif base[2] == n and base[4] == n and base[6]==n:
- return "y"
- elif base[0] == n and base[4] == n and base[8]==n:
- return "y"
- elif count[0] == 9:
- return "t"
- else:
- return "n"
- def Result(player):
- global breaking,finalResult
- result = checkWin(player)
- if result=="y":
- finalResult = "won"
- printgameBoard()
- breaking = True
- elif result == "t":
- printgameBoard()
- finalResult = "tie"
- breaking = True
- else:
- pass
- def onePlayerGame():
- print((" AI LEVEL: "+gameplay[4]+"\n").center(34))
- compAI()
- while count[0]<=9:
- if gameplay[1] == "p1":
- printgameBoard()
- gameplay[1] = "p1"
- player1Move()
- Result(play[0])
- if breaking == True:
- if finalResult == "tie":
- print(("It is a tie!").center(34))
- elif finalResult == "won":
- print(("Player 1 ("+play[0]+") wins!").center(34))
- print("\n--------- 1P GAME ENDED ---------\n")
- returntoMenu()
- break
- else:
- gameplay[1] = "comp"
- else:
- gameplay[1] = "comp"
- computerMove()
- Result(play[1])
- if breaking == True:
- if finalResult == "tie":
- print(("It is a tie!").center(34))
- elif finalResult == "won":
- print(("Computer ("+play[1]+") wins!").center(34))
- print("\n--------- 1P GAME ENDED ---------\n")
- returntoMenu()
- break
- else:
- gameplay[1] = "p1"
- def StartGame():
- option = gameMenu()
- resetGame()
- if option== 1:
- gameplay[2] = "1p"
- selectAI_level()
- x_or_o()
- print("\n--------- 1P GAME STARTED ---------\n")
- onePlayerGame()
- else:
- print("\n----------- TIC TAC TOE CLOSED -----------\n")
- StartGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement