Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tic Tac Toe
- TL, TM, TR, ML, MM, MR, BL, BM, BR = 'TL', 'TM', 'TR', 'ML', 'MM', 'MR', 'BL', 'BM', 'BR'
- ALL_SPACES = (TL, TM, TR, ML, MM, MR, BL, BM, BR)
- X, O, BLANK = 'X', 'O', ' '
- def main():
- game = TicTacToeGame()
- game.run()
- class TicTacToeGame:
- def run(self):
- print('Welcome to Tic Tac Toe!')
- mainBoard = TicTacToeBoard()
- turn = X
- nextTurn = O
- while True:
- print('It is ' + turn + '\'s turn.')
- mainBoard.drawBoard()
- move = mainBoard.getPlayerMove()
- mainBoard.setSpace(move, turn)
- if mainBoard.isWinner(turn):
- mainBoard.drawBoard()
- print(turn + ' has won the game!')
- break
- elif mainBoard.isFull():
- mainBoard.draw()
- print('The game is a tie!')
- break
- print()
- turn, nextTurn = nextTurn, turn
- class TicTacToeBoard:
- def __init__(self, startingMarks=None):
- # Create a new, blank tic tac toe board.
- if startingMarks is None:
- startingMarks = {}
- self.spaces = {}
- for space in ALL_SPACES:
- self.spaces.setdefault(space, startingMarks.get(space, BLANK))
- def drawBoard(self):
- # Display a text-representation of the board.
- print(f'{self.spaces[TL]}|{self.spaces[TM]}|{self.spaces[TR]}')
- print('-----')
- print(f'{self.spaces[ML]}|{self.spaces[MM]}|{self.spaces[MR]}')
- print('-----')
- print(f'{self.spaces[BL]}|{self.spaces[BM]}|{self.spaces[BR]}')
- def isWinner(self, mark):
- bo, m = self.spaces, mark # These shorter names make the following code shorter.
- return ((bo[TL] == m and bo[TM] == m and bo[TR] == m) or # across the top
- (bo[ML] == m and bo[MM] == m and bo[MR] == m) or # across the middle
- (bo[BL] == m and bo[BM] == m and bo[BR] == m) or # across the bottom
- (bo[TL] == m and bo[ML] == m and bo[BL] == m) or # down the left side
- (bo[TM] == m and bo[MM] == m and bo[BM] == m) or # down the middle
- (bo[TR] == m and bo[MR] == m and bo[BR] == m) or # down the right side
- (bo[TL] == m and bo[MM] == m and bo[BR] == m) or # diagonal
- (bo[TR] == m and bo[MM] == m and bo[BL] == m)) # diagonal
- def getPlayerMove(self):
- # Let the player type in their move.
- move = None
- while move not in ALL_SPACES or not self.spaces[move] == BLANK:
- print('What is your move? (TL TM TR ML MM MR BL BM BR)')
- move = input().upper()
- return move
- def isFull(self):
- # Return True if every space on the board has been taken. Otherwise return False.
- for space in ALL_SPACES:
- if self.spaces[space] == BLANK:
- return False
- return True
- def setSpace(self, space, mark):
- # Sets the space on the board to mark, if it is valid.
- if mark not in (X, O, BLANK):
- raise ValueError('invalid mark for space')
- self.spaces[space] = mark
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement