Advertisement
SigmaBoy456

python tictactoe (e/m/h)

Mar 2nd, 2025
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.07 KB | None | 0 0
  1. from random import randint
  2. from math import inf
  3.  
  4. class tictactoe:
  5.     def __init__(self):
  6.         self.Board = [
  7.             [1, 2, 3],
  8.             [4, 5, 6],
  9.             [7, 8, 9]
  10.         ]
  11.         self.Player = None
  12.         self.AI = None
  13.         self.PrevPlayed = None
  14.         self.Turn = None
  15.         self.Diff = None
  16.     def DrawBoard(self):
  17.         print("-"*14)
  18.         for i in range(3):
  19.             print(f"| {self.Board[i][0]} | {self.Board[i][1]} | {self.Board[i][2]} | ")
  20.         print("-"*14)
  21.     def ChooseTeam(self):
  22.         while True:
  23.             n = input("Choose You Team (O or X) : ").upper()
  24.             vaildTeam = ["O", "X"]
  25.             if n not in vaildTeam:
  26.                 print("Invaild Team")
  27.                 continue
  28.             self.Player = n
  29.             self.AI = "O" if n == "X" else "X"
  30.             break
  31.     def SelectDiff(self):
  32.         while True:
  33.             n = input("Select You Diff for AI\ne: Easy\nm: Meduim\nh: Hard : ").lower()
  34.             vaildDiff = ["e", "m", "h"]
  35.             if n not in vaildDiff:
  36.                 print("Invaild Diff")
  37.                 continue
  38.             self.Diff = n
  39.             break
  40.     def StartTurn(self):
  41.         n = randint(1, 2)
  42.         self.Turn = self.Player if n == 1 else self.AI
  43.     def IsTie(self) -> bool:
  44.         return all([type(self.Board[i][j]) != int for i in range(3) for j in range(3)])
  45.     def IsGameOver(self) -> bool:
  46.         for i in range(3):
  47.             if self.Board[i][0] == self.Board[i][1] and self.Board[i][1] == self.Board[i][2]:
  48.                 return True
  49.             elif self.Board[0][i] == self.Board[1][i] and self.Board[1][i] == self.Board[2][i]:
  50.                 return True
  51.         if self.Board[0][0] == self.Board[1][1] and self.Board[1][1] == self.Board[2][2]:
  52.             return True
  53.         elif self.Board[0][2] == self.Board[1][1] and self.Board[1][1] == self.Board[2][0]:
  54.             return True
  55.         return False
  56.     def IsAbleFill(self, row : int, col : int) -> bool:
  57.         return type(self.Board[row][col]) == int
  58.     def PlayerFill(self, row : int, col : int):
  59.         if self.IsAbleFill(row, col):
  60.             self.Board[row][col] = self.Player
  61.         else:
  62.             return
  63.     # AI Algorithm/ Hard Mode/ Meduim Mode/ Easy Mode
  64.     def EasyAIFill(self):
  65.         ava = [[i, j] for i in range(3) for j in range(3) if self.IsAbleFill(i, j)]
  66.         avaSpot = ava[randint(0, len(ava)-1)]
  67.         self.Board[avaSpot[0]][avaSpot[1]] = self.AI
  68.     def FindAvaSpot(self, symbol : str):
  69.         for i in range(3):
  70.             if self.Board[i][0] == symbol and self.Board[i][1] == symbol and self.IsAbleFill(i, 2):
  71.                 return [i, 2]
  72.             elif self.Board[i][2] == symbol and self.Board[i][1] == symbol and self.IsAbleFill(i, 0):
  73.                 return [i, 0]
  74.             elif self.Board[0][i] == symbol and self.Board[1][i] == symbol and self.IsAbleFill(2, i):
  75.                 return [2, i]
  76.             elif self.Board[2][i] == symbol and self.Board[1][i] == symbol and self.IsAbleFill(0, i):
  77.                 return [0, i]
  78.             elif self.Board[i][0] == symbol and self.Board[i][2] == symbol and self.IsAbleFill(i, 1):
  79.                 return [i, 1]
  80.             elif self.Board[0][i] == symbol and self.Board[2][i] == symbol and self.IsAbleFill(1, i):
  81.                 return [1, i]
  82.         if self.Board[0][0] == symbol and self.Board[1][1] == symbol and self.IsAbleFill(2, 2):
  83.             return [0, 0]
  84.         elif self.Board[2][2] == symbol and self.Board[1][1] == symbol and self.Board[0][0]:
  85.             return [2, 2]
  86.         elif self.Board[0][2] == symbol and self.Board[1][1] == symbol and self.IsAbleFill(2, 0):
  87.             return [2, 0]
  88.         elif self.Board[2][0] == symbol and self.Board[1][1] == symbol and self.IsAbleFill(0, 2):
  89.             return [0, 2]
  90.         return []
  91.     def MiniMaxCheckWinner(self) -> str:
  92.         for i in range(3):
  93.             if self.Board[i][0] == self.Board[i][1] and self.Board[i][1] == self.Board[i][2]:
  94.                 return self.Board[i][0]
  95.             elif self.Board[0][i] == self.Board[1][i] and self.Board[1][i] == self.Board[2][i]:
  96.                 return self.Board[0][i]
  97.         if self.Board[0][0] == self.Board[1][1] and self.Board[2][2]:
  98.             return self.Board[0][0]
  99.         elif self.Board[0][2] == self.Board[1][1] and self.Board[2][0]:
  100.             return self.Board[0][2]
  101.         return None
  102.     def MiniMax(self, ismaxing : bool) -> int:
  103.         if self.MiniMaxCheckWinner() == self.AI:
  104.             return 1
  105.         if self.MiniMaxCheckWinner() == self.Player:
  106.             return -1
  107.         if self.IsTie():
  108.             return 0
  109.         if ismaxing:
  110.             maxscore = -inf
  111.             for i in range(3):
  112.                 for j in range(3):
  113.                     if self.IsAbleFill:
  114.                         temp = self.Board[i][j]
  115.                         self.Board[i][j] = self.AI
  116.                         score = self.MiniMax(False)
  117.                         maxscore = max(score, maxscore)
  118.                         self.Board[i][j] = temp
  119.             return maxscore
  120.         else:
  121.             minscore = inf
  122.             for i in range(3):
  123.                 for j in range(3):
  124.                     if self.IsAbleFill(i, j):
  125.                         temp = self.Board[i][j]
  126.                         self.Board[i][j] = self.AI
  127.                         score = self.MiniMax(True)
  128.                         minscore = min(score, minscore)
  129.                         self.Board[i][j] = temp
  130.             return minscore
  131.     def AIFill(self):
  132.         match self.Diff:
  133.             case "e":
  134.                 self.EasyAIFill()
  135.             case "m":
  136.                 WinSpot = self.FindAvaSpot(self.AI)
  137.                 if WinSpot:
  138.                     self.Board[WinSpot[0]][WinSpot[1]] = self.AI
  139.                     return
  140.                 BlockSpot = self.FindAvaSpot(self.Player)
  141.                 if BlockSpot:
  142.                     self.Board[BlockSpot[0]][BlockSpot[1]] = self.AI
  143.                     return
  144.                 for i in range(3):
  145.                     for j in range(3):
  146.                         if self.IsAbleFill(i, j):
  147.                             self.Board[i][j] = self.AI
  148.                             return
  149.             case "h":
  150.                 bestscore = -inf
  151.                 bestfill = None
  152.                 for i in range(3):
  153.                     for j in range(3):
  154.                         if self.IsAbleFill(i, j):
  155.                             temp = self.Board[i][j]
  156.                             self.Board[i][j] = self.AI
  157.                             score = self.MiniMax(False)
  158.                             if score > bestscore:
  159.                                 bestscore = score
  160.                                 bestfill = [i, j]
  161.                             self.Board[i][j] = temp
  162.                 if bestfill:
  163.                     self.Board[bestfill[0]][bestfill[1]] = self.AI
  164.     def AutoPlayRound(self):
  165.         match self.Turn:
  166.             case self.Player:
  167.                 while True:
  168.                     row, col = None, None
  169.                     plrcin = int(input(f"Player Turn! Currently Player is : {self.Player}\n Choose Board to Fill in From 1-9\n input Here : "))
  170.                     if plrcin > 9 or plrcin < 1 or not plrcin:
  171.                         print("invaild input")
  172.                         continue
  173.                     if plrcin <= 3:
  174.                         row, col = 0, plrcin - 1
  175.                         if not self.IsAbleFill(row, col):
  176.                             print("Board Already Filled Choose Another To Fill")
  177.                             continue
  178.                         self.PlayerFill(row, col)
  179.                         break
  180.                     elif plrcin <= 6:
  181.                         row, col = 1, plrcin - 4
  182.                         if not self.IsAbleFill(row, col):
  183.                             print("Board Already Filled Choose Another To Fill")
  184.                             continue
  185.                         self.PlayerFill(row, col)
  186.                         break
  187.                     elif plrcin <= 9:
  188.                         row, col = 2, plrcin - 7
  189.                         if not self.IsAbleFill(row, col):
  190.                             print("Board Already Filled Choose Another To Fill")
  191.                             continue
  192.                         self.PlayerFill(row, col)
  193.                         break
  194.                 self.PrevPlayed = self.Player
  195.                 self.Turn = self.AI
  196.             case self.AI:
  197.                 print("AI Turn!..AI Is Thinking And Choosing..")
  198.                 self.AIFill()
  199.                 self.PrevPlayed = self.AI
  200.                 self.Turn = self.Player
  201.     def StartGame(self):
  202.         self.ChooseTeam()
  203.         self.SelectDiff()
  204.         self.StartTurn()
  205.         while True:
  206.             self.DrawBoard()
  207.             if self.IsGameOver():
  208.                 print(f"Game Over Winner : {self.PrevPlayed}")
  209.                 break
  210.             if self.IsTie():
  211.                 print("Game Tie!")
  212.                 break
  213.             self.AutoPlayRound()
  214. #Test Result
  215. ttt1 = tictactoe()
  216. ttt1.StartGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement