Guest User

Untitled

a guest
Sep 24th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. import sys
  2. import random
  3.  
  4. WINNING_COMBINATIONS=[
  5. (1,2,3),
  6. (4,5,6),
  7. (7,8,9),
  8. (1,4,7),
  9. (2,5,8),
  10. (3,6,9),
  11. (1,5,9),
  12. (3,5,7),
  13. ]
  14.  
  15. def switch_player(current_player):
  16. return 'O' if current_player == 'X' else 'X'
  17.  
  18. class Game:
  19. def __init__(self, board):
  20. self.board = board
  21.  
  22. def get_player_marker(self):
  23. marker = ''
  24. while not (marker in ['X', 'O']):
  25. marker = input('(Player1):Do you want to be X or O?').upper()
  26. return ('X', 'O') if marker == 'X' else ('O', 'X')
  27.  
  28. def check_winner(self, mark):
  29. grid = self.board.grid
  30. return any([(grid[a] == grid[b] == grid[c] == mark) for (a,b,c) in WINNING_COMBINATIONS])
  31.  
  32. def get_player_choice(self, current_player):
  33. while True:
  34. try:
  35. pos = int(input(f'({current_player})Choose your next position: (1-9)'))
  36. if pos in (self.board.all_positions - self.board.marked_positions):
  37. return pos
  38. else:
  39. print('Someone has already moved to that spot.')
  40. except ValueError:
  41. ...
  42.  
  43. def play(self):
  44. print('Tic Tac Toe')
  45. P1, P2 = self.get_player_marker()
  46. current_player = P1
  47. while True:
  48. pos = self.get_player_choice(current_player)
  49. self.board.mark_board(current_player, pos)
  50. self.board.print_board()
  51. if self.check_winner(current_player):
  52. print(f'Game over. Player {current_player} wins')
  53. break
  54. if self.board.is_full:
  55. print('Game ended in a draw')
  56. break
  57. current_player = switch_player(current_player)
  58.  
  59. class Board:
  60. def __init__(self):
  61. self.grid = [' '] * 10
  62. self.marked_positions = set()
  63. self.all_positions = set(list(range(1,10)))
  64.  
  65. def mark_board(self, marker, position):
  66. if self.grid[position] in ('X', 'O'):
  67. return
  68. self.grid[position] = marker
  69. self.marked_positions.add(position)
  70.  
  71. @property
  72. def is_full(self):
  73. return self.marked_positions == self.all_positions
  74.  
  75. def print_board(self):
  76. grid = self.grid
  77. sys.stdout.write('\033[H')
  78. sys.stdout.write('\033[J')
  79.  
  80. print(' ' + grid[7] + ' | ' + grid[8] + ' | ' + grid[9])
  81. print('-----------')
  82. print(' ' + grid[4] + ' | ' + grid[5] + ' | ' + grid[6])
  83. print('-----------')
  84. print(' ' + grid[1] + ' | ' + grid[2] + ' | ' + grid[3])
  85.  
  86. def main():
  87. board = Board()
  88. game = Game(board)
  89. try:
  90. game.play()
  91. except KeyboardInterrupt:
  92. print('\nexiting...')
  93. sys.exit(1)
  94.  
  95. if __name__ == '__main__':
  96. main()
Add Comment
Please, Sign In to add comment