Петър обнови решението на 15.04.2013 13:00 (преди над 11 години)
+class InvalidMove(Exception):
+ pass
+
+
+class InvalidValue(Exception):
+ pass
+
+
+class InvalidKey(Exception):
+ pass
+
+
+class NotYourTurn(Exception):
+ pass
+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {"A1": " ", "A2": " ", "A3": " ",
+ "B1": " ", "B2": " ", "B3": " ",
+ "C1": " ", "C2": " ", "C3": " "}
+ self.currentPlayer = 1
+ self.players = {-1: "O", 1: "X"}
+ self.markedCells = 0
+ self.gameStates = ["Game in progress.", "Draw!", "X wins!", "O wins!"]
+ self.gameWinner = {"O": self.gameStates[3], "X": self.gameStates[2]}
+ self.gameStatus = self.gameStates[0]
+
+ def __str__(self):
+ board = self.board
+ table = "\n -------------\n" +\
+ "3 | "+board["A3"]+" | "+board["B3"]+" | "+board["C3"]+" |\n" +\
+ " -------------\n" +\
+ "2 | "+board["A2"]+" | "+board["B2"]+" | "+board["C2"]+" |\n" +\
+ " -------------\n" +\
+ "1 | "+board["A1"]+" | "+board["B1"]+" | "+board["C1"]+" |\n" +\
+ " -------------\n" +\
+ " A B C \n"
+ return table
+
+ def __setitem__(self, index, value):
+ if self.gameStatus != self.gameStates[0]:
+ print(self.game_status())
+ return
+ indexes = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
+
+ if value not in ["O", "X"]:
+ raise InvalidValue()
+ return
+ if index not in indexes:
+ raise InvalidKey()
+ return
+ if self.board[index] is not " ":
+ raise InvalidMove()
+ return
+ if self.markedCells is 0:
+ if self.players[-1] is value:
+ self.currentPlayer = -1
+ else:
+ self.currentPlayer = 1
+ if value == self.players[self.currentPlayer]:
+ self.board[index] = value
+ self.currentPlayer *= -1
+ else:
+ raise NotYourTurn()
+ self.markedCells += 1
+ self.check_progress()
+
+ def game_status(self):
+ return self.gameStatus
+
+ def check_progress(self):
+ if self.markedCells < 5:
+ return
+ win = self.check_3_cells("A1", "A2", "A3")
+ if win is not None:
+ return
+ win = self.check_3_cells("B1", "B2", "B3")
+ if win is not None:
+ return
+ win = self.check_3_cells("C1", "C2", "C3")
+ if win is not None:
+ return
+ win = self.check_3_cells("A1", "B1", "C1")
+ if win is not None:
+ return
+ win = self.check_3_cells("A2", "B2", "C2")
+ if win is not None:
+ return
+ win = self.check_3_cells("A3", "B3", "C3")
+ if win is not None:
+ return
+ win = self.check_3_cells("A1", "B2", "C3")
+ if win is not None:
+ return
+ win = self.check_3_cells("A3", "B2", "C1")
+ if win is not None:
+ return
+ if self.markedCells == 9:
+ self.gameStatus = self.gameStates[1]
+
+ def check_3_cells(self, firstC, secondC, thirdC):
+ if self.board[firstC] not in ["O", "X"]:
+ return None
+ b = self.board
+ if b[firstC] == b[secondC] and b[secondC] == b[thirdC]:
+ self.gameStatus = self.gameWinner[b[firstC]]
+ return b[firstC]
+ else:
+ return None