Камелия обнови решението на 15.04.2013 09:03 (преди над 11 години)
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {'A1': ' ',
+ 'A2': ' ',
+ 'A3': ' ',
+ 'B1': ' ',
+ 'B2': ' ',
+ 'B3': ' ',
+ 'C1': ' ',
+ 'C2': ' ',
+ 'C3': ' ',
+ }
+ self.status = "Game in progress."
+ self.last_played = ' '
+
+ def __getitem__(self, cell):
+ return self.board[cell]
+
+ def __setitem__(self, cell, value):
+ if self.game_ended():
+ self.board[cell] = value
+ return
+ if not self.turn_of_player(value):
+ raise NotYourTurn
+ if value is not 'X' and value is not 'O':
+ raise InvalidValue
+ if cell not in self.board:
+ raise InvalidKey
+ if self.board[cell] != ' ':
+ raise InvalidMove
+ self.board[cell] = value
+ self.last_played = value
+ if self.wins(value) and value is 'X':
+ self.status = 'X wins!'
+ return
+ if self.wins(value) and value is 'O':
+ self.status = 'O wins!'
+ return
+ if self.full():
+ self.status = 'Draw!'
+
+ def game_status(self):
+ return self.status
+
+ def wins(self, value):
+ return (value, value, value) in self.lines()
+
+ def lines(self):
+ return [(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['C1']),
+ ]
+
+ def full(self):
+ return ' ' not in self.board.values()
+
+ def game_ended(self):
+ return self.status != 'Game in progress.'
+
+ def turn_of_player(self, value):
+ return self.last_played is ' ' or self.last_played is not value
+
+ 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"
+
+
+class TicTacToeError(Exception):
+
+ def __init__(self):
+ pass
+
+
+class InvalidMove(TicTacToeError):
+
+ def __init__(self):
+ super().__init__()
+
+
+class InvalidValue(TicTacToeError):
+
+ def __init__(self):
+ super().__init__()
+
+
+class InvalidKey(TicTacToeError):
+
+ def __init__(self):
+ super().__init__()
+
+
+class NotYourTurn(TicTacToeError):
+
+ def __init__(self):
+ super().__init__()
По-добре си направи изключенията така: MyException(Exception): pass
__str__
можеш лесно да го направиш малко по-пригледен със str.format