Дейвид обнови решението на 29.11.2022 16:32 (преди почти 2 години)
+""""
+Created by David Kamenov 62585
+Homework 4
+
+Task:
+# start position of party:
+# rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
+# position: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
+# Figures
+# "R/r" - Rook (топ) - 5 points
+# "N/n" - Knight (кон) /използва се "N", а не "K", защото се припокриват с царя - 3 points
+# "B/b" - Bishop (офицер) - 3 points
+# "Q/q" - Queen (дама) - 9 points
+# "K/k" - King (цар) - 4 points (not always necessary)
+# "P/p" - Pawn (пешка) - 1 point
+import re
+
+# small - black
+# big - white
+
+
+"""
+CHESS_SIZE = 8
+figures_dict = {'r': 5,
+ 'n': 3,
+ 'b': 3,
+ 'k': 4,
+ 'q': 9,
+ 'p': 1
+ }
+
+
+class ChessException(Exception):
+ def __init__(self, message='undefined error'):
+ self.message = message
+ super().__init__(self.message)
+
+
+class ChessPosition:
+ def __init__(self, FEN):
+ self.FEN = FEN
+ self.matrix = self.validate_FEN()
+
+ # TODO there is a problem it is not working with more unusual fen like 4P3 inputs
+ def validate_FEN(self):
+ extracted = self.FEN.split('/')
+ matrix = [['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
+ ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
+ ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
+ ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '']]
+ # "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR".
+ # rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR
+ empty_spaces = 0
+ for i in range(CHESS_SIZE):
+ for j in range(len(extracted[i])):
+ if empty_spaces != 0:
+ matrix[empty_spaces][j] = extracted[i][j]
+ empty_spaces = 0
+ continue
+ if '0' < extracted[i][j] < f'{CHESS_SIZE}':
+ empty_spaces = extracted[i][j]
+ matrix[i][j] = extracted[i][j]
+ # print(matrix[i])
+
+ # todo Done implement the case with kings close to each other
+ # exception for more than one king
+ for line in matrix:
+ if line.count('k') > 1 or line.count('K') > 1:
+ raise ChessException("kings")
+
+ # exeption for wrong king position
+ # left up corner
+ # TODO it is possible that it may work without the edge cases
+ if (matrix[0][0] == 'k' or matrix[0][0] == 'K') and (matrix[0][1] == 'k' or matrix[0][1] == 'K') \
+ or (matrix[0][0] == 'k' or matrix[0][0] == 'K') and (matrix[1][1] == 'k' or matrix[1][1] == 'K') \
+ or (matrix[0][0] == 'k' or matrix[0][0] == 'K') and (matrix[1][0] == 'k' or matrix[1][0] == 'K'):
+ raise ChessException("kings")
+
+ # left right
+ elif (matrix[0][CHESS_SIZE - 1] == 'k' or matrix[0][CHESS_SIZE - 1] == 'K') and (
+ matrix[0][CHESS_SIZE - 2] == 'k' or matrix[0][CHESS_SIZE - 2] == 'K') \
+ or (matrix[0][CHESS_SIZE - 1] == 'k' or matrix[0][CHESS_SIZE - 1] == 'K') and (
+ matrix[1][CHESS_SIZE - 1] == 'k' or matrix[1][CHESS_SIZE - 1] == 'K') \
+ or (matrix[0][CHESS_SIZE - 1] == 'k' or matrix[0][CHESS_SIZE - 1] == 'K') and (
+ matrix[1][CHESS_SIZE - 2] == 'k' or matrix[1][CHESS_SIZE - 2] == 'K'):
+ raise ChessException("kings")
+
+ # down left
+ elif (matrix[CHESS_SIZE - 1][0] == 'k' or matrix[CHESS_SIZE - 1][0] == 'K') and (
+ matrix[CHESS_SIZE - 2][0] == 'k' or matrix[CHESS_SIZE - 2][0] == 'K') \
+ or (matrix[CHESS_SIZE - 1][0] == 'k' or matrix[CHESS_SIZE - 1][0] == 'K') and (
+ matrix[CHESS_SIZE - 2][1] == 'k' or matrix[CHESS_SIZE - 2][1] == 'K') \
+ or (matrix[CHESS_SIZE - 1][0] == 'k' or matrix[CHESS_SIZE - 1][0] == 'K') and (
+ matrix[CHESS_SIZE - 1][1] == 'k' or matrix[CHESS_SIZE - 1][1] == 'K'):
+ raise ChessException("kings")
+
+ # down right
+ elif (matrix[CHESS_SIZE - 1][CHESS_SIZE - 1] == 'k' or matrix[CHESS_SIZE - 1][CHESS_SIZE - 1] == 'K') and (
+ matrix[CHESS_SIZE - 2][CHESS_SIZE - 1] == 'k' or matrix[CHESS_SIZE - 2][CHESS_SIZE - 1] == 'K') \
+ or (
+ matrix[CHESS_SIZE - 1][CHESS_SIZE - 1] == 'k' or matrix[CHESS_SIZE - 1][CHESS_SIZE - 1] == 'K') and (
+ matrix[CHESS_SIZE - 2][CHESS_SIZE - 2] == 'k' or matrix[CHESS_SIZE - 2][CHESS_SIZE - 2] == 'K') \
+ or (
+ matrix[CHESS_SIZE - 1][CHESS_SIZE - 1] == 'k' or matrix[CHESS_SIZE - 1][CHESS_SIZE - 1] == 'K') and (
+ matrix[CHESS_SIZE - 1][CHESS_SIZE - 2] == 'k' or matrix[CHESS_SIZE - 1][CHESS_SIZE - 2] == 'K'):
+ raise ChessException("kings")
+
+ for i in range(CHESS_SIZE):
+ for j in range(CHESS_SIZE):
+ # the four sides without the diagonals
+ if i > 0 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i - 1][j] == 'k' or matrix[i - 1][j] == 'K'):
+ raise ChessException("kings")
+ elif i < CHESS_SIZE - 1 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i + 1][j] == 'k' or matrix[i + 1][j] == 'K'):
+ raise ChessException("kings")
+ elif j > 0 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i][j - 1] == 'k' or matrix[i][j - 1] == 'K'):
+ raise ChessException("kings")
+ elif j < CHESS_SIZE - 1 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i][j + 1] == 'k' or matrix[i][j + 1] == 'K'):
+ raise ChessException("kings")
+
+ if i > 0 and j > 0 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i - 1][j - 1] == 'k' or matrix[i - 1][j - 1] == 'K'):
+ raise ChessException("kings")
+ elif i > 0 and j < CHESS_SIZE - 1 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i - 1][j + 1] == 'k' or matrix[i - 1][j + 1] == 'K'):
+ raise ChessException("kings")
+ elif i < CHESS_SIZE - 1 and j > 0 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i + 1][j - 1] == 'k' or matrix[i + 1][j - 1] == 'K'):
+ raise ChessException("kings")
+ elif i < CHESS_SIZE - 1 and j < CHESS_SIZE - 1 and (matrix[i][j] == 'k' or matrix[i][j] == 'K') and (
+ matrix[i + 1][j + 1] == 'k' or matrix[i + 1][j + 1] == 'K'):
+ raise ChessException("kings")
+
+ # exception for wrong pawns position
+ if 'p' in matrix[0] or 'p' in matrix[7] or 'P' in matrix[0] or 'P' in matrix[7]:
+ raise ChessException("pawns")
+
+ return matrix
+
+ def __repr__(self):
+ return self.FEN
+
+ def __len__(self):
+ count_figures = 0
+ for figure in figures_dict:
+ count_figures += self.FEN.count(figure)
+
+ return count_figures
+
+ # TODO
+ def __getitem__(self, cord):
+ letter_dict = {
+ "A": 1,
+ "B": 2,
+ "C": 3,
+ "D": 4,
+ "E": 5,
+ "F": 6
+ }
+
+ # format 'E2'
+ second_cord = int(cord[1]) - 1
+ first_coord = letter_dict[cord[0]] - 1
+
+ if self.matrix[second_cord][first_coord].isalpha():
+ return self.matrix[second_cord][first_coord]
+ else:
+ return None
+
+ def get_white_score(self):
+ upper_list = []
+ for i in range(CHESS_SIZE):
+ for j in range(CHESS_SIZE):
+ if self.matrix[i][j].isupper():
+ upper_list.append(self.matrix[i][j])
+
+ # print(upper_list)
+
+ white_score = ChessScore(upper_list)
+ # print(white_score)
+
+ return white_score
+
+ def get_black_score(self):
+ lower_list = []
+ for i in range(CHESS_SIZE):
+ for j in range(CHESS_SIZE):
+ if self.matrix[i][j].islower():
+ lower_list.append(self.matrix[i][j])
+
+ # print(lower_list)
+ black_score = ChessScore(lower_list)
+ # print(black_score.score)
+ return black_score
+
+ 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()
+
+
+# calculate numbers of points to the whole
+class ChessScore:
+ def __init__(self, figures_list):
+ self.figures_list = figures_list
+ self.score = self.calculate_points()
+
+ def calculate_points(self):
+ total_points = 0
+ for cur_figure in self.figures_list:
+ for dict_figure in figures_dict:
+ if cur_figure.lower() == dict_figure:
+ total_points += figures_dict[dict_figure]
+
+ # print(cur_figure, figures_dict[figure]) # todo debug code
+ return int(total_points)
+
+ def __repr__(self):
+ return str(self.score)
+
+ def __int__(self):
+ return self.score
+
+ 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 __ge__(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
Качена първа версия
Можеш да минеш и само с един
pass
в тялото на класа, защото този инициализатор реално не прави нищо.Главните букви оказват константи, т.е. не е прието да имаш аргументи, които да са с главни букви, било то и абревиатури.
Това можеш да го генерираш с малко лист компрехеншън и умможение на листове.
За тези валидации те съветвам да огледаш другите решения. Има къси методи за справяне с проблема.
Избягвай пренасяне на редове с наклонена черта на всяка цена. Можеш да използваш цикли, променливи, функции, но не и това.