Светлана обнови решението на 14.04.2013 23:43 (преди над 11 години)
+class TicTacToeError(Exception):
+ pass
+
+
+class InvalidMove(TicTacToeError):
+
+ def __init__(self):
+ self.message = "This field is already filled."
+
+
+class InvalidKey(TicTacToeError):
+
+ def __init__(self):
+ self.message = "There is no such field."
+
+
+class InvalidValue(TicTacToeError):
+
+ def __init__(self):
+ self.message = "This is not a proper mark"
+
+
+class NotYourTurn(TicTacToeError):
+
+ def __init__(self):
+ self.message = "The other player hasn't made his move yet"
+
+
+class TicTacToeBoard:
+
+ def __init__(self):
+ self.board = {"A1": " ", "A2": " ", "A3": " ",
+ "B1": " ", "B2": " ", "B3": " ",
+ "C1": " ", "C2": " ", "C3": " "}
+ self.status = "Game in progress."
+ self.last_played = None
+ self.winner = None
+
+ def __getitem__(self, key):
+ if key not in self.board:
+ raise InvalidKey
+ return self.board[key]
+
+ def __setitem__(self, key, value):
+ if value != "X" and value != "O":
+ raise InvalidValue
+ if key not in self.board:
+ raise InvalidKey
+ if self.board[key] != " ":
+ raise InvalidMove
+ if value == self.last_played:
+ raise NotYourTurn
+ self.last_played = value
+ self.board[key] = value
+ self.check_status()
+
+ def check_status(self):
+ if self.winner:
+ return
+ for row in ["1", "2", "3"]:
+ if (self.board["A" + row] == self.board["B" + row] ==
+ self.board["C" + row] != " "):
+ self.winner = self.board["A" + row]
+ for column in ["A", "B", "C"]:
+ if (self.board[column + "1"] == self.board[column + "2"] ==
+ self.board[column + "3"] != " "):
+ self.winner = self.board[column + "1"]
+ if self.board["A3"] == self.board["B2"] == self.board["C1"] != " ":
+ self.winner = self.board["A3"]
+ if self.board["A1"] == self.board["B2"] == self.board["C3"] != " ":
+ self.winner = self.board["A3"]
+ if self.winner:
+ self.status = self.winner + " wins!"
+ if " " not in self.board.values() and not self.winner:
+ self.status = "Draw!"
+ self.winner = "Draw"
+
+ def __str__(self):
+ return ("\n -------------\n"
+ "3 | {0[A3]} | {0[B3]} | {0[C3]} |\n"
+ " -------------\n"
+ "2 | {0[A2]} | {0[B2]} | {0[C2]} |\n"
+ " -------------\n"
+ "1 | {0[A1]} | {0[B1]} | {0[C1]} |\n"
+ " -------------\n"
+ " A B C \n").format(self.board)
+
+ def game_status(self):
+ return self.status