Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import random
- WINNING_COMBINATIONS=[
- (1,2,3),
- (4,5,6),
- (7,8,9),
- (1,4,7),
- (2,5,8),
- (3,6,9),
- (1,5,9),
- (3,5,7),
- ]
- def switch_player(current_player):
- return 'O' if current_player == 'X' else 'X'
- class Game:
- def __init__(self, board):
- self.board = board
- def get_player_marker(self):
- marker = ''
- while not (marker in ['X', 'O']):
- marker = input('(Player1):Do you want to be X or O?').upper()
- return ('X', 'O') if marker == 'X' else ('O', 'X')
- def check_winner(self, mark):
- grid = self.board.grid
- return any([(grid[a] == grid[b] == grid[c] == mark) for (a,b,c) in WINNING_COMBINATIONS])
- def get_player_choice(self, current_player):
- while True:
- try:
- pos = int(input(f'({current_player})Choose your next position: (1-9)'))
- if pos in (self.board.all_positions - self.board.marked_positions):
- return pos
- else:
- print('Someone has already moved to that spot.')
- except ValueError:
- ...
- def play(self):
- print('Tic Tac Toe')
- P1, P2 = self.get_player_marker()
- current_player = P1
- while True:
- pos = self.get_player_choice(current_player)
- self.board.mark_board(current_player, pos)
- self.board.print_board()
- if self.check_winner(current_player):
- print(f'Game over. Player {current_player} wins')
- break
- if self.board.is_full:
- print('Game ended in a draw')
- break
- current_player = switch_player(current_player)
- class Board:
- def __init__(self):
- self.grid = [' '] * 10
- self.marked_positions = set()
- self.all_positions = set(list(range(1,10)))
- def mark_board(self, marker, position):
- if self.grid[position] in ('X', 'O'):
- return
- self.grid[position] = marker
- self.marked_positions.add(position)
- @property
- def is_full(self):
- return self.marked_positions == self.all_positions
- def print_board(self):
- grid = self.grid
- sys.stdout.write('\033[H')
- sys.stdout.write('\033[J')
- print(' ' + grid[7] + ' | ' + grid[8] + ' | ' + grid[9])
- print('-----------')
- print(' ' + grid[4] + ' | ' + grid[5] + ' | ' + grid[6])
- print('-----------')
- print(' ' + grid[1] + ' | ' + grid[2] + ' | ' + grid[3])
- def main():
- board = Board()
- game = Game(board)
- try:
- game.play()
- except KeyboardInterrupt:
- print('\nexiting...')
- sys.exit(1)
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment