Марина обнови решението на 15.04.2013 15:08 (преди над 11 години)
+class TicTacToeBoard:
+ def __init__(self):
+ self.board = {'A1': ' ', 'A2': ' ', 'A3': ' ',
+ 'B1': ' ', 'B2': ' ', 'B3': ' ',
+ 'C1': ' ', 'C2': ' ', 'C3': ' '}
+ self.last = None
+ self.list_values = ['X', 'O']
+
+ def __setitem__(self, key, value):
+ if key not in self.board:
+ raise InvalidKey
+
+ if value not in self.list_values:
+ raise InvalidValue
+
+ if self.board[key] is not " ":
+ raise InvalidMove
+
+ if self.last == value:
+ raise NotYourTurn
+
+ self.board[key] = value
+ self.last = value
+
+ def __getitem__(self, key):
+ return self.board[key]
+
+ def __str__(self):
+ return '\n -------------\n' +\
+ '3 | ' + self.board['A3'] + ' | ' + self.board['B3'] +\
+ ' | ' + self.board['C3'] + ' |\n' +\
+ ' -------------\n' +\
+ '2 | ' + self.board['A2'] + ' | ' + self.board['B2'] +\
+ ' | ' + self.board['C2'] + ' |\n' +\
+ ' -------------\n' +\
+ '1 | ' + self.board['A1'] + ' | ' + self.board['B1'] +\
+ ' | ' + self.board['C1'] + ' |\n' +\
+ ' -------------\n' +\
+ ' A B C \n'
+
+ def winning_combos(self, z):
+ self.winning = [[self.board['A1'], self.board['A2'], self.board['A3']],
+ [self.board['B1'], self.board['B2'], self.board['B3']],
+ [self.board['C1'], self.board['C2'], self.board['C3']],
+ [self.board['A1'], self.board['B1'], self.board['C1']],
+ [self.board['A2'], self.board['B2'], self.board['C2']],
+ [self.board['A3'], self.board['B3'], self.board['C3']],
+ [self.board['A1'], self.board['B2'], self.board['C3']],
+ [self.board['A3'], self.board['B2'], self.board['C3']]]
+
+ for l in self.winning:
+ if l[0] == l[1] == l[2] == z:
+ return True
+
+ return False
+
+ def game_status(self):
+ positions = ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
+
+ if self.winning_combos('O'):
+ return "O wins!"
+
+ if self.winning_combos('X'):
+ return "X wins!"
+
+ if self.winning_combos('X') is self.winning_combos('O') is False:
+ for z in positions:
+ if self.board[z] == ' ':
+ return "Game in progress."
+ return "Draw!"
+
+
+class InvalidMove(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidKey(Exception):
+ pass
+
+
+class NotYourTurn(Exception):
+ pass
+