Георги обнови решението на 15.04.2013 13:18 (преди над 11 години)
+class TicTacToeBoard:
+ def __init__(self):
+ self.coords = ['A1', 'A2', 'A3',
+ 'B1', 'B2', 'B3',
+ 'C1', 'C2', 'C3']
+ self.xoxo = [None] * 9
+ self.last_turn = None
+ self.flag = True
+ self.status = 0
+
+ def __getitem__(self, coord):
+ if coord in self.coords:
+ return self.xoxo[self.coords.index(coord)]
+ else:
+ raise InvalidKey
+
+ def __setitem__(self, coord, value):
+ if coord in self.coords:
+ if self.xoxo[self.coords.index(coord)] is None:
+ if value in ['X', 'O']:
+ if value != self.last_turn:
+ self.xoxo[self.coords.index(coord)] = value
+ self.last_turn = value
+ self.check_result()
+ else:
+ raise NotYourTurn
+ else:
+ raise InvalidValue
+ else:
+ raise InvalidMove
+ else:
+ raise InvalidKey
+
+ def __str__(self):
+ new_line = "\n -------------\n"
+ print_it = new_line
+ for row in range(3):
+ print_it += str(3-row) + " |"
+ for col in self.xoxo[(2-row)::3]:
+ if col:
+ print_it += " " + str(col) + " |"
+ else:
+ print_it += " |"
+ print_it += new_line
+ print_it += " A B C \n"
+ return print_it
+
+ def check_result(self):
+ if self.flag:
+ for my_index in range(3):
+ if self.xoxo[my_index] == self.xoxo[my_index+3]:
+ if self.xoxo[my_index+3] == self.xoxo[my_index+6]:
+ if self.xoxo[my_index] == "X":
+ self.status = 1
+ self.flag = False
+ elif self.xoxo[my_index] == "O":
+ self.status = 2
+ self.flag = False
+ elif self.xoxo[(my_index*3)] == self.xoxo[(my_index*3)+1]:
+ if self.xoxo[(my_index*3)] == self.xoxo[(my_index*3)+2]:
+ if self.xoxo[my_index*3] == "X":
+ self.status = 1
+ self.flag = False
+ elif self.xoxo[my_index*3] == "O":
+ self.status = 2
+ self.flag = False
+ if self.xoxo[0] == self.xoxo[4] == self.xoxo[8]:
+ if self.xoxo[0] == "X":
+ self.status = 1
+ self.flag = False
+ elif self.xoxo[2] == "O":
+ self.status = 2
+ self.flag = False
+ elif self.xoxo[2] == self.xoxo[4] == self.xoxo[6]:
+ if self.xoxo[2] == "X":
+ self.status = 1
+ self.flag = False
+ elif self.xoxo[2] == "O":
+ self.status = 2
+ self.flag = False
+ elif all(self.xoxo):
+ self.flag = False
+ self.status = 3
+
+ def game_status(self):
+ status_messages = ["Game in progress.",
+ "X wins!", "O wins!",
+ "Draw!"]
+ return status_messages[self.status]
+
+
+class NotYourTurn(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidMove(Exception):
+ pass
+
+
+class InvalidKey(Exception):
+ pass