Решение на Шахматни фенове от Огнян Йончев

Обратно към всички решения

Към профила на Огнян Йончев

Резултати

  • 5 точки от тестове
  • 0 бонус точки
  • 5 точки общо
  • 9 успешни тест(а)
  • 8 неуспешни тест(а)

Код

chess_figures = {
'r': 5,
'n': 3,
'b': 3,
'q': 9,
'k': 4,
'p': 1,
}
class ChessException(Exception):
def __init__(self, message='Wrong chess.'):
self._message = message
super().__init__(self._message)
class ChessPosition:
def __init__(self, fen):
self.fen = fen
self.converted = self.__convert_fen(fen)
if (self.__kings_amount() or self.__kings_positions()):
raise ChessException('kings')
elif (self.__pawns_positions()):
raise ChessException('pawns')
def __convert_fen(self, fen):

Бих запазаил резултатът от този метод като атрибут на инстанцията, за да не минаваш всеки път през този метод, когато ти трябва да работиш с дъската.

# Convert fen to 8x8 chess with spaces.
new_fen = []
old_fen = fen.lower().split('/')
for row in old_fen:
new_row = ''
for figure in row:
if figure.isalpha():
new_row += figure
else:
new_row += ''.join('_'*int(figure))
new_fen.append(new_row)
return new_fen
def __kings_amount(self):
# Check if there is only two kings.
return self.fen.count('k') != 1 or self.fen.count('K') != 1
def __kings_positions(self):
# Check if the positions of the kings are correct.
for i_row, row in enumerate(self.converted):
for i_figure, figure in enumerate(row):
if i_row == 0 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
(self.converted[0][1] == 'k' or self.converted[1][0] == 'k' or self.converted[1][1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(self.converted[0][6] == 'k' or self.converted[1][7] == 'k' or self.converted[1][6] == 'k')):
return True
elif (figure == 'k' and
(self.converted[0][i_figure - 1] == 'k' or self.converted[0][i_figure + 1] == 'k' or
self.converted[1][i_figure] == 'k' or self.converted[1][i_figure - 1] == 'k' or self.converted[1][i_figure + 1] == 'k')):
return True
elif i_row == 7 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
(self.converted[7][1] == 'k' or self.converted[6][0] == 'k' or self.converted[6][0] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(self.converted[7][6] == 'k' or self.converted[6][7] == 'k' or self.converted[6][6] == 'k')):
return True
elif (figure == 'k' and
(self.converted[7][i_figure - 1] == 'k' or self.converted[7][i_figure + 1] == 'k' or
self.converted[6][i_figure] == 'k' or self.converted[6][i_figure - 1] == 'k' or self.converted[6][i_figure + 1] == 'k')):
return True
elif figure == 'k':
if (i_figure == 0 and figure == 'k' and
(self.converted[i_row - 1][i_figure] == 'k' or self.converted[i_row + 1][i_figure] == 'k' or
self.converted[i_row - 1][i_figure + 1] == 'k' or self.converted[i_row + 1][i_figure + 1] == 'k' or self.converted[i_row][i_figure + 1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(self.converted[i_row - 1][i_figure] == 'k' or self.converted[i_row + 1][i_figure] == 'k' or
self.converted[i_row - 1][i_figure - 1] == 'k' or self.converted[i_row + 1][i_figure - 1] == 'k' or self.converted[i_row][i_figure - 1] == 'k')):
return True
elif (figure == 'k' and
self.converted[i_row - 1][i_figure] == 'k' or self.converted[i_row + 1][i_figure] == 'k' or
self.converted[i_row - 1][i_figure + 1] == 'k' or self.converted[i_row + 1][i_figure + 1] == 'k' or self.converted[i_row][i_figure + 1] == 'k' or
self.converted[i_row - 1][i_figure - 1] == 'k' or self.converted[i_row + 1][i_figure - 1] == 'k' or self.converted[i_row][i_figure - 1] == 'k'):
return True
return False
def __pawns_positions(self):
# Check if the positions of the pawns are correct.
for i_row, row in enumerate(self.converted):
for figure in row:
if figure == 'p' and i_row in (0, 7):
return True
return False
def get_white_score(self):
white_figures = []
for figure in self.fen:
if figure not in chess_figures and figure.isalpha():
white_figures.append(figure.lower())
return ChessScore(white_figures)
def get_black_score(self):
black_figures = []
for figure in self.fen:
if figure in chess_figures:
black_figures.append(figure)
return ChessScore(black_figures)
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()
def __str__(self):
return self.fen
def __len__(self):
figures_amount = 0
for figure in self.fen:
if figure.isalpha():
figures_amount += 1
return figures_amount
def __getitem__(self, position):
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
row = int(position[1])
col = int(letters.index(position[0]))
converted_fen = self.__convert_fen(self.fen)
if converted_fen[row - 1][col].isalpha():
return converted_fen[row - 1][col]
else:
return None
class ChessScore:
def __init__(self, figures):
figures_value = 0
for figure in figures:
if figure not in (chess_figures):
raise ChessException('Wrong figures.')
else:
figures_value += chess_figures[figure]
self.figures = figures
self.figures_value = figures_value
def __gt__(self, other):
# Operator >
if isinstance(other, ChessScore):

Един от малкото хора, които са се сетили да се застраховат, че other е от същия тип - поздравления! Като отключим решенията, можеш да видиш как съм дефинирал тази застраховка чрез декоратор, за да спестя дублиране на код.

return self.figures_value > other.figures_value
else:
raise NotImplemented()
def __ge__(self, other):
# Operator >=
if isinstance(other, ChessScore):
return self.figures_value >= other.figures_value
else:
raise NotImplemented()
def __lt__(self, other):
# Operator <
if isinstance(other, ChessScore):
return self.figures_value < other.figures_value
else:
raise NotImplemented()
def __le__(self, other):
# Operator <=
if isinstance(other, ChessScore):
return self.figures_value <= other.figures_value
else:
raise NotImplemented()
def __eq__(self, other):
# Operator ==
if isinstance(other, ChessScore):
return self.figures_value == other.figures_value
else:
raise NotImplemented()
def __ne__(self, other):
# Operator !=
if isinstance(other, ChessScore):
return self.figures_value != other.figures_value
else:
raise NotImplemented()
def __add__(self, other):
# Operator +
if isinstance(other, ChessScore):
return self.figures_value + other.figures_value
else:
raise NotImplemented()
def __sub__(self, other):
# Operator -
if isinstance(other, ChessScore):
return self.figures_value - other.figures_value
else:
raise NotImplemented()
def __int__(self):
return self.figures_value
def __iadd__(self, other):
# Operator +=
if isinstance(other, ChessScore):
self.figures_value += other.figures_value
return self
else:
raise NotImplemented()
def __isub__(self, other):
# Operator -=
if isinstance(other, ChessScore):
self.figures_value -= other.figures_value
return self
else:
raise NotImplemented()

Лог от изпълнението

..EEEFE.EE..E....
======================================================================
ERROR: test_black_is_winning (test.TestChessPosition)
Test black_is_winning.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
solution.ChessException: kings

======================================================================
ERROR: test_get_black_score (test.TestChessPosition)
Test get_black_score.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
solution.ChessException: kings

======================================================================
ERROR: test_get_white_score (test.TestChessPosition)
Test get_white_score.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
solution.ChessException: kings

======================================================================
ERROR: test_is_equal (test.TestChessPosition)
Test is_equal.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
solution.ChessException: kings

======================================================================
ERROR: test_len (test.TestChessPosition)
Test number of pieces for a position.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
IndexError: string index out of range

======================================================================
ERROR: test_pawns_position (test.TestChessPosition)
Test for incorrect pawns.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
IndexError: string index out of range

======================================================================
ERROR: test_white_is_winning (test.TestChessPosition)
Test white_is_winning.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
solution.ChessException: kings

======================================================================
FAIL: test_getitem (test.TestChessPosition)
Test getitem functionality.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: None != 'K'

----------------------------------------------------------------------
Ran 17 tests in 0.168s

FAILED (failures=1, errors=7)

История (5 версии и 9 коментара)

Огнян обнови решението на 29.11.2022 10:42 (преди почти 2 години)

+chess_figures = {
+ 'r': 5,
+ 'n': 3,
+ 'b': 3,
+ 'q': 5,
+ 'k': 4,
+ 'p': 1,
+}
+
+
+class ChessException(Exception):
+ def __init__(self, message='Wrong chess.'):
+ self._message = message
+ super().__init__(self._message)
+
+
+class ChessPosition:
+
+ def __kings_amount(self, fen):
+ if 0 < fen.count('k') < 2 or 0 < fen.count('K') < 2:
+ return False
+ return True
+
+ def __kings_positions(self, fen):
+ for i_row, row in enumerate(fen):
+ for i_figure, figure in enumerate(row):
+ if i_row == 0 and figure == 'k':
+ if (i_figure == 0 and figure == 'k' and
+ (fen[0][1] == 'k' or fen[1][0] == 'k' or fen[1][1] == 'k')):
+ return True
+ elif (i_figure == 7 and figure == 'k' and
+ (fen[0][6] == 'k' or fen[1][7] == 'k' or fen[1][6] == 'k')):
+ return True
+ elif (figure == 'k' and
+ (fen[0][i_figure - 1] == 'k' or fen[0][i_figure + 1] == 'k' or
+ fen[1][i_figure] == 'k' or fen[1][i_figure - 1] == 'k' or fen[1][i_figure + 1] == 'k')):
+ return True
+
+ elif i_row == 7 and figure == 'k':
+ if (i_figure == 0 and figure == 'k' and
+ (fen[7][1] == 'k' or fen[6][0] == 'k' or fen[6][0] == 'k')):
+ return True
+ elif (i_figure == 7 and figure == 'k' and
+ (fen[7][6] == 'k' or fen[6][7] == 'k' or fen[6][6] == 'k')):
+ return True
+ elif (figure == 'k' and
+ (fen[7][i_figure - 1] == 'k' or fen[7][i_figure + 1] == 'k' or
+ fen[6][i_figure] == 'k' or fen[6][i_figure - 1] == 'k' or fen[6][i_figure + 1] == 'k')):
+ return True
+
+ elif figure == 'k':
+ if (i_figure == 0 and figure == 'k' and
+ (fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
+ fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k')):
+ return True
+ elif (i_figure == 7 and figure == 'k' and
+ (fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
+ fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k')):
+ return True
+ elif (figure == 'k' and
+ fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
+ fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k' or
+ fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k'):
+ return True
+
+ return False
+
+ def __pawns_positions(self, fen):
+ for i_row, row in enumerate(fen):
+ for figure in row:
+ if figure == 'p' and (i_row == 0 or i_row == 7):
+ return True
+ return False
+
+ def __init__(self, fen):
+ self.fen = fen
+ splited = fen.lower().split('/')
+ if (self.__kings_amount(fen) or self.__kings_positions(splited)):
+ raise ChessException('kings')
+ elif (self.__pawns_positions(splited)):
+ raise ChessException('pawns')
+
+ def get_white_score(self):
+ white_figures = []
+ for figure in self.fen:
+ if figure not in chess_figures and figure.isalpha():
+ white_figures.append(figure.lower())
+ return ChessScore(white_figures)
+
+ def get_black_score(self):
+ black_figures = []
+ for figure in self.fen:
+ if figure in chess_figures:
+ black_figures.append(figure)
+ return ChessScore(black_figures)
+
+ 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
+
+ def __str__(self):
+ return self.fen
+
+ def __len__(self):
+ figures_amount = 0
+ for figure in self.fen:
+ if (figure.isalpha()):
+ figures_amount += 1
+ return figures_amount
+
+ def __getitem__(self, position):
+ letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
+ row = 0
+ col = 0
+ for item in position:
+ if item.isalpha():
+ col = letters.index(item)
+ else:
+ row = item
+ if self.fen.split('/')[row][col].isalpha():
+ return self.fen.split('/')[row][col]
+ else:
+ return None
+
+
+class ChessScore:
+ def __init__(self, figures):
+ figures_value = 0
+ for figure in figures:
+ if figure not in (chess_figures):
+ raise ChessException('Wrong figures.')
+ else:
+ figures_value += chess_figures[figure]
+
+ self.figures = figures
+ self.figures_value = figures_value
+
+ def __gt__(self, other): # >
+ if isinstance(other, ChessScore):
+ return self.figures_value > other.figures_value
+ else:
+ raise NotImplemented()
+
+ def __ge__(self, other): # >=
+ if isinstance(other, ChessScore):
+ return self.figures_value >= other.figures_value
+ else:
+ raise NotImplemented()
+
+ def __lt__(self, other): # <
+ if isinstance(other, ChessScore):
+ return self.figures_value < other.figures_value
+ else:
+ raise NotImplemented()
+
+ def __le__(self, other): # <=
+ if isinstance(other, ChessScore):
+ return self.figures_value <= other.figures_value
+ else:
+ raise NotImplemented()
+
+ def __eq__(self, other): # ==
+ if isinstance(other, ChessScore):
+ return self.figures_value == other.figures_value
+ else:
+ raise NotImplemented()
+
+ def __ne__(self, other): # !=
+ if isinstance(other, ChessScore):
+ return self.figures_value != other.figures_value
+ else:
+ raise NotImplemented()
+
+ def __add__(self, other):
+ if isinstance(other, ChessScore):
+ new_figure_value = self.figures_value.copy()
+ new_figure_value += other.figures_value
+ return new_figure_value
+ else:
+ raise NotImplemented()
+
+ def __sub__(self, other):
+ if isinstance(other, ChessScore):
+ new_figure_value = self.figures_value.copy()
+ new_figure_value -= other.figures_value
+ return new_figure_value
+ else:
+ raise NotImplemented()
+
+ def __iadd__(self, other):
+ if isinstance(other, ChessScore):
+ self.figures_value += other.figures_value
+ return self
+ else:
+ raise NotImplemented()
+
+ def __isub__(self, other):
+ if isinstance(other, ChessScore):
+ self.figures_value -= other.figures_value
+ return self
+ else:
+ raise NotImplemented()
+

Огнян обнови решението на 29.11.2022 11:08 (преди почти 2 години)

chess_figures = {
'r': 5,
'n': 3,
'b': 3,
- 'q': 5,
+ 'q': 9,
'k': 4,
'p': 1,
}
class ChessException(Exception):
def __init__(self, message='Wrong chess.'):
self._message = message
super().__init__(self._message)
class ChessPosition:
def __kings_amount(self, fen):
if 0 < fen.count('k') < 2 or 0 < fen.count('K') < 2:
return False
return True
def __kings_positions(self, fen):
for i_row, row in enumerate(fen):
for i_figure, figure in enumerate(row):
if i_row == 0 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
(fen[0][1] == 'k' or fen[1][0] == 'k' or fen[1][1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(fen[0][6] == 'k' or fen[1][7] == 'k' or fen[1][6] == 'k')):
return True
elif (figure == 'k' and
(fen[0][i_figure - 1] == 'k' or fen[0][i_figure + 1] == 'k' or
fen[1][i_figure] == 'k' or fen[1][i_figure - 1] == 'k' or fen[1][i_figure + 1] == 'k')):
return True
elif i_row == 7 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
(fen[7][1] == 'k' or fen[6][0] == 'k' or fen[6][0] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(fen[7][6] == 'k' or fen[6][7] == 'k' or fen[6][6] == 'k')):
return True
elif (figure == 'k' and
(fen[7][i_figure - 1] == 'k' or fen[7][i_figure + 1] == 'k' or
fen[6][i_figure] == 'k' or fen[6][i_figure - 1] == 'k' or fen[6][i_figure + 1] == 'k')):
return True
elif figure == 'k':
if (i_figure == 0 and figure == 'k' and
(fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k')):
return True
elif (figure == 'k' and
fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k' or
fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k'):
return True
return False
def __pawns_positions(self, fen):
for i_row, row in enumerate(fen):
for figure in row:
if figure == 'p' and (i_row == 0 or i_row == 7):
return True
return False
def __init__(self, fen):
self.fen = fen
splited = fen.lower().split('/')
if (self.__kings_amount(fen) or self.__kings_positions(splited)):
raise ChessException('kings')
elif (self.__pawns_positions(splited)):
raise ChessException('pawns')
def get_white_score(self):
white_figures = []
for figure in self.fen:
if figure not in chess_figures and figure.isalpha():
white_figures.append(figure.lower())
return ChessScore(white_figures)
def get_black_score(self):
black_figures = []
for figure in self.fen:
if figure in chess_figures:
black_figures.append(figure)
return ChessScore(black_figures)
def white_is_winning(self):
- return self.get_white_score > self.get_black_score
+ return self.get_white_score() > self.get_black_score()
def black_is_winning(self):
- return self.get_white_score < self.get_black_score
+ return self.get_white_score() < self.get_black_score()
def is_equal(self):
- return self.get_white_score == self.get_black_score
+ return self.get_white_score() == self.get_black_score()
def __str__(self):
return self.fen
def __len__(self):
figures_amount = 0
for figure in self.fen:
if (figure.isalpha()):
figures_amount += 1
return figures_amount
def __getitem__(self, position):
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
row = 0
col = 0
for item in position:
if item.isalpha():
col = letters.index(item)
else:
row = item
if self.fen.split('/')[row][col].isalpha():
return self.fen.split('/')[row][col]
else:
return None
class ChessScore:
def __init__(self, figures):
figures_value = 0
for figure in figures:
if figure not in (chess_figures):
raise ChessException('Wrong figures.')
else:
figures_value += chess_figures[figure]
self.figures = figures
self.figures_value = figures_value
def __gt__(self, other): # >
if isinstance(other, ChessScore):
return self.figures_value > other.figures_value
else:
raise NotImplemented()
def __ge__(self, other): # >=
if isinstance(other, ChessScore):
return self.figures_value >= other.figures_value
else:
raise NotImplemented()
def __lt__(self, other): # <
if isinstance(other, ChessScore):
return self.figures_value < other.figures_value
else:
raise NotImplemented()
def __le__(self, other): # <=
if isinstance(other, ChessScore):
return self.figures_value <= other.figures_value
else:
raise NotImplemented()
def __eq__(self, other): # ==
if isinstance(other, ChessScore):
return self.figures_value == other.figures_value
else:
raise NotImplemented()
def __ne__(self, other): # !=
if isinstance(other, ChessScore):
return self.figures_value != other.figures_value
else:
raise NotImplemented()
def __add__(self, other):
if isinstance(other, ChessScore):
- new_figure_value = self.figures_value.copy()
- new_figure_value += other.figures_value
- return new_figure_value
+ return self.figures_value + other.figures_value
else:
raise NotImplemented()
def __sub__(self, other):
if isinstance(other, ChessScore):
- new_figure_value = self.figures_value.copy()
- new_figure_value -= other.figures_value
- return new_figure_value
+ return self.figures_value - other.figures_value
else:
raise NotImplemented()
+ def __int__(self):
+ return self.figures_value
+
def __iadd__(self, other):
if isinstance(other, ChessScore):
self.figures_value += other.figures_value
return self
else:
raise NotImplemented()
def __isub__(self, other):
if isinstance(other, ChessScore):
self.figures_value -= other.figures_value
return self
else:
raise NotImplemented()
-

Огнян обнови решението на 29.11.2022 12:04 (преди почти 2 години)

chess_figures = {
'r': 5,
'n': 3,
'b': 3,
'q': 9,
'k': 4,
'p': 1,
+ '_': 0,
}
class ChessException(Exception):
def __init__(self, message='Wrong chess.'):
self._message = message
super().__init__(self._message)
class ChessPosition:
+ def __convert_fen(self, fen):
+ new_fen = []
+ old_fen = fen.lower().split('/')
+ for row in old_fen:
+ new_row = ''
+ for figure in row:
+ if figure.isalpha():
+ new_row += figure
+ else:
+ new_row += ''.join('_'*int(figure))
+ new_fen.append(new_row)
+ return new_fen
+
def __kings_amount(self, fen):
- if 0 < fen.count('k') < 2 or 0 < fen.count('K') < 2:
+ if 0 < fen.count('k') < 2 and 0 < fen.count('K') < 2:
return False
return True
def __kings_positions(self, fen):
for i_row, row in enumerate(fen):
for i_figure, figure in enumerate(row):
if i_row == 0 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
(fen[0][1] == 'k' or fen[1][0] == 'k' or fen[1][1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(fen[0][6] == 'k' or fen[1][7] == 'k' or fen[1][6] == 'k')):
return True
elif (figure == 'k' and
(fen[0][i_figure - 1] == 'k' or fen[0][i_figure + 1] == 'k' or
fen[1][i_figure] == 'k' or fen[1][i_figure - 1] == 'k' or fen[1][i_figure + 1] == 'k')):
return True
elif i_row == 7 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
(fen[7][1] == 'k' or fen[6][0] == 'k' or fen[6][0] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(fen[7][6] == 'k' or fen[6][7] == 'k' or fen[6][6] == 'k')):
return True
elif (figure == 'k' and
(fen[7][i_figure - 1] == 'k' or fen[7][i_figure + 1] == 'k' or
fen[6][i_figure] == 'k' or fen[6][i_figure - 1] == 'k' or fen[6][i_figure + 1] == 'k')):
return True
elif figure == 'k':
if (i_figure == 0 and figure == 'k' and
(fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
(fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k')):
return True
elif (figure == 'k' and
fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k' or
fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k'):
return True
return False
def __pawns_positions(self, fen):
for i_row, row in enumerate(fen):
for figure in row:
if figure == 'p' and (i_row == 0 or i_row == 7):
return True
return False
def __init__(self, fen):
self.fen = fen
- splited = fen.lower().split('/')
- if (self.__kings_amount(fen) or self.__kings_positions(splited)):
+ converted = self.__convert_fen(fen)
+ if (self.__kings_amount(fen) or self.__kings_positions(converted)):
raise ChessException('kings')
- elif (self.__pawns_positions(splited)):
+ elif (self.__pawns_positions(converted)):
raise ChessException('pawns')
def get_white_score(self):
white_figures = []
for figure in self.fen:
if figure not in chess_figures and figure.isalpha():
white_figures.append(figure.lower())
return ChessScore(white_figures)
def get_black_score(self):
black_figures = []
for figure in self.fen:
if figure in chess_figures:
black_figures.append(figure)
return ChessScore(black_figures)
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()
def __str__(self):
return self.fen
def __len__(self):
figures_amount = 0
for figure in self.fen:
if (figure.isalpha()):
figures_amount += 1
return figures_amount
def __getitem__(self, position):
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
- row = 0
- col = 0
- for item in position:
- if item.isalpha():
- col = letters.index(item)
- else:
- row = item
- if self.fen.split('/')[row][col].isalpha():
- return self.fen.split('/')[row][col]
+ row = int(position[1])
+ col = int(letters.index(position[0]))
+ converted_fen = self.__convert_fen(self.fen)
+
+ if converted_fen[row - 1][col - 1].isalpha():
+ return converted_fen[row - 1][col - 1]
else:
return None
class ChessScore:
def __init__(self, figures):
figures_value = 0
for figure in figures:
if figure not in (chess_figures):
raise ChessException('Wrong figures.')
else:
figures_value += chess_figures[figure]
self.figures = figures
self.figures_value = figures_value
def __gt__(self, other): # >
if isinstance(other, ChessScore):
return self.figures_value > other.figures_value
else:
raise NotImplemented()
def __ge__(self, other): # >=
if isinstance(other, ChessScore):
return self.figures_value >= other.figures_value
else:
raise NotImplemented()
def __lt__(self, other): # <
if isinstance(other, ChessScore):
return self.figures_value < other.figures_value
else:
raise NotImplemented()
def __le__(self, other): # <=
if isinstance(other, ChessScore):
return self.figures_value <= other.figures_value
else:
raise NotImplemented()
def __eq__(self, other): # ==
if isinstance(other, ChessScore):
return self.figures_value == other.figures_value
else:
raise NotImplemented()
def __ne__(self, other): # !=
if isinstance(other, ChessScore):
return self.figures_value != other.figures_value
else:
raise NotImplemented()
def __add__(self, other):
if isinstance(other, ChessScore):
return self.figures_value + other.figures_value
else:
raise NotImplemented()
def __sub__(self, other):
if isinstance(other, ChessScore):
return self.figures_value - other.figures_value
else:
raise NotImplemented()
def __int__(self):
return self.figures_value
def __iadd__(self, other):
if isinstance(other, ChessScore):
self.figures_value += other.figures_value
return self
else:
raise NotImplemented()
def __isub__(self, other):
if isinstance(other, ChessScore):
self.figures_value -= other.figures_value
return self
else:
raise NotImplemented()
+

Огнян обнови решението на 29.11.2022 13:00 (преди почти 2 години)

chess_figures = {
'r': 5,
'n': 3,
'b': 3,
'q': 9,
'k': 4,
'p': 1,
- '_': 0,
}
class ChessException(Exception):
def __init__(self, message='Wrong chess.'):
self._message = message
super().__init__(self._message)
class ChessPosition:
def __convert_fen(self, fen):

Бих запазаил резултатът от този метод като атрибут на инстанцията, за да не минаваш всеки път през този метод, когато ти трябва да работиш с дъската.

+ # Convert fen to 8x8 chess with spaces.
new_fen = []
old_fen = fen.lower().split('/')
for row in old_fen:
new_row = ''
for figure in row:
if figure.isalpha():
new_row += figure
else:
new_row += ''.join('_'*int(figure))
new_fen.append(new_row)
return new_fen
def __kings_amount(self, fen):
+ # Check if there is only two kings.
if 0 < fen.count('k') < 2 and 0 < fen.count('K') < 2:
return False
return True
def __kings_positions(self, fen):

Можеш да си вземеш конкретните позиции на двата царя (след като вече си се убедил, че са точно два) и да изчлислиш разстоянието между тях. Това ще ти спести цялият този код, който според мен е прекалено сложен и дълъг.

- for i_row, row in enumerate(fen):
+ # Check if the positions of the kings are correct.
+ converted = self.__convert_fen(fen)
+
+ for i_row, row in enumerate(converted):
for i_figure, figure in enumerate(row):
+
if i_row == 0 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
- (fen[0][1] == 'k' or fen[1][0] == 'k' or fen[1][1] == 'k')):
+ (converted[0][1] == 'k' or converted[1][0] == 'k' or converted[1][1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
- (fen[0][6] == 'k' or fen[1][7] == 'k' or fen[1][6] == 'k')):
+ (converted[0][6] == 'k' or converted[1][7] == 'k' or converted[1][6] == 'k')):
return True
elif (figure == 'k' and
- (fen[0][i_figure - 1] == 'k' or fen[0][i_figure + 1] == 'k' or
- fen[1][i_figure] == 'k' or fen[1][i_figure - 1] == 'k' or fen[1][i_figure + 1] == 'k')):
+ (converted[0][i_figure - 1] == 'k' or converted[0][i_figure + 1] == 'k' or
+ converted[1][i_figure] == 'k' or converted[1][i_figure - 1] == 'k' or converted[1][i_figure + 1] == 'k')):
return True
elif i_row == 7 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
- (fen[7][1] == 'k' or fen[6][0] == 'k' or fen[6][0] == 'k')):
+ (converted[7][1] == 'k' or converted[6][0] == 'k' or converted[6][0] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
- (fen[7][6] == 'k' or fen[6][7] == 'k' or fen[6][6] == 'k')):
+ (converted[7][6] == 'k' or converted[6][7] == 'k' or converted[6][6] == 'k')):
return True
elif (figure == 'k' and
- (fen[7][i_figure - 1] == 'k' or fen[7][i_figure + 1] == 'k' or
- fen[6][i_figure] == 'k' or fen[6][i_figure - 1] == 'k' or fen[6][i_figure + 1] == 'k')):
+ (converted[7][i_figure - 1] == 'k' or converted[7][i_figure + 1] == 'k' or
+ converted[6][i_figure] == 'k' or converted[6][i_figure - 1] == 'k' or converted[6][i_figure + 1] == 'k')):
return True
elif figure == 'k':
if (i_figure == 0 and figure == 'k' and
- (fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
- fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k')):
+ (converted[i_row - 1][i_figure] == 'k' or converted[i_row + 1][i_figure] == 'k' or
+ converted[i_row - 1][i_figure + 1] == 'k' or converted[i_row + 1][i_figure + 1] == 'k' or converted[i_row][i_figure + 1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
- (fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
- fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k')):
+ (converted[i_row - 1][i_figure] == 'k' or converted[i_row + 1][i_figure] == 'k' or
+ converted[i_row - 1][i_figure - 1] == 'k' or converted[i_row + 1][i_figure - 1] == 'k' or converted[i_row][i_figure - 1] == 'k')):
return True
elif (figure == 'k' and
- fen[i_row - 1][i_figure] == 'k' or fen[i_row + 1][i_figure] == 'k' or
- fen[i_row - 1][i_figure + 1] == 'k' or fen[i_row + 1][i_figure + 1] == 'k' or fen[i_row][i_figure + 1] == 'k' or
- fen[i_row - 1][i_figure - 1] == 'k' or fen[i_row + 1][i_figure - 1] == 'k' or fen[i_row][i_figure - 1] == 'k'):
+ converted[i_row - 1][i_figure] == 'k' or converted[i_row + 1][i_figure] == 'k' or
+ converted[i_row - 1][i_figure + 1] == 'k' or converted[i_row + 1][i_figure + 1] == 'k' or converted[i_row][i_figure + 1] == 'k' or
+ converted[i_row - 1][i_figure - 1] == 'k' or converted[i_row + 1][i_figure - 1] == 'k' or converted[i_row][i_figure - 1] == 'k'):
return True
return False
def __pawns_positions(self, fen):
- for i_row, row in enumerate(fen):
+ # Check if the positions of the pawns are correct.
+ converted = self.__convert_fen(fen)
+ for i_row, row in enumerate(converted):
for figure in row:
if figure == 'p' and (i_row == 0 or i_row == 7):
return True
return False
def __init__(self, fen):
self.fen = fen
- converted = self.__convert_fen(fen)
- if (self.__kings_amount(fen) or self.__kings_positions(converted)):
+ if (self.__kings_amount(fen) or self.__kings_positions(fen)):
raise ChessException('kings')
- elif (self.__pawns_positions(converted)):
+ elif (self.__pawns_positions(fen)):
raise ChessException('pawns')
def get_white_score(self):
white_figures = []
for figure in self.fen:
if figure not in chess_figures and figure.isalpha():
white_figures.append(figure.lower())
return ChessScore(white_figures)
def get_black_score(self):
black_figures = []
for figure in self.fen:
if figure in chess_figures:
black_figures.append(figure)
return ChessScore(black_figures)
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()
def __str__(self):
return self.fen
def __len__(self):
figures_amount = 0
for figure in self.fen:
if (figure.isalpha()):
figures_amount += 1
return figures_amount
def __getitem__(self, position):
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
row = int(position[1])
col = int(letters.index(position[0]))
converted_fen = self.__convert_fen(self.fen)
-
- if converted_fen[row - 1][col - 1].isalpha():
- return converted_fen[row - 1][col - 1]
+
+ if converted_fen[row - 1][col].isalpha():
+ return converted_fen[row - 1][col]
else:
return None
class ChessScore:
def __init__(self, figures):
figures_value = 0
for figure in figures:
if figure not in (chess_figures):
raise ChessException('Wrong figures.')
else:
figures_value += chess_figures[figure]
self.figures = figures
self.figures_value = figures_value
- def __gt__(self, other): # >
+ def __gt__(self, other):
+ # Operator >
if isinstance(other, ChessScore):

Един от малкото хора, които са се сетили да се застраховат, че other е от същия тип - поздравления! Като отключим решенията, можеш да видиш как съм дефинирал тази застраховка чрез декоратор, за да спестя дублиране на код.

return self.figures_value > other.figures_value
else:
raise NotImplemented()
- def __ge__(self, other): # >=
+ def __ge__(self, other):
+ # Operator >=
if isinstance(other, ChessScore):
return self.figures_value >= other.figures_value
else:
raise NotImplemented()
- def __lt__(self, other): # <
+ def __lt__(self, other):
+ # Operator <
if isinstance(other, ChessScore):
return self.figures_value < other.figures_value
else:
raise NotImplemented()
- def __le__(self, other): # <=
+ def __le__(self, other):
+ # Operator <=
if isinstance(other, ChessScore):
return self.figures_value <= other.figures_value
else:
raise NotImplemented()
- def __eq__(self, other): # ==
+ def __eq__(self, other):
+ # Operator ==
if isinstance(other, ChessScore):
return self.figures_value == other.figures_value
else:
raise NotImplemented()
- def __ne__(self, other): # !=
+ def __ne__(self, other):
+ # Operator !=
if isinstance(other, ChessScore):
return self.figures_value != other.figures_value
else:
raise NotImplemented()
def __add__(self, other):
+ # Operator +
if isinstance(other, ChessScore):
return self.figures_value + other.figures_value
else:
raise NotImplemented()
def __sub__(self, other):
+ # Operator -
if isinstance(other, ChessScore):
return self.figures_value - other.figures_value
else:
raise NotImplemented()
def __int__(self):
return self.figures_value
def __iadd__(self, other):
+ # Operator +=
if isinstance(other, ChessScore):
self.figures_value += other.figures_value
return self
else:
raise NotImplemented()
def __isub__(self, other):
+ # Operator -=
if isinstance(other, ChessScore):
self.figures_value -= other.figures_value
return self
else:
raise NotImplemented()

Огнян обнови решението на 29.11.2022 17:18 (преди почти 2 години)

chess_figures = {
'r': 5,
'n': 3,
'b': 3,
'q': 9,
'k': 4,
'p': 1,
}
class ChessException(Exception):
def __init__(self, message='Wrong chess.'):
self._message = message
super().__init__(self._message)
class ChessPosition:
+ def __init__(self, fen):
+ self.fen = fen
+ self.converted = self.__convert_fen(fen)
+ if (self.__kings_amount() or self.__kings_positions()):
+ raise ChessException('kings')
+ elif (self.__pawns_positions()):
+ raise ChessException('pawns')
+
def __convert_fen(self, fen):
# Convert fen to 8x8 chess with spaces.
new_fen = []
old_fen = fen.lower().split('/')
for row in old_fen:
new_row = ''
for figure in row:
if figure.isalpha():
new_row += figure
else:
new_row += ''.join('_'*int(figure))
new_fen.append(new_row)
return new_fen
- def __kings_amount(self, fen):
+ def __kings_amount(self):
# Check if there is only two kings.
- if 0 < fen.count('k') < 2 and 0 < fen.count('K') < 2:
- return False
- return True
+ return self.fen.count('k') != 1 or self.fen.count('K') != 1
- def __kings_positions(self, fen):
+ def __kings_positions(self):
# Check if the positions of the kings are correct.
- converted = self.__convert_fen(fen)
-
- for i_row, row in enumerate(converted):
+ for i_row, row in enumerate(self.converted):
for i_figure, figure in enumerate(row):
if i_row == 0 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
- (converted[0][1] == 'k' or converted[1][0] == 'k' or converted[1][1] == 'k')):
+ (self.converted[0][1] == 'k' or self.converted[1][0] == 'k' or self.converted[1][1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
- (converted[0][6] == 'k' or converted[1][7] == 'k' or converted[1][6] == 'k')):
+ (self.converted[0][6] == 'k' or self.converted[1][7] == 'k' or self.converted[1][6] == 'k')):
return True
elif (figure == 'k' and
- (converted[0][i_figure - 1] == 'k' or converted[0][i_figure + 1] == 'k' or
- converted[1][i_figure] == 'k' or converted[1][i_figure - 1] == 'k' or converted[1][i_figure + 1] == 'k')):
+ (self.converted[0][i_figure - 1] == 'k' or self.converted[0][i_figure + 1] == 'k' or
+ self.converted[1][i_figure] == 'k' or self.converted[1][i_figure - 1] == 'k' or self.converted[1][i_figure + 1] == 'k')):
return True
elif i_row == 7 and figure == 'k':
if (i_figure == 0 and figure == 'k' and
- (converted[7][1] == 'k' or converted[6][0] == 'k' or converted[6][0] == 'k')):
+ (self.converted[7][1] == 'k' or self.converted[6][0] == 'k' or self.converted[6][0] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
- (converted[7][6] == 'k' or converted[6][7] == 'k' or converted[6][6] == 'k')):
+ (self.converted[7][6] == 'k' or self.converted[6][7] == 'k' or self.converted[6][6] == 'k')):
return True
elif (figure == 'k' and
- (converted[7][i_figure - 1] == 'k' or converted[7][i_figure + 1] == 'k' or
- converted[6][i_figure] == 'k' or converted[6][i_figure - 1] == 'k' or converted[6][i_figure + 1] == 'k')):
+ (self.converted[7][i_figure - 1] == 'k' or self.converted[7][i_figure + 1] == 'k' or
+ self.converted[6][i_figure] == 'k' or self.converted[6][i_figure - 1] == 'k' or self.converted[6][i_figure + 1] == 'k')):
return True
elif figure == 'k':
if (i_figure == 0 and figure == 'k' and
- (converted[i_row - 1][i_figure] == 'k' or converted[i_row + 1][i_figure] == 'k' or
- converted[i_row - 1][i_figure + 1] == 'k' or converted[i_row + 1][i_figure + 1] == 'k' or converted[i_row][i_figure + 1] == 'k')):
+ (self.converted[i_row - 1][i_figure] == 'k' or self.converted[i_row + 1][i_figure] == 'k' or
+ self.converted[i_row - 1][i_figure + 1] == 'k' or self.converted[i_row + 1][i_figure + 1] == 'k' or self.converted[i_row][i_figure + 1] == 'k')):
return True
elif (i_figure == 7 and figure == 'k' and
- (converted[i_row - 1][i_figure] == 'k' or converted[i_row + 1][i_figure] == 'k' or
- converted[i_row - 1][i_figure - 1] == 'k' or converted[i_row + 1][i_figure - 1] == 'k' or converted[i_row][i_figure - 1] == 'k')):
+ (self.converted[i_row - 1][i_figure] == 'k' or self.converted[i_row + 1][i_figure] == 'k' or
+ self.converted[i_row - 1][i_figure - 1] == 'k' or self.converted[i_row + 1][i_figure - 1] == 'k' or self.converted[i_row][i_figure - 1] == 'k')):
return True
elif (figure == 'k' and
- converted[i_row - 1][i_figure] == 'k' or converted[i_row + 1][i_figure] == 'k' or
- converted[i_row - 1][i_figure + 1] == 'k' or converted[i_row + 1][i_figure + 1] == 'k' or converted[i_row][i_figure + 1] == 'k' or
- converted[i_row - 1][i_figure - 1] == 'k' or converted[i_row + 1][i_figure - 1] == 'k' or converted[i_row][i_figure - 1] == 'k'):
+ self.converted[i_row - 1][i_figure] == 'k' or self.converted[i_row + 1][i_figure] == 'k' or
+ self.converted[i_row - 1][i_figure + 1] == 'k' or self.converted[i_row + 1][i_figure + 1] == 'k' or self.converted[i_row][i_figure + 1] == 'k' or
+ self.converted[i_row - 1][i_figure - 1] == 'k' or self.converted[i_row + 1][i_figure - 1] == 'k' or self.converted[i_row][i_figure - 1] == 'k'):
return True
return False
- def __pawns_positions(self, fen):
+ def __pawns_positions(self):
# Check if the positions of the pawns are correct.
- converted = self.__convert_fen(fen)
- for i_row, row in enumerate(converted):
+ for i_row, row in enumerate(self.converted):
for figure in row:
- if figure == 'p' and (i_row == 0 or i_row == 7):
+ if figure == 'p' and i_row in (0, 7):
return True
return False
- def __init__(self, fen):
- self.fen = fen
- if (self.__kings_amount(fen) or self.__kings_positions(fen)):
- raise ChessException('kings')
- elif (self.__pawns_positions(fen)):
- raise ChessException('pawns')
-
def get_white_score(self):
white_figures = []
for figure in self.fen:
if figure not in chess_figures and figure.isalpha():
white_figures.append(figure.lower())
return ChessScore(white_figures)
def get_black_score(self):
black_figures = []
for figure in self.fen:
if figure in chess_figures:
black_figures.append(figure)
return ChessScore(black_figures)
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()
def __str__(self):
return self.fen
def __len__(self):
figures_amount = 0
for figure in self.fen:
- if (figure.isalpha()):
+ if figure.isalpha():
figures_amount += 1
return figures_amount
def __getitem__(self, position):
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
row = int(position[1])
col = int(letters.index(position[0]))
converted_fen = self.__convert_fen(self.fen)
if converted_fen[row - 1][col].isalpha():
return converted_fen[row - 1][col]
else:
return None
class ChessScore:
def __init__(self, figures):
figures_value = 0
for figure in figures:
if figure not in (chess_figures):
raise ChessException('Wrong figures.')
else:
figures_value += chess_figures[figure]
self.figures = figures
self.figures_value = figures_value
def __gt__(self, other):
# Operator >
if isinstance(other, ChessScore):
return self.figures_value > other.figures_value
else:
raise NotImplemented()
def __ge__(self, other):
# Operator >=
if isinstance(other, ChessScore):
return self.figures_value >= other.figures_value
else:
raise NotImplemented()
- def __lt__(self, other):
+ def __lt__(self, other):
# Operator <
if isinstance(other, ChessScore):
return self.figures_value < other.figures_value
else:
raise NotImplemented()
- def __le__(self, other):
+ def __le__(self, other):
# Operator <=
if isinstance(other, ChessScore):
return self.figures_value <= other.figures_value
else:
raise NotImplemented()
- def __eq__(self, other):
+ def __eq__(self, other):
# Operator ==
if isinstance(other, ChessScore):
return self.figures_value == other.figures_value
else:
raise NotImplemented()
- def __ne__(self, other):
+ def __ne__(self, other):
# Operator !=
if isinstance(other, ChessScore):
return self.figures_value != other.figures_value
else:
raise NotImplemented()
def __add__(self, other):
# Operator +
if isinstance(other, ChessScore):
return self.figures_value + other.figures_value
else:
raise NotImplemented()
def __sub__(self, other):
# Operator -
if isinstance(other, ChessScore):
return self.figures_value - other.figures_value
else:
raise NotImplemented()
def __int__(self):
return self.figures_value
def __iadd__(self, other):
# Operator +=
if isinstance(other, ChessScore):
self.figures_value += other.figures_value
return self
else:
raise NotImplemented()
def __isub__(self, other):
# Operator -=
if isinstance(other, ChessScore):
self.figures_value -= other.figures_value
return self
else:
raise NotImplemented()

тук съм оправил сложния метод

chess_figures = { 'r': 5, 'n': 3, 'b': 3, 'q': 9, 'k': 4, 'p': 1, }

class ChessException(Exception): def init(self, message='Wrong chess.'): self.message = message super().init(self.message)

class ChessPosition: def init(self, fen): self.fen = fen self.converted = self.convert_fen(fen) if (self.kings_amount() or self.kings_positions()): raise ChessException('kings') elif (self.pawns_positions()): raise ChessException('pawns')

def __convert_fen(self, fen):
    # Convert fen to 8x8 chess with spaces.
    new_fen = []
    old_fen = fen.split('/')
    for row in old_fen:
        new_row = ''
        for figure in row:
            if figure.isalpha():
                new_row += figure
            else:
                new_row += ''.join('_'*int(figure))
        new_fen.append(new_row)

    return new_fen

def __kings_amount(self):
    # Check if there is only two kings.
    return self.fen.count('k') != 1 or self.fen.count('K') != 1

def __kings_positions(self):
    # Check if the positions of the kings are correct.
    black_king = []
    white_king = []
    for i_row, row in enumerate(self.converted):
        for i_figure, figure in enumerate(row):
            if figure == 'k':
                black_king = [i_row, i_figure]
            elif figure == 'K':
                white_king = [i_row, i_figure]

    return abs(black_king[0] - white_king[0]) <= 1 and abs(black_king[1] - white_king[1])

def __pawns_positions(self):
    # Check if the positions of the pawns are correct.
    for i_row, row in enumerate(self.converted):
        for figure in row:
            if figure in ('p', 'P') and i_row in (0, 7):
                return True
    return False

def get_white_score(self):
    white_figures = []
    for figure in self.fen:
        if figure not in chess_figures and figure.isalpha():
            white_figures.append(figure.lower())
    return ChessScore(white_figures)

def get_black_score(self):
    black_figures = []
    for figure in self.fen:
        if figure in chess_figures:
            black_figures.append(figure)
    return ChessScore(black_figures)

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()

def __str__(self):
    return self.fen

def __len__(self):
    figures_amount = 0
    for figure in self.fen:
        if figure.isalpha():
            figures_amount += 1
    return figures_amount

def __getitem__(self, position):
    letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
    row = int(position[1])
    col = int(letters.index(position[0]))

    if self.converted[row - 1][col].isalpha():
        return self.converted[row - 1][col]
    else:
        return None

class ChessScore: def init(self, figures): figures_value = 0 for figure in figures: if figure.lower() not in (chess_figures): raise ChessException('Wrong figures.') else: figures_value += chess_figures[figure.lower()]

    self.figures = figures
    self.figures_value = figures_value

def __gt__(self, other):
    # Operator >
    if isinstance(other, ChessScore):
        return self.figures_value > other.figures_value
    else:
        raise NotImplemented()

def __ge__(self, other):
    # Operator >=
    if isinstance(other, ChessScore):
        return self.figures_value >= other.figures_value
    else:
        raise NotImplemented()

def __lt__(self, other):
    # Operator <
    if isinstance(other, ChessScore):
        return self.figures_value < other.figures_value
    else:
        raise NotImplemented()

def __le__(self, other):
    # Operator <=
    if isinstance(other, ChessScore):
        return self.figures_value <= other.figures_value
    else:
        raise NotImplemented()

def __eq__(self, other):
    # Operator ==
    if isinstance(other, ChessScore):
        return self.figures_value == other.figures_value
    else:
        raise NotImplemented()

def __ne__(self, other):
    # Operator !=
    if isinstance(other, ChessScore):
        return self.figures_value != other.figures_value
    else:
        raise NotImplemented()

def __add__(self, other):
    # Operator +
    if isinstance(other, ChessScore):
        return self.figures_value + other.figures_value
    else:
        raise NotImplemented()

def __sub__(self, other):
    # Operator -
    if isinstance(other, ChessScore):
        return self.figures_value - other.figures_value
    else:
        raise NotImplemented()

def __int__(self):
    return self.figures_value

def __iadd__(self, other):
    # Operator +=
    if isinstance(other, ChessScore):
        self.figures_value += other.figures_value
        return self
    else:
        raise NotImplemented()

def __isub__(self, other):
    # Operator -=
    if isinstance(other, ChessScore):
        self.figures_value -= other.figures_value
        return self
    else:
        raise NotImplemented()