Виктор обнови решението на 27.11.2022 16:59 (преди почти 2 години)
+import re
+
+
+class ChessException(Exception):
+ pass
+
+
+class ChessScore:
+ def __new__(cls, pieces):
+ return int(sum(pieces.count(piece) * value
+ for piece, value in {'r': 5, 'n': 3, 'b': 3, 'q': 9,
+ 'k': 4, 'p': 1}.items()))
+
+
+class ChessPosition(str):
+ def __new__(cls, position_string):
+ return super().__new__(cls, position_string)
+
+ def __init__(self, position_string):
+ self.translated = self
+ # Place a dot on every empty square and remove separators (/)
+ for number in re.findall(r'\d', self):
+ self.translated = re.sub(number, '.' * int(number), self.translated)
+ self.translated = re.sub(r'/', '', self.translated)
+ if sorted(list(re.findall(r'[Kk]', self))) != ['K', 'k']:
+ raise ChessException('kings')
+ kings_distance = abs(self.translated.index('K') -
+ self.translated.index('k'))
+ if kings_distance in (1, 7, 8, 9): # 7 and 9 are for diagonals
+ raise ChessException('kings')
+ if re.search(r'[Pp]', self.translated[:8] + self.translated[-8:]):
+ raise ChessException('pawns')
+
+ def __len__(self):
+ return len(re.sub(r'[\d/]', '', self))
+
+ def __getitem__(self, pos):
+ figure = self.translated[ord(pos[0]) - 65 + (8 - int(pos[1])) * 8]
+ return figure if figure != '.' else None
+
+ def get_white_score(self):
+ return ChessScore([piece.lower() for piece in re.findall(r'[A-Z]', self)])
+
+ def get_black_score(self):
+ return ChessScore(list(re.findall(r'[a-z]', self)))
+
+ def white_is_winning(self):
+ return self.get_white_score() > self.get_black_score()
+
+ def black_is_winning(self):
+ return self.get_white_score() < self.get_black_score()
+
+ def is_equal(self):
+ return self.get_white_score() == self.get_black_score()