Решение на Шахматни фенове от Надежда Панделиева

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

Към профила на Надежда Панделиева

Резултати

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

Код

import re
from typing import List
class ChessException(Exception):
pass
files = ["A", "B", "C", "D", "E", "F", "G", "H"]
ranks = ["8", "7", "6", "5", "4", "3", "2", "1"]
class ChessPosition:
def __init__(self, fen: str):
self.fen = self.is_valid_notation(fen)
self.list_fen = self._get_list_of_figures(fen)
self.white, self.black = self._get_white_and_black_str(self.list_fen)
def _get_list_of_figures(self, fen):
return fen.split(" ")[0].split("/")
def _get_white_and_black_str(self, list_fen):
black_re = re.compile("([kqbnrp])")
white_re = re.compile("([KQBNRP])")
white_piece_tokens = []
black_piece_tokens_black = []
for rank in list_fen:
white_piece_tokens.extend(white_re.findall(rank))
black_piece_tokens_black.extend(black_re.findall(rank))
return white_piece_tokens, black_piece_tokens_black
def get_white_score(self):
return ChessScore(self.white)
def get_black_score(self):
return ChessScore(self.black)
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 __len__(self):
piece_re = re.compile("([kqbnrpKQBNRP])")
piece_tokens = []
for rank in self.list_fen:
piece_tokens.extend(piece_re.findall(rank))
return len(piece_tokens)
def __str__(self):
return self.fen
def __getitem__(self, item):
if item[0] in files and item[1] in ranks:
return self.list_fen[ranks.index(item[1])][files.index(item[0])]
else:
return None
def _generate_matrix(self, list_fen):
matrix = []
piece_re = re.compile("([kqbnrpKQBNRP])")
ret_val = ""
for rank in list_fen:
for r in rank:
if piece_re.match(r):
ret_val += r
else:
ret_val += int(r) * " "
matrix.append([*ret_val])
ret_val = ""
return matrix
def _check_count_of_kings(self, fen):
white, black = self._get_white_and_black_str(self._get_list_of_figures(fen))
kings = white.count("K") + black.count("k")
return kings == 2
def _check_pos_of_pawns(self, fen):
list_fen = self._get_list_of_figures(fen)
if (
"p" in list_fen[0]
or "P" in list_fen[0]
or "p" in list_fen[7]
or "P" in list_fen[7]
):
return False
else:
return True
def _check_pos_of_kings(self, fen):
list_fen = self._get_list_of_figures(fen)
board = self._generate_matrix(list_fen)
pos_of_black_king = ()
pos_of_white_king = ()
for i, row in enumerate(board):
if "k" in row:
pos_of_black_king = (i, row.index("k"))
if "K" in row:
pos_of_white_king = (i, row.index("K"))
if pos_of_black_king[0] == pos_of_white_king[0] and pos_of_white_king[1] in (
pos_of_black_king[1] - 1,
pos_of_black_king[1] + 1,
):
return False
if pos_of_white_king[0] in (
pos_of_black_king[0] - 1,
pos_of_black_king[0] + 1,
) and pos_of_white_king[1] in (
pos_of_black_king[1] - 1,
pos_of_black_king[1],
pos_of_black_king[1] + 1,
):
return False
return True
def is_valid_notation(self, notation):
if not self._check_count_of_kings(notation):
raise ChessException("kings")
elif not self._check_pos_of_kings(notation):
raise ChessException("kings")
elif not self._check_pos_of_pawns(notation):
raise ChessException("pawns")
else:
return notation
class ChessScore:
def __init__(self, figures: List[str]):
self.figures = figures
self.__points = {"k": 4, "r": 5, "n": 3, "b": 3, "q": 9, "p": 1}
self.score = self.get_points()
def get_points(self):
sum_of_points = sum(
[self.__points.get(figure.lower(), 0) for figure in self.figures]
)
return sum_of_points
def __lt__(self, other):
return self.score < other.score
def __le__(self, other):
return self.score <= other.score
def __gt__(self, other):
return self.score > other.score
def __eq__(self, other):
return self.score == other.score
def __ne__(self, other):
return self.score != other.score
def __add__(self, other):
return self.score + other.score
def __sub__(self, other):
return self.score - other.score
# def __repr__(self):
# return str(self.score)
def __int__(self):
return self.score

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

.....E...........
======================================================================
ERROR: 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
IndexError: string index out of range

----------------------------------------------------------------------
Ran 17 tests in 0.183s

FAILED (errors=1)

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

Надежда обнови решението на 29.11.2022 07:18 (преди почти 2 години)

+import re
+
+"""
+Малко тъпо си написах методите, ама докато се усетя, че с матрица ще е по-лесно
+вече бях написала почти всичко и ме мързеше да променя нещата.
+"""
+
+
+class ChessException(Exception):
+ def __init__(self, message):
+ self._message = message
+ super().__init__(self._message)
+
+
+files = ["A", "B", "C", "D", "E", "F", "G", "H"]
+ranks = ["8", "7", "6", "5", "4", "3", "2", "1"]
+
+
+class ChessPosition:
+ def __init__(self, fen: str):
+ self.fen = self.is_valid_notation(fen)
+ self.list_fen = self.__get_list_of_figures(fen)
+ self.white, self.black = self.__get_white_and_black_str(self.list_fen)
+
+ def __get_list_of_figures(self, fen):
+ return fen.split(" ")[0].split("/")
+
+ def __get_white_and_black_str(self, list_fen):
+ black_re = re.compile("([kqbnrp])")
+ white_re = re.compile("([KQBNRP])")
+
+ white_piece_tokens = []
+ black_piece_tokens_black = []
+ for rank in list_fen:
+ white_piece_tokens.extend(white_re.findall(rank))
+ black_piece_tokens_black.extend(black_re.findall(rank))
+
+ return white_piece_tokens, black_piece_tokens_black
+
+ def get_white_score(self):
+ return ChessScore(self.white)
+
+ def get_black_score(self):
+ return ChessScore(self.black)
+
+ 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 __len__(self):
+ piece_re = re.compile("([kqbnrpKQBNRP])")
+ piece_tokens = []
+ for rank in self.list_fen:
+ piece_tokens.extend(piece_re.findall(rank))
+
+ return len(piece_tokens)
+
+ def __str__(self):
+ return self.fen
+
+ def __getitem__(self, item):
+ if item[0] in files and item[1] in ranks:
+ return self.list_fen[ranks.index(item[1])][files.index(item[0])]
+ else:
+ return None
+
+ def generate_matrix(self, list_fen):
+ matrix = []
+ piece_re = re.compile("([kqbnrpKQBNRP])")
+ ret_val = ""
+ for rank in list_fen:
+ for r in rank:
+ if piece_re.match(r):
+ ret_val += r
+ else:
+ ret_val += int(r) * " "
+ matrix.append([*ret_val])
+ ret_val = ""
+ return matrix
+
+ def check_count_of_kings(self, fen):
+ white, black = self.__get_white_and_black_str(self.__get_list_of_figures(fen))
+ kings = white.count('K') + black.count('k')
+
+ return True if kings == 2 else False
+
+ def check_pos_of_pawns(self, fen):
+ list_fen = self.__get_list_of_figures(fen)
+ if 'p' in list_fen[0] or 'P' in list_fen[0] or 'p' in list_fen[7] or 'P' in list_fen[7]:
+ return False
+ else:
+ return True
+
+ def check_pos_of_kings(self, fen):
+ list_fen = self.__get_list_of_figures(fen)
+ board = self.generate_matrix(list_fen)
+ pos_of_black_king = ()
+ pos_of_white_king = ()
+ for i, row in enumerate(board):
+ if 'k' in row:
+ pos_of_black_king = (i, row.index('k'))
+ if 'K' in row:
+ pos_of_white_king = (i, row.index('K'))
+
+ if pos_of_black_king[0] == pos_of_black_king[0] and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
+ return False
+ if pos_of_black_king[1] == pos_of_black_king[1] and abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1:
+ return False
+ if abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1 and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
+ return False
+
+ return True
+
+ def is_valid_notation(self, notation):
+ if not self.check_count_of_kings(notation):
+ raise ChessException("kings")
+ elif not self.check_pos_of_kings(notation):
+ raise ChessException("kings")
+ elif not self.check_pos_of_pawns(notation):
+ raise ChessException("pawns")
+ else:
+ return notation
+
+
+
+class ChessScore:
+ def __init__(self, figures: List[str]):
+ self.figures = figures
+ self.__points = {'k': 4, 'r': 5, 'n': 3, 'b': 3, 'q': 9, 'p': 1}
+ self.score = self.get_points()
+
+ def get_points(self):
+ sum_of_points = sum(
+ [self.__points.get(figure.lower()) for figure in self.figures if figure.lower() in self.__points.keys()]
+ )
+ return sum_of_points
+
+ def __lt__(self, other):
+ return self.score < other.score
+
+ def __le__(self, other):
+ return self.score <= other.score
+
+ def __gt__(self, other):
+ return self.score > other.score
+
+ def __eq__(self, other):
+ return self.score == other.score
+
+ def __ne__(self, other):
+ return self.score != other.score
+
+ def __add__(self, other):
+ return self.score + other.score
+
+ def __sub__(self, other):
+ return self.score - other.score
+
+ # def __repr__(self):
+ # return str(self.score)
+
+ def __int__(self):
+ return self.score

Надежда обнови решението на 29.11.2022 12:16 (преди почти 2 години)

import re
"""
Малко тъпо си написах методите, ама докато се усетя, че с матрица ще е по-лесно
вече бях написала почти всичко и ме мързеше да променя нещата.
"""
class ChessException(Exception):
def __init__(self, message):
self._message = message
super().__init__(self._message)
files = ["A", "B", "C", "D", "E", "F", "G", "H"]
ranks = ["8", "7", "6", "5", "4", "3", "2", "1"]
class ChessPosition:
def __init__(self, fen: str):
self.fen = self.is_valid_notation(fen)
self.list_fen = self.__get_list_of_figures(fen)
self.white, self.black = self.__get_white_and_black_str(self.list_fen)
def __get_list_of_figures(self, fen):
return fen.split(" ")[0].split("/")
def __get_white_and_black_str(self, list_fen):
black_re = re.compile("([kqbnrp])")
white_re = re.compile("([KQBNRP])")
white_piece_tokens = []
black_piece_tokens_black = []
for rank in list_fen:
white_piece_tokens.extend(white_re.findall(rank))
black_piece_tokens_black.extend(black_re.findall(rank))
return white_piece_tokens, black_piece_tokens_black
def get_white_score(self):
return ChessScore(self.white)
def get_black_score(self):
return ChessScore(self.black)
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 __len__(self):
piece_re = re.compile("([kqbnrpKQBNRP])")
piece_tokens = []
for rank in self.list_fen:
piece_tokens.extend(piece_re.findall(rank))
return len(piece_tokens)
def __str__(self):
return self.fen
def __getitem__(self, item):
if item[0] in files and item[1] in ranks:
return self.list_fen[ranks.index(item[1])][files.index(item[0])]
else:
return None
def generate_matrix(self, list_fen):
matrix = []
piece_re = re.compile("([kqbnrpKQBNRP])")
ret_val = ""
for rank in list_fen:
for r in rank:
if piece_re.match(r):
ret_val += r
else:
ret_val += int(r) * " "
matrix.append([*ret_val])
ret_val = ""
return matrix
def check_count_of_kings(self, fen):
white, black = self.__get_white_and_black_str(self.__get_list_of_figures(fen))
kings = white.count('K') + black.count('k')
return True if kings == 2 else False
def check_pos_of_pawns(self, fen):
list_fen = self.__get_list_of_figures(fen)
if 'p' in list_fen[0] or 'P' in list_fen[0] or 'p' in list_fen[7] or 'P' in list_fen[7]:
return False
else:
return True
def check_pos_of_kings(self, fen):
list_fen = self.__get_list_of_figures(fen)
board = self.generate_matrix(list_fen)
pos_of_black_king = ()
pos_of_white_king = ()
for i, row in enumerate(board):
if 'k' in row:
pos_of_black_king = (i, row.index('k'))
if 'K' in row:
pos_of_white_king = (i, row.index('K'))
if pos_of_black_king[0] == pos_of_black_king[0] and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
return False
if pos_of_black_king[1] == pos_of_black_king[1] and abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1:
return False
if abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1 and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
return False
return True
def is_valid_notation(self, notation):
if not self.check_count_of_kings(notation):
raise ChessException("kings")
elif not self.check_pos_of_kings(notation):
raise ChessException("kings")
elif not self.check_pos_of_pawns(notation):
raise ChessException("pawns")
else:
return notation
class ChessScore:
- def __init__(self, figures: List[str]):
+ def __init__(self, figures):
self.figures = figures
self.__points = {'k': 4, 'r': 5, 'n': 3, 'b': 3, 'q': 9, 'p': 1}
self.score = self.get_points()
def get_points(self):
sum_of_points = sum(
[self.__points.get(figure.lower()) for figure in self.figures if figure.lower() in self.__points.keys()]
)
return sum_of_points
def __lt__(self, other):
return self.score < other.score
def __le__(self, other):
return self.score <= other.score
def __gt__(self, other):
return self.score > other.score
def __eq__(self, other):
return self.score == other.score
def __ne__(self, other):
return self.score != other.score
def __add__(self, other):
return self.score + other.score
def __sub__(self, other):
return self.score - other.score
# def __repr__(self):
# return str(self.score)
def __int__(self):
return self.score

Надежда обнови решението на 29.11.2022 12:31 (преди почти 2 години)

import re
+from typing import List
-"""
-Малко тъпо си написах методите, ама докато се усетя, че с матрица ще е по-лесно
-вече бях написала почти всичко и ме мързеше да променя нещата.
-"""
-
-
class ChessException(Exception):
def __init__(self, message):
self._message = message
super().__init__(self._message)
files = ["A", "B", "C", "D", "E", "F", "G", "H"]
ranks = ["8", "7", "6", "5", "4", "3", "2", "1"]
class ChessPosition:
def __init__(self, fen: str):
self.fen = self.is_valid_notation(fen)
self.list_fen = self.__get_list_of_figures(fen)
self.white, self.black = self.__get_white_and_black_str(self.list_fen)
def __get_list_of_figures(self, fen):
return fen.split(" ")[0].split("/")
def __get_white_and_black_str(self, list_fen):
black_re = re.compile("([kqbnrp])")
white_re = re.compile("([KQBNRP])")
white_piece_tokens = []
black_piece_tokens_black = []
for rank in list_fen:
white_piece_tokens.extend(white_re.findall(rank))
black_piece_tokens_black.extend(black_re.findall(rank))
return white_piece_tokens, black_piece_tokens_black
def get_white_score(self):
return ChessScore(self.white)
def get_black_score(self):
return ChessScore(self.black)
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 __len__(self):
piece_re = re.compile("([kqbnrpKQBNRP])")
piece_tokens = []
for rank in self.list_fen:
piece_tokens.extend(piece_re.findall(rank))
return len(piece_tokens)
def __str__(self):
return self.fen
def __getitem__(self, item):
if item[0] in files and item[1] in ranks:
return self.list_fen[ranks.index(item[1])][files.index(item[0])]
else:
return None
def generate_matrix(self, list_fen):
matrix = []
piece_re = re.compile("([kqbnrpKQBNRP])")
ret_val = ""
for rank in list_fen:
for r in rank:
if piece_re.match(r):
ret_val += r
else:
ret_val += int(r) * " "
matrix.append([*ret_val])
ret_val = ""
return matrix
def check_count_of_kings(self, fen):
white, black = self.__get_white_and_black_str(self.__get_list_of_figures(fen))
kings = white.count('K') + black.count('k')
return True if kings == 2 else False
def check_pos_of_pawns(self, fen):
list_fen = self.__get_list_of_figures(fen)
if 'p' in list_fen[0] or 'P' in list_fen[0] or 'p' in list_fen[7] or 'P' in list_fen[7]:
return False
else:
return True
def check_pos_of_kings(self, fen):
list_fen = self.__get_list_of_figures(fen)
board = self.generate_matrix(list_fen)
pos_of_black_king = ()
pos_of_white_king = ()
for i, row in enumerate(board):
if 'k' in row:
pos_of_black_king = (i, row.index('k'))
if 'K' in row:
pos_of_white_king = (i, row.index('K'))
if pos_of_black_king[0] == pos_of_black_king[0] and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
return False
if pos_of_black_king[1] == pos_of_black_king[1] and abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1:
return False
if abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1 and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
return False
return True
def is_valid_notation(self, notation):
if not self.check_count_of_kings(notation):
raise ChessException("kings")
elif not self.check_pos_of_kings(notation):
raise ChessException("kings")
elif not self.check_pos_of_pawns(notation):
raise ChessException("pawns")
else:
return notation
class ChessScore:
- def __init__(self, figures):
+ def __init__(self, figures: List[str]):
self.figures = figures
self.__points = {'k': 4, 'r': 5, 'n': 3, 'b': 3, 'q': 9, 'p': 1}
self.score = self.get_points()
def get_points(self):
sum_of_points = sum(
[self.__points.get(figure.lower()) for figure in self.figures if figure.lower() in self.__points.keys()]
)
return sum_of_points
def __lt__(self, other):
return self.score < other.score
def __le__(self, other):
return self.score <= other.score
def __gt__(self, other):
return self.score > other.score
def __eq__(self, other):
return self.score == other.score
def __ne__(self, other):
return self.score != other.score
def __add__(self, other):
return self.score + other.score
def __sub__(self, other):
return self.score - other.score
# def __repr__(self):
# return str(self.score)
def __int__(self):
return self.score

Надежда обнови решението на 29.11.2022 17:35 (преди почти 2 години)

import re
from typing import List
class ChessException(Exception):
- def __init__(self, message):
- self._message = message
- super().__init__(self._message)
+ pass
files = ["A", "B", "C", "D", "E", "F", "G", "H"]
ranks = ["8", "7", "6", "5", "4", "3", "2", "1"]
class ChessPosition:
def __init__(self, fen: str):
self.fen = self.is_valid_notation(fen)
- self.list_fen = self.__get_list_of_figures(fen)
- self.white, self.black = self.__get_white_and_black_str(self.list_fen)
+ self.list_fen = self._get_list_of_figures(fen)
+ self.white, self.black = self._get_white_and_black_str(self.list_fen)
- def __get_list_of_figures(self, fen):
+ def _get_list_of_figures(self, fen):
return fen.split(" ")[0].split("/")
- def __get_white_and_black_str(self, list_fen):
+ def _get_white_and_black_str(self, list_fen):
black_re = re.compile("([kqbnrp])")
white_re = re.compile("([KQBNRP])")
white_piece_tokens = []
black_piece_tokens_black = []
for rank in list_fen:
white_piece_tokens.extend(white_re.findall(rank))
black_piece_tokens_black.extend(black_re.findall(rank))
return white_piece_tokens, black_piece_tokens_black
def get_white_score(self):
return ChessScore(self.white)
def get_black_score(self):
return ChessScore(self.black)
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 __len__(self):
piece_re = re.compile("([kqbnrpKQBNRP])")
piece_tokens = []
for rank in self.list_fen:
piece_tokens.extend(piece_re.findall(rank))
return len(piece_tokens)
def __str__(self):
return self.fen
def __getitem__(self, item):
if item[0] in files and item[1] in ranks:
return self.list_fen[ranks.index(item[1])][files.index(item[0])]
else:
return None
def generate_matrix(self, list_fen):
matrix = []
piece_re = re.compile("([kqbnrpKQBNRP])")
ret_val = ""
for rank in list_fen:
for r in rank:
if piece_re.match(r):
ret_val += r
else:
ret_val += int(r) * " "
matrix.append([*ret_val])
ret_val = ""
return matrix
def check_count_of_kings(self, fen):
- white, black = self.__get_white_and_black_str(self.__get_list_of_figures(fen))
+ white, black = self._get_white_and_black_str(self._get_list_of_figures(fen))
kings = white.count('K') + black.count('k')
- return True if kings == 2 else False
+ return kings == 2
def check_pos_of_pawns(self, fen):
- list_fen = self.__get_list_of_figures(fen)
+ list_fen = self._get_list_of_figures(fen)
if 'p' in list_fen[0] or 'P' in list_fen[0] or 'p' in list_fen[7] or 'P' in list_fen[7]:
return False
else:
return True
def check_pos_of_kings(self, fen):
- list_fen = self.__get_list_of_figures(fen)
+ list_fen = self._get_list_of_figures(fen)
board = self.generate_matrix(list_fen)
pos_of_black_king = ()
pos_of_white_king = ()
for i, row in enumerate(board):
if 'k' in row:
pos_of_black_king = (i, row.index('k'))
if 'K' in row:
pos_of_white_king = (i, row.index('K'))
- if pos_of_black_king[0] == pos_of_black_king[0] and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
+ if pos_of_black_king[0] == pos_of_white_king[0] and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
return False
- if pos_of_black_king[1] == pos_of_black_king[1] and abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1:
+ if pos_of_black_king[1] == pos_of_white_king[1] and abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1:
return False
if abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1 and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
return False
return True
def is_valid_notation(self, notation):
if not self.check_count_of_kings(notation):
raise ChessException("kings")
elif not self.check_pos_of_kings(notation):
raise ChessException("kings")
elif not self.check_pos_of_pawns(notation):
raise ChessException("pawns")
else:
return notation
class ChessScore:
def __init__(self, figures: List[str]):
self.figures = figures
self.__points = {'k': 4, 'r': 5, 'n': 3, 'b': 3, 'q': 9, 'p': 1}
self.score = self.get_points()
def get_points(self):
- sum_of_points = sum(
- [self.__points.get(figure.lower()) for figure in self.figures if figure.lower() in self.__points.keys()]
- )
+ sum_of_points = sum([self.__points.get(figure.lower(), 0) for figure in self.figures])
+
return sum_of_points
def __lt__(self, other):
return self.score < other.score
def __le__(self, other):
return self.score <= other.score
def __gt__(self, other):
return self.score > other.score
def __eq__(self, other):
return self.score == other.score
def __ne__(self, other):
return self.score != other.score
def __add__(self, other):
return self.score + other.score
def __sub__(self, other):
return self.score - other.score
# def __repr__(self):
# return str(self.score)
def __int__(self):
return self.score

Надежда обнови решението на 29.11.2022 17:53 (преди почти 2 години)

import re
from typing import List
+
class ChessException(Exception):
pass
files = ["A", "B", "C", "D", "E", "F", "G", "H"]
ranks = ["8", "7", "6", "5", "4", "3", "2", "1"]
class ChessPosition:
def __init__(self, fen: str):
self.fen = self.is_valid_notation(fen)
self.list_fen = self._get_list_of_figures(fen)
self.white, self.black = self._get_white_and_black_str(self.list_fen)
def _get_list_of_figures(self, fen):
return fen.split(" ")[0].split("/")
def _get_white_and_black_str(self, list_fen):
black_re = re.compile("([kqbnrp])")
white_re = re.compile("([KQBNRP])")
white_piece_tokens = []
black_piece_tokens_black = []
for rank in list_fen:
white_piece_tokens.extend(white_re.findall(rank))
black_piece_tokens_black.extend(black_re.findall(rank))
return white_piece_tokens, black_piece_tokens_black
def get_white_score(self):
return ChessScore(self.white)
def get_black_score(self):
return ChessScore(self.black)
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 __len__(self):
piece_re = re.compile("([kqbnrpKQBNRP])")
piece_tokens = []
for rank in self.list_fen:
piece_tokens.extend(piece_re.findall(rank))
return len(piece_tokens)
def __str__(self):
return self.fen
def __getitem__(self, item):
if item[0] in files and item[1] in ranks:
return self.list_fen[ranks.index(item[1])][files.index(item[0])]
else:
return None
- def generate_matrix(self, list_fen):
+ def _generate_matrix(self, list_fen):
matrix = []
piece_re = re.compile("([kqbnrpKQBNRP])")
ret_val = ""
for rank in list_fen:
for r in rank:
if piece_re.match(r):
ret_val += r
else:
ret_val += int(r) * " "
matrix.append([*ret_val])
ret_val = ""
return matrix
- def check_count_of_kings(self, fen):
+ def _check_count_of_kings(self, fen):
white, black = self._get_white_and_black_str(self._get_list_of_figures(fen))
- kings = white.count('K') + black.count('k')
+ kings = white.count("K") + black.count("k")
return kings == 2
- def check_pos_of_pawns(self, fen):
+ def _check_pos_of_pawns(self, fen):
list_fen = self._get_list_of_figures(fen)
- if 'p' in list_fen[0] or 'P' in list_fen[0] or 'p' in list_fen[7] or 'P' in list_fen[7]:
+ if (
+ "p" in list_fen[0]
+ or "P" in list_fen[0]
+ or "p" in list_fen[7]
+ or "P" in list_fen[7]
+ ):
return False
else:
return True
- def check_pos_of_kings(self, fen):
+ def _check_pos_of_kings(self, fen):
list_fen = self._get_list_of_figures(fen)
- board = self.generate_matrix(list_fen)
+ board = self._generate_matrix(list_fen)
pos_of_black_king = ()
pos_of_white_king = ()
for i, row in enumerate(board):
- if 'k' in row:
- pos_of_black_king = (i, row.index('k'))
- if 'K' in row:
- pos_of_white_king = (i, row.index('K'))
+ if "k" in row:
+ pos_of_black_king = (i, row.index("k"))
+ if "K" in row:
+ pos_of_white_king = (i, row.index("K"))
- if pos_of_black_king[0] == pos_of_white_king[0] and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
+ if pos_of_black_king[0] == pos_of_white_king[0] and pos_of_white_king[1] in (
+ pos_of_black_king[1] - 1,
+ pos_of_black_king[1] + 1,
+ ):
return False
- if pos_of_black_king[1] == pos_of_white_king[1] and abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1:
+ if pos_of_white_king[0] in (
+ pos_of_black_king[0] - 1,
+ pos_of_black_king[0] + 1,
+ ) and pos_of_white_king[1] in (
+ pos_of_black_king[1] - 1,
+ pos_of_black_king[1],
+ pos_of_black_king[1] + 1,
+ ):
return False
- if abs(pos_of_black_king[0] - pos_of_white_king[0]) == 1 and abs(pos_of_black_king[1] - pos_of_white_king[1]) == 1:
- return False
return True
def is_valid_notation(self, notation):
- if not self.check_count_of_kings(notation):
+ if not self._check_count_of_kings(notation):
raise ChessException("kings")
- elif not self.check_pos_of_kings(notation):
+ elif not self._check_pos_of_kings(notation):
raise ChessException("kings")
- elif not self.check_pos_of_pawns(notation):
+ elif not self._check_pos_of_pawns(notation):
raise ChessException("pawns")
else:
return notation
-
class ChessScore:
def __init__(self, figures: List[str]):
self.figures = figures
- self.__points = {'k': 4, 'r': 5, 'n': 3, 'b': 3, 'q': 9, 'p': 1}
+ self.__points = {"k": 4, "r": 5, "n": 3, "b": 3, "q": 9, "p": 1}
self.score = self.get_points()
def get_points(self):
- sum_of_points = sum([self.__points.get(figure.lower(), 0) for figure in self.figures])
+ sum_of_points = sum(
+ [self.__points.get(figure.lower(), 0) for figure in self.figures]
+ )
return sum_of_points
def __lt__(self, other):
return self.score < other.score
def __le__(self, other):
return self.score <= other.score
def __gt__(self, other):
return self.score > other.score
def __eq__(self, other):
return self.score == other.score
def __ne__(self, other):
return self.score != other.score
def __add__(self, other):
return self.score + other.score
def __sub__(self, other):
return self.score - other.score
# def __repr__(self):
# return str(self.score)
def __int__(self):
- return self.score
+ return self.score