Кристиян обнови решението на 14.04.2013 20:44 (преди над 11 години)
+import re
+
+
+class TicTacToeExceptions(Exception):
+
+ def __init__(self):
+ pass
+
+
+class InvalidMove(TicTacToeExceptions):
+
+ def __init__(self):
+ super().__init__()
+
+
+class InvalidValue(TicTacToeExceptions):
+
+ def __init__(self):
+ super().__init__()
+
+
+class InvalidKey(TicTacToeExceptions):
+
+ def __init__(self):
+ super().__init__()
+
+
+class NotYourTurn(TicTacToeExceptions):
+
+ def __init__(self):
+ super().__init__()
+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {}
+ for x in range(9):
+ self.board[x + 1] = " "
+ self.winner = " "
+ self.previous_player = " "
+
+ def __setitem__(self, str, val):
+ try:
+
+ if not (re.search(r'^[ABC][123]$', str)):
+ raise InvalidKey
+
+ if re.search(r'^O|X$', self.board[int(ord(str[0]) - ord('A') + 1) +
+ (3 - (int(str[1]))) * 3]):
+ raise InvalidMove
+
+ if not (re.search(r'^O|X$', val)):
+ raise InvalidValue
+
+ if ord(self.previous_player) - ord(val) == 0:
+ raise NotYourTurn
+ else:
+ self.previous_player = val
+ self.winner = self.game_status()
+
+ except InvalidKey as e:
+ raise InvalidKey
+ except InvalidMove as e:
+ raise InvalidMove
+ except InvalidValue as e:
+ raise InvalidValue
+ except NotYourTurn as e:
+ raise NotYourTurn
+
+ else:
+ self.board[int(ord(str[0]) - ord(
+ 'A') + 1) + (3 - (int(str[1]))) * 3] = val
+
+ def __str__(self):
+ board_visualisation = '\n -------------\n' + '3 |'
+ for x in (sorted(self.board.items(), key=lambda t: t[0])):
+ board_visualisation += ' ' + x[1] + ' |'
+ if x[0] % 3 == 0 and x[0] != 9:
+ board_visualisation += '\n -------------\n' + \
+ str(3 - (x[0] // 3)) + ' |'
+ board_visualisation += '\n -------------\n' + ' A B C \n'
+ return board_visualisation
+
+ def are_these_equal(self, a, b, c):
+ return self.board[a] == self.board[b] == self.board[c] != " "
+
+ def game_status(self):
+ if self.winner != " " and self.winner != "Game in progress.":
+ return self.winner
+ else:
+ if self.are_these_equal(1, 5, 9):
+ self.winner = self.board[1] + ' wins!'
+ return self.winner
+ if self.are_these_equal(3, 5, 7):
+ self.winner = self.board[3] + ' wins!'
+ return self.winner
+ for i in range(3):
+ if self.are_these_equal(3 * i + 1, 3 * i + 2, 3 * i + 3):
+ self.winner = self.board[3 * i + 1] + ' wins!'
+ return self.winner
+ if self.are_these_equal(i + 1, i + 4, i + 7):
+ self.winner = self.board[3 * i + 1] + ' wins!'
+ return self.winner
+ if " " in self.board.values():
+ return "Game in progress."
+ return 'Draw!'
По добре си дефинирай изключенията така:
class InvalidKey(Еxception):
pass
При положение че нямаш специална функционалност в изключенията няма смисъл да си правиш някаква йерархия от тях. Просто си наследявай Exception.