Милан обнови решението на 09.04.2013 01:42 (преди над 11 години)
+class TicTacToeBoard:
+
+ def __init__(self):
+ self._empty = ' '
+ self._players = ('X', 'O')
+ slots = ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3')
+ self._board = {position: self._empty for position in slots}
+ self._on_turn = self._empty
+
+ def __getitem__(self, index):
+ if(self._board[index] != self._empty):
+ return self._board[index]
+
+ def __setitem__(self, index, item):
+ if index not in self._board:
+ raise InvalidKey
+ if item not in self._players:
+ raise InvalidValue
+ if not self._board[index] == self._empty:
+ raise InvalidMove
+ if item == self._on_turn:
+ raise NotYourTurn
+
+ self._board[index] = item
+ self._on_turn = item
+
+ def game_status(self):
+ winning_lines = (['A1', 'A2', 'A3'],
+ ['B1', 'B2', 'B3'],
+ ['C1', 'C2', 'C3'],
+ ['A1', 'B1', 'C1'],
+ ['A2', 'B2', 'C2'],
+ ['A3', 'B3', 'C3'],
+ ['A1', 'B2', 'C3'],
+ ['A3', 'B2', 'C1'])
+ winner = None
+ for row in winning_lines:
+ player = self._board[row.pop(0)]
+ if all(player == self._board[pos] != self._empty for pos in row):
+ winner = player
+
+ if winner:
+ return '{0} wins!'.format(winner)
+ if self._empty not in self._board.values():
+ return 'Draw!'
+ return 'Game in progress.'
+
+ def __str__(self):
+ return '''
+ -------------
+3 | {A3} | {B3} | {C3} |
+ -------------
+2 | {A2} | {B2} | {C2} |
+ -------------
+1 | {A1} | {B1} | {C1} |
+ -------------
+ A B C \n'''.format(**self._board)
+
+
+class InvalidKey(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidMove(Exception):
+ pass
+
+
+class NotYourTurn(Exception):
+ pass