Мариян обнови решението на 27.11.2022 16:31 (преди почти 2 години)
+import re
+
+
+class ChessException(Exception):
+ pass
+
+
+class MultipleKings(ChessException):
+ pass
+
+
+class AdjascentKings(ChessException):
+ pass
+
+
+class FirstLinePawn(ChessException):
+ pass
+
+
+def ChessDesk(str):
+ for row in str.split('/'):
+ for column in row:
+ if column.isdigit():
+ str = str.replace(column, 'X' * eval(column))
+ return str.split('/')
+
+
+def isKing(piece):
+ return piece in ('k', 'K')
+
+
+def HasAdjascentKings(chessDesk, row, column):
+ for i in [-1, 0, 1]:
+ for j in [-1, 0, 1]:
+ if chessDesk[row+i][column+j] == chessDesk[row][column] and not (i, j) == (0, 0):
+ return True
+ return False
+
+
+def IsValidIndex(i, j):
+ def isInRange(number):
+ return 0 <= number - 1 <= number + 1 <= 7
+ return isInRange(i) and isInRange(j)
+
+
+class ChessPosition():
+ def __init__(self, str):
+ try:
+ for i, row in enumerate(ChessDesk(str)):
+ for j, piece in enumerate(row):
+ if (isKing(piece) and IsValidIndex(i, j) and HasAdjascentKings(ChessDesk(str), i, j)):
+ raise AdjascentKings
+ if (str.count('K') != 1 or str.count('k') != 1):
+ raise MultipleKings
+ for i, row in enumerate(str.split('/')):
+ if (re.search(r'[P]{1}', row, re.IGNORECASE) and i in (0, 7)):
+ raise FirstLinePawn
+ except AdjascentKings:
+ print("kings")
+ except MultipleKings:
+ print("kings")
+ except FirstLinePawn:
+ print("pawns")
+ else:
+ self.str = str
+ self.chessDesk = ChessDesk(str)
+
+ def get_white_score(self):
+ points = {'R': 5, 'N': 3, 'B': 3, 'Q': 9, 'K': 4, 'P': 1}
+ return sum([points[char] for char in self.str if char in points.keys()])
+
+ def get_black_score(self):
+ points = {'r': 5, 'n': 3, 'b': 3, 'q': 9, 'k': 4, 'p': 1}
+ return sum([points[char] for char in self.str if char in points.keys()])
+
+ def white_is_winning(self):
+ return self.get_white_score() > self.get_black_score()
+
+ def black_is_winning(self):
+ return self.get_black_score() > self.get_white_score()
+
+ def is_equal(self):
+ return self.get_black_score() == self.get_white_score()
+
+ def __str__(self):
+ return self.str
+
+ def __len__(self):
+ return len(re.findall(r'[RrNnBbQqKkPp]', self.str))
+
+ def __getitem__(self, key):
+ return self.chessDesk[7-(ord(key[0])-ord('A'))][int(key[1])-1]
+
+
+class ChessScore():
+ def __init__(self, pieces):
+ self.pieces = pieces
+
+ def __int__(self):
+ points = {'r': 5, 'n': 3, 'b': 3, 'q': 9, 'k': 4, 'p': 1}
+ return sum([points[char] for char in self.pieces if char in points.keys()])
+
+ def __lt__(self, other):
+ return int(self) < int(other)
+
+ def __le__(self, other):
+ return int(self) <= int(other)
+
+ def __gt__(self, other):
+ return int(self) > int(other)
+
+ def __eq__(self, other):
+ return int(self) == int(other)
+
+ def __ne__(self, other):
+ return int(self) != int(other)