Advertisement
Lyuben_Andreev

OOP: Tic-Tac-Toe

Aug 6th, 2024
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.45 KB | Software | 0 0
  1. ALL_SPACES = list('123456789')
  2. X, O, BLANK = 'X', 'O', ' '
  3.  
  4.  
  5. def main():
  6.     """Runs a game of tic-tac-toe."""
  7.     print('Welcome to tic-tac-toe!')
  8.     gameBoard = TTTBoard()
  9.     currentPlayer, nextPlayer = X, O
  10.  
  11.     while True:
  12.         print(gameBoard.getBoardStr())
  13.  
  14.         move = None
  15.         while not gameBoard.isValidSpace(move):
  16.             print(f'What is {currentPlayer}\'s move? (1-9)')
  17.             move = input()
  18.             if not move.isdigit() or move not in ALL_SPACES:
  19.                 print("Please enter a valid number between 1 and 9.")
  20.                 move = None
  21.                 continue
  22.  
  23.             if gameBoard.isValidSpace(move):
  24.                 gameBoard.updateBoard(move, currentPlayer)
  25.                 break
  26.             else:
  27.                 print("That space is already occupied. Choose another space.")
  28.                 move = None
  29.  
  30.         # Check if the game is over:
  31.         if gameBoard.isWinner(currentPlayer):
  32.             print(gameBoard.getBoardStr())
  33.             print(f'{currentPlayer} has won the game!')
  34.             break
  35.         elif gameBoard.isBoardFull():
  36.             print(gameBoard.getBoardStr())
  37.             print("The game is a tie.")
  38.             break
  39.  
  40.         # Swap turns
  41.         currentPlayer, nextPlayer = nextPlayer, currentPlayer
  42.  
  43.     print('Thanks for playing!')
  44.  
  45.  
  46. class TTTBoard:
  47.     def __init__(self, usePrettyBoard=False, useLogging=False):
  48.         """Create a new, blank tic-tac-toe board."""
  49.         self._spaces = {}
  50.         for space in ALL_SPACES:
  51.             self._spaces[space] = BLANK
  52.  
  53.     def getBoardStr(self):
  54.         """Return a text-representation of the board."""
  55.         return (
  56.             f"{self._spaces['1']} | {self._spaces['2']} | {self._spaces['3']}  1 2 3\n"
  57.             f"--+---+--\n"
  58.             f"{self._spaces['4']} | {self._spaces['5']} | {self._spaces['6']}  4 5 6\n"
  59.             f"--+---+--\n"
  60.             f"{self._spaces['7']} | {self._spaces['8']} | {self._spaces['9']}  7 8 9"
  61.         )
  62.  
  63.     def isValidSpace(self, space):
  64.         """Returns True if the space on the board is a valid space number and the space is blank."""
  65.         return space in ALL_SPACES and self._spaces[space] == BLANK
  66.  
  67.     def isWinner(self, player):
  68.         """Return True if player is a winner on this TTTBoard."""
  69.         b, p = self._spaces, player  # Shorter names as "syntactic sugar".
  70.         # Check for 3 marks across the 3 rows, 3 columns, and 2 diagonals.
  71.         return ((b['1'] == b['2'] == b['3'] == p) or  # Across the top
  72.                 (b['4'] == b['5'] == b['6'] == p) or  # Across the middle
  73.                 (b['7'] == b['8'] == b['9'] == p) or  # Across the bottom
  74.                 (b['1'] == b['4'] == b['7'] == p) or  # Down the left
  75.                 (b['2'] == b['5'] == b['8'] == p) or  # Down the middle
  76.                 (b['3'] == b['6'] == b['9'] == p) or  # Down the right
  77.                 (b['3'] == b['5'] == b['7'] == p) or  # Diagonal
  78.                 (b['1'] == b['5'] == b['9'] == p))  # Diagonal
  79.  
  80.     def isBoardFull(self):
  81.         """Return True if every space on the board has been taken."""
  82.         for space in ALL_SPACES:
  83.             if self._spaces[space] == BLANK:
  84.                 return False  # If a single space is blank, return False.
  85.         return True  # No spaces are blank, so return True.
  86.  
  87.     def updateBoard(self, space, mark):
  88.         """Sets the space on the board to mark."""
  89.         self._spaces[space] = mark
  90.  
  91.  
  92. main()
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement