Христина обнови решението на 12.04.2013 16:59 (преди над 11 години)
+import re
+
+
+class InvalidMove(AssertionError):
+ pass
+
+
+class InvalidKey(KeyError):
+ pass
+
+
+class InvalidValue(ValueError):
+ pass
+
+
+class NotYourTurn(AssertionError):
+ pass
+
+
+class TicTacToeBoard:
+ def __init__(self):
+ self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
+ 'B1': ' ', 'B2': ' ', 'B3': ' ',
+ 'C1': ' ', 'C2': ' ', 'C3': ' ',
+ 'previous_turn_value': ' '}
+
+ def __setitem__(self, key, value):
+ if not re.match('[ABC][123]', key):
+ raise InvalidKey(key)
+ if self.board[key] != ' ':
+ raise InvalidMove(key, 'has already been set!')
+ if value not in ('X', 'O'):
+ raise InvalidValue(value)
+ if self.board['previous_turn_value'] == value and not self.winner():
+ raise NotYourTurn('Not', value, 'turn!')
+ if not self.winner():
+ self.board[key] = value
+ self.board['previous_turn_value'] = value
+
+ def __getitem__(self, key):
+ return self.board[key]
+
+ def __str__(self):
+ tic_tac_toe_board = ''
+ dashes = ' -------------\n'
+ for row in ('3', '2', '1'):
+ tic_tac_toe_board += '\n{0}{1} |'.format(dashes, row)
+ for column in ('A', 'B', 'C'):
+ tic_tac_toe_board += ' {0} |'.format(self.board[column + row])
+ tic_tac_toe_board += '\n{0} A B C \n'.format(dashes)
+ return tic_tac_toe_board
+
+ def does_it_win(self, value):
+ winner_moves = [['A1', 'B1', 'C1'], ['A2', 'B2', 'C2'],
+ ['A3', 'B3', 'C3'], ['A1', 'A2', 'A3'],
+ ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3'],
+ ['A1', 'B2', 'C3'], ['A3', 'B2', 'C1']]
+ if any([all([value == self.board.get(_, ' ') for _ in elements])
+ for elements in winner_moves]):
+ return value
+
+ def winner(self):
+ return self.does_it_win('X') or self.does_it_win('O')
+
+ def is_board_filled(self):
+ return len([value for key, value in self.board.items()
+ if self.board[key] != ' ']) == 10
+
+ def game_status(self):
+ if self.winner():
+ return '{0} wins!'.format(self.winner())
+ if self.is_board_filled():
+ return "Draw!"
+ return "Game in progress."