Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tic Tac Toe
- # Author: John Moore
- from enum import IntEnum
- # global constants
- X = 'X'
- O = 'O'
- EMPTY = ' '
- TIE = 'T'
- NO_ONE = 'N'
- NUM_SQUARES = 9
- DIMENSION = 3
- YES = 'y'
- NO = 'n'
- class Status(IntEnum):
- WINNER = 1
- NOWINNER = 2
- TIE_GAME = 3
- class GameBoard():
- def __init__(self):
- self.reset()
- def reset(self):
- self.board = [[EMPTY for x in range(DIMENSION)] for y in range(DIMENSION)]
- def countEmptyCells(self):
- count = 0
- for row in range(DIMENSION):
- for col in range(DIMENSION):
- if self.board[row][col] == EMPTY:
- count += 1
- return count
- def Display(self):
- for row in range(DIMENSION):
- print("{:^3}|{:^3}|{:^3}".format(self.board[row][0], self.board[row][1], self.board[row][2]))
- if row < DIMENSION - 1:
- print("-" * 10)
- def getMark(self, location):
- mark = self.board[location // DIMENSION][location % DIMENSION]
- return mark
- def putMark(self, location, mark):
- self.board[location // DIMENSION][location % DIMENSION] = mark
- def isLegal(self, location):
- return self.board[location // DIMENSION][location % DIMENSION] == EMPTY
- def winner(self):
- TOTAL_ROWS = 8
- WINNING_ROWS = [
- [0, 1, 2],
- [3, 4, 5],
- [6, 7, 8],
- [0, 3, 6],
- [1, 4, 7],
- [2, 5, 8],
- [0, 4, 8],
- [2, 4, 6]
- ]
- for row in range(TOTAL_ROWS):
- status = self.getMark(WINNING_ROWS[row][0]) != EMPTY \
- and self.getMark(WINNING_ROWS[row][0]) == self.getMark(WINNING_ROWS[row][1]) \
- and self.getMark(WINNING_ROWS[row][1]) == self.getMark(WINNING_ROWS[row][2])
- if status:
- return self.getMark(WINNING_ROWS[row][0])
- # See if we have a tie
- if self.countEmptyCells() == 0:
- return TIE
- # No Winner
- return NO_ONE
- def getStatus(self):
- status = self.winner()
- if status == NO_ONE:
- print("NO WINNER")
- return Status.NOWINNER
- elif status == TIE:
- print("TIE GAME")
- return Status.TIE_GAME
- else:
- print("WINNER")
- return Status.WINNER
- class Player():
- def __init__(self, gameboard, mark=None):
- self.board = gameboard # type: GameBoard
- self.marker = mark
- @property
- def Marker(self):
- return self.marker
- @Marker.setter
- def Marker(self, value):
- self.marker = value
- def askNumber(self, question, high, low):
- number = None
- while True:
- number = int(input(question + "({} - {}):".format(low, high)))
- if number >= low and number <= high:
- return number
- def takeYourTurn(self):
- while True:
- move = self.askNumber("\nPlease Enter Your Move", 9, 1) - 1
- moveIsLegit = self.board.isLegal(move)
- if moveIsLegit:
- self.board.putMark(move, self.marker)
- break
- else:
- print("\nThat Move Has Already Been Taken\nPlease Try Again!\n")
- class ComputerPlayer(Player):
- def __init__(self, gameboard, mark=None):
- super().__init__(gameboard, mark)
- def opponent(self):
- if self.marker == X:
- return O
- else:
- return X
- def Strategy1(self):
- for move in range(NUM_SQUARES):
- if self.board.isLegal(move):
- self.board.putMark(move, self.marker)
- if self.board.winner() == self.marker:
- print(move + 1)
- return True
- else:
- self.board.putMark(move, EMPTY)
- return False
- def Strategy2(self):
- opponent = self.opponent()
- for move in range(NUM_SQUARES):
- if self.board.isLegal(move):
- self.board.putMark(move, opponent)
- if self.board.winner() == opponent:
- print(move + 1)
- self.board.putMark(move, self.marker)
- return True
- else:
- self.board.putMark(move, EMPTY)
- return False
- def Strategy3(self):
- Best_Moves = [4, 0, 7, 6, 8, 1, 3, 5, 2]
- for i in range(NUM_SQUARES):
- move = Best_Moves[i]
- if self.board.isLegal(move):
- self.board.putMark(move, self.marker)
- print(move + 1)
- return
- def takeYourTurn(self):
- print("\nI'm going to take move ", end='')
- if self.Strategy1():
- return
- elif self.Strategy2():
- return
- else:
- self.Strategy3()
- class TicTacToe():
- def __init__(self):
- self.board = GameBoard()
- self.computer = ComputerPlayer(self.board)
- self.human = Player(self.board)
- self.turn = None
- def askYesNo(self, question):
- response = None
- while True:
- response = input(question + "(y/n):").lower()
- if response[0] == YES or response[0] == NO:
- return response
- def switchTurn(self):
- self.turn = O if self.turn == X else X
- def displayInstructions(self):
- print("Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\n")
- print("--where human brain is pit against silicon processor\n\n")
- print("Make your move known by entering a number, 1 - 9. The number\n")
- print("corresponds to the desired board position, as illustrated:\n\n")
- print(" 1 | 2 | 3")
- print(" ---------")
- print(" 4 | 5 | 6")
- print(" ---------")
- print(" 7 | 8 | 9\n")
- print("Prepare yourself, human. The battle is about to begin.\n\n")
- def declareATie(self):
- print("It's a tie.")
- print("You were most lucky, human, and somehow managed to tie me.")
- print("Celebrate... for this is the best you will ever achieve.")
- def congratulateWinner(self):
- theWinner = self.board.winner()
- if theWinner == self.human.Marker:
- print(theWinner + "'s won!")
- print("No, no! It cannot be! Somehow you tricked me, human.")
- print("But never again! I, the computer, so swear it!")
- else: # theWinner == computer.getMarker()
- print(theWinner + "'s won!")
- print("As I predicted, human, I am triumphant once more -- proof")
- print("that computers are superior to humans in all regards.")
- def determineFirstPlayer(self):
- if self.turn is not None:
- return
- self.turn = X
- if self.askYesNo("Do You Want To Go First") == YES:
- self.human = Player(self.board, X)
- self.computer = ComputerPlayer(self.board, O)
- else: # answer is no
- self.human = Player(self.board, O)
- self.computer = ComputerPlayer(self.board, X)
- def PlayOneRound(self):
- self.board.reset()
- self.displayInstructions()
- self.determineFirstPlayer()
- status = None
- if self.turn == self.human.Marker:
- self.board.Display()
- # Game Loop
- while True:
- if self.turn == self.human.Marker:
- self.human.takeYourTurn()
- else: # turn == computer.getMarker()
- self.computer.takeYourTurn()
- self.board.Display()
- self.switchTurn()
- status = self.board.getStatus()
- if status == Status.WINNER or status == Status.TIE_GAME:
- break
- if status == Status.WINNER:
- self.congratulateWinner()
- else: # Tie Game
- self.declareATie()
- def Play(self):
- while True:
- self.PlayOneRound()
- if self.askYesNo("Do you want to play again") != YES:
- break
- print("\nThanks For Playing Tic Tac Toe!\n")
- if __name__ == "__main__":
- game = TicTacToe()
- game.Play()
Advertisement
Add Comment
Please, Sign In to add comment