Емил обнови решението на 15.04.2013 16:57 (преди над 11 години)
+class InvalidMove(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidKey(Exception):
+ pass
+
+
+class NotYourTurn(Exception):
+ pass
+
+
+class TicTacToeBoard:
+
+ keys = ("A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3")
+# keys = ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3')
+ signs = ('X', 'O')
+ mapping = {'A': 0, 'B': 1, 'C': 2}
+ map_values = {'X': 1, 'O': -1}
+
+ def __init__(self):
+ self.status = 'Game in progress.'
+ self.rows = [0, 0, 0, 0]
+ self.cols = [0, 0, 0, 0]
+ self.matrix = ([' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '])
+ self.is_solvled = False
+ self.last_sign
+ self.diagonal = 0
+ self.opposite_diagonal = 0
+ self.filed_cells = 0
+
+ # def __getattr__(self, key):
+ # if key not in self.keys:
+ # raise InvalidKey
+ # super().__getattr__(key)
+
+ def __setattr__(self, key, sign):
+ if key not in self.keys:
+ raise InvalidKey
+ col = self.mapping[key[0]]
+ row = int(key[1]) - 1
+ if self.matrix[row][col] != ' ':
+ raise InvalidMove
+ if sign not in self.signs:
+ raise InvalidValue
+ if self.last_sign == sign:
+ raise NotYourTurn
+ self.matrix[row][col] = sign
+ self.filed_cells += 1
+ if self.is_solvled:
+ return
+ self.last_sign = sign
+ self.process(sign, row, col)
+ self.check_status()
+
+ def check_status(self):
+ for sum in self.rows + self.cols:
+ if sum == 3:
+ self.status = 'X wins!'
+ self.is_solvled = True
+ return
+ if sum == -3:
+ self.status = 'O wins!'
+ self.is_solvled = True
+ return
+ if self.filed_cells == 9:
+ self.status = 'Draw!'
+ self.is_solvled = True
+
+ def process(self, sign, row, col):
+ value = self.map_values[sign]
+ self.rows[row] += value
+ self.cols[col] += value
+ if row == col:
+ self.diagonal += value
+ if row + col == 2:
+ self.opposite_diagonal += value
+
+ def game_status(self):
+ return self.status
+
+ def __str__(self):
+ m = self.matrix
+ print('\n -------------')
+ print('3 | {} | {} | {} |'.format(m[0][0], m[0][1], m[0][2]))
+ print(' -------------')
+ print('2 | {} | {} | {} |'.format(m[1][0], m[1][1], m[1][2]))
+ print(' -------------')
+ print('1 | {} | {} | {} |'.format(m[2][0], m[2][1], m[2][2]))
+ print(' -------------')
+ print(' A B C ')