Александър обнови решението на 12.04.2013 23:47 (преди над 11 години)
+import re
+
+
+class InvalidMove(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidKey(Exception):
+ pass
+
+
+class NotYourTurn(Exception):
+ pass
+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {}
+ self.last_player = ''
+ self.status = 'Game in progress.'
+ self.steps = 0
+
+ def game_status(self):
+ return self.status
+
+ def __setitem__(self, key, value):
+ match = re.search('[ABC][123]', key)
+
+ if match is None:
+ raise InvalidKey
+
+ start, end = match.span()
+
+ if key[start:end] != key:
+ raise InvalidKey
+
+ if value != 'X' and value != 'O':
+ raise InvalidValue
+
+ if key in self.board:
+ raise InvalidMove
+
+ if self.last_player == value:
+ raise NotYourTurn
+
+ self.board[key] = value
+ self.last_player = value
+ self.steps += 1
+
+ if self.status == 'Game in progress.':
+ board_string = ''
+
+ for col in ['A', 'B', 'C']:
+ for row in ['1', '2', '3']:
+ board_string += self.board.get(col+row, ' ')
+
+ win_regex = ['ppp......', '...ppp...', '......ppp',
+ 'p..p..p', 'p...p...p', '..p.p.p..']
+
+ for player in ['X', 'O']:
+ for regex in win_regex:
+ pattern = re.sub('p', player, regex)
+ if re.search(pattern, board_string):
+ self.status = player + ' wins!'
+
+ if self.status == 'Game in progress.' and self.steps == 9:
+ self.status = 'Draw!'
+
+ def __getitem__(self, key):
+ return self.board[key]
+
+ def __str__(self):
+ result = '\n -------------\n'
+ for row in ['3', '2', '1']:
+ result += row + ' |'
+ for col in ['A', 'B', 'C']:
+ result += ' ' + self.board.get(col+row, ' ') + ' |'
+ result += '\n -------------\n'
+ result += ' A B C \n'
+ return result