Решение на Шахматни фенове от Дейвид Каменов

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

Към профила на Дейвид Каменов

Резултати

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

Код

"""
Created by David Kamenov 62585
Homework 4
Version 1.4 Some minor fixes
Task description:
# 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()
def validate_FEN(self):
extracted = self.FEN.split('/')
matrix = [['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '']]
for i in range(CHESS_SIZE):
ind = 0
for j in range(len(extracted[i])):
skip_times = 0
if extracted[i][j].isalpha():
matrix[i][ind] = extracted[i][j]
ind += 1
elif extracted[i][j].isdigit():
skip_times = int(extracted[i][j]) # it has t skip 4 times
# print(skip_times)
for k in range(skip_times):
matrix[i][ind] = ''
ind += 1
# exception for more than one king
k_kings = 0
K_kings = 0
for line in matrix:
for el in line:
if el == 'k':
k_kings += 1
if el == 'K':
K_kings += 1
if k_kings > 1 or K_kings > 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")
# the diagonals
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
def __getitem__(self, cord):
letter_dict = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6
}
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])
white_score = ChessScore(upper_list)
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])
black_score = ChessScore(lower_list)
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]
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

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

.....F.EF........
======================================================================
ERROR: test_king_count (test.TestChessPosition)
Test for missing or multiple kings.
----------------------------------------------------------------------
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
Exception: No exception raised on: 8/8/8/8/8/8/8/8

======================================================================
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'

======================================================================
FAIL: 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
AssertionError: 3 != 7

----------------------------------------------------------------------
Ran 17 tests in 0.177s

FAILED (failures=2, errors=1)

История (3 версии и 6 коментара)

Дейвид обнови решението на 29.11.2022 16:32 (преди над 1 година)

+""""
+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

Дейвид обнови решението на 29.11.2022 17:43 (преди над 1 година)

""""
Created by David Kamenov 62585
Homework 4
-
-Task:
+Version 1.2 fixed a bug
+
+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):
+ ind = 0
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])
+ skip_times = 0
+ if extracted[i][j].isalpha():
+ matrix[i][ind] = extracted[i][j]
+ ind += 1
+ elif extracted[i][j].isdigit():
+ skip_times = int(extracted[i][j]) # it has t skip 4 times
+ # print(skip_times)
+ for k in range(skip_times):
+ matrix[i][ind] = ''
+ ind += 1
- # 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

Дейвид обнови решението на 29.11.2022 17:59 (преди над 1 година)

-""""
+"""
Created by David Kamenov 62585
Homework 4
-Version 1.2 fixed a bug
+Version 1.4 Some minor fixes
-Task
+Task description:
# 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 = [['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '']]
for i in range(CHESS_SIZE):
ind = 0
for j in range(len(extracted[i])):
skip_times = 0
if extracted[i][j].isalpha():
matrix[i][ind] = extracted[i][j]
ind += 1
elif extracted[i][j].isdigit():
skip_times = int(extracted[i][j]) # it has t skip 4 times
# print(skip_times)
for k in range(skip_times):
matrix[i][ind] = ''
ind += 1
# exception for more than one king
+ k_kings = 0
+ K_kings = 0
for line in matrix:
- if line.count('k') > 1 or line.count('K') > 1:
- raise ChessException("kings")
+ for el in line:
+ if el == 'k':
+ k_kings += 1
+ if el == 'K':
+ K_kings += 1
+ if k_kings > 1 or K_kings > 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")
+ # the diagonals
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
def __getitem__(self, cord):
letter_dict = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6
}
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])
white_score = ChessScore(upper_list)
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])
black_score = ChessScore(lower_list)
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]
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