Решение на Шахматни фенове от Иван Лаков

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

Към профила на Иван Лаков

Резултати

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

Код

import re
class ChessException(Exception):
pass
class ChessPosition:
def __init__(self, FEN):
self._rows = FEN.split("/")
self._rows.reverse()
self._decoded_rows = self._rows
i = -1
for row in self._rows:
i += 1
for char in row:
if char.isnumeric():
new_char = int(char) * "0"
self._decoded_rows[i] = self._decoded_rows[i].replace(char, new_char)
to_check = []
i = -1
for row in self._decoded_rows:
i += 1
j = -1
for char in row:
j += 1
if char == "K" or char == "k":
converted_index = f"{chr(j + 65)}{i+1}" # actual king pos
to_check.append(f"{chr(j + 65)}{i+2}")
to_check.append(f"{chr(j + 65)}{i}")
to_check.append(f"{chr(j + 66)}{i+1}") # right
to_check.append(f"{chr(j + 66)}{i+2}")
to_check.append(f"{chr(j + 66)}{i}")
to_check.append(f"{chr(j + 64)}{i+1}") # left
to_check.append(f"{chr(j + 64)}{i+2}")
to_check.append(f"{chr(j + 64)}{i}")
figure = ""
for index in to_check:
try:
figure = self[index]
except IndexError:
continue
if figure == "K" or figure == "k":
pass
#raise ChessException("kings")
# In the end I couldn't do it. Better luck next time. :)
if FEN == "" or FEN is None:
raise Exception("FEN string is empty")
if FEN.count('K') != 1 or FEN.count('k') != 1:
raise ChessException("kings")
pawn_check = re.compile(r'[Pp]')
if pawn_check.search(self._rows[0]) or pawn_check.search(self._rows[7]):
raise ChessException("pawns")
self._FEN = FEN
def __str__(self):
return f"{self._FEN}"
def __len__(self):
length_regex = re.compile(r'[RrNnBbQqKkPp]')
return len(re.findall(length_regex, self._FEN))
def __getitem__(self, key):
letter = ord(key[0]) - 65
number = ord(key[1]) - 49
result = self._decoded_rows[number][letter]
if result == "0":
result = None
return result
def get_white_score(self):
regex = re.compile(r'[RNBQKP]')
whites = re.findall(regex, self._FEN)
cs = ChessScore(whites)
return cs
def get_black_score(self):
regex = re.compile(r'[rnbqkp]')
blacks = re.findall(regex, self._FEN)
cs = ChessScore(blacks)
return cs
def white_is_winning(self):
white_score = self.get_white_score()
black_score = self.get_black_score()
return white_score > black_score
def black_is_winning(self):
white_score = self.get_white_score()
black_score = self.get_black_score()
return white_score < black_score
def is_equal(self):
white_score = self.get_white_score()
black_score = self.get_black_score()
return white_score == black_score
class ChessScore:
def __init__(self, letters):
self._list = [char.lower() for char in letters]
result = 0
for figure in self._list:
score = 0
match figure:
case 'r': score = 5
case 'n': score = 3
case 'b': score = 3
case 'k': score = 4
case 'q': score = 9
case 'p': score = 1
case '_': raise TypeError("Unexpected figure encountered.")
result += score
self._result = result
def __int__(self):
return self._result
def __add__(self, other):
return self._result + other._result
def __sub__(self, other):
return self._result - other._result
def __lt__(self, other):
return self._result < other._result
def __gt__(self, other):
return self._result > other._result
def __le__(self, other):
return self._result <= other._result
def __ge__(self, other):
return self._result >= other._result
def __eq__(self, other):
return self._result == other._result
def __ne__(self, other):
return self._result != other._result
cp = ChessPosition("rnbqkbnr/pppppppp/8/8/8/8/PPPPRPPP/RNBQKBNR")
print(cp)
#print(cp._decoded_rows)
#print(len(cp))
#print(cp["H2"])
#print(cp.get_white_score())
#print(cp.get_black_score())
#print(cp.white_is_winning())
#print(cp.black_is_winning())
#print(cp.is_equal())
#score1 = ChessScore(['r', 'n', 'b', 'k', 'q', 'p'])
#score2 = ChessScore(['r', 'b'])
#print(int(score1))
#print(int(score2))
#print(score1 + score2)
#print(score1 - score2)

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

rnbqkbnr/pppppppp/8/8/8/8/PPPPRPPP/RNBQKBNR
.E.........F.....
======================================================================
ERROR: test_against_touching_kings (test.TestChessPosition)
Test for kings next to each other.
----------------------------------------------------------------------
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: k7/K7/8/8/8/8/8/8

======================================================================
FAIL: test_validation_conflict (test.TestChessPosition)
Test for correct Exception on multiple validation fails.
----------------------------------------------------------------------
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: 'pawns' != 'kings'
- pawns
+ kings


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

FAILED (failures=1, errors=1)

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

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

+# A note from the "developer": 2 parts of the code are not finished. I will finish them tomorrow
+# Uploading this intermediate version just so that I can receive comments on the other parts of the code.
+# Thanks :)
+
+import re
+
+class ChessException(Exception):
+ pass
+
+class ChessPosition:
+ def __init__(self, FEN):
+ self._rows = FEN.split("/")
+ self._rows.reverse()
+
+ # Checking for kings doesn't yet work as I was too tired to implement it. Will upload a new version tomorrow.
+
+ if FEN == "" or FEN is None:
+ raise Exception("FEN string is empty")
+
+ if FEN.count('K') != 1 or FEN.count('k') != 1:
+ raise ChessException("kings")
+
+ pawn_check = re.compile(r'[Pp]')
+ if pawn_check.search(self._rows[0]) or pawn_check.search(self._rows[7]):
+ raise ChessException("pawns")
+
+ self._FEN = FEN
+
+ def __str__(self):
+ return f"{self._FEN}"
+
+ def __len__(self):
+ length_regex = re.compile(r'[RrNnBbQqKkPp]')
+ return len(re.findall(length_regex, self._FEN))
+
+ def __getitem__(self, key):
+ # Doesn't properly work yet. Will upload a new version tomorrow.
+ letter = ord(key[0]) - 65
+ number = ord(key[1]) - 49
+ result = self._rows[number][letter]
+ return result
+
+ def get_white_score(self):
+ regex = re.compile(r'[RNBQKP]')
+ whites = re.findall(regex, self._FEN)
+ cs = ChessScore(whites)
+ return int(cs)
+
+ def get_black_score(self):
+ regex = re.compile(r'[rnbqkp]')
+ blacks = re.findall(regex, self._FEN)
+ cs = ChessScore(blacks)
+ return int(cs)
+
+ def white_is_winning(self):
+ white_score = self.get_white_score()
+ black_score = self.get_black_score()
+ if (white_score > black_score):
+ return True
+ return False
+
+ def black_is_winning(self):
+ white_score = self.get_white_score()
+ black_score = self.get_black_score()
+ if (white_score < black_score):
+ return True
+ return False
+
+ def is_equal(self):
+ white_score = self.get_white_score()
+ black_score = self.get_black_score()
+ if (white_score == black_score):
+ return True
+ return False
+
+class ChessScore:
+ def __init__(self, letters):
+
+ self._list = [char.lower() for char in letters]
+
+ result = 0
+ for figure in self._list:
+ score = 0
+ match figure:
+ case 'r': score = 5
+ case 'n': score = 3
+ case 'b': score = 3
+ case 'k': score = 4
+ case 'q': score = 9
+ case 'p': score = 1
+ case '_': raise TypeError("Unexpected figure encountered.")
+ result += score
+ self._result = result
+
+ def __int__(self):
+ return self._result
+
+ def __add__(self, other):
+ return self._result + other._result
+
+ def __sub__(self, other):
+ return self._result - other._result
+
+ def __lt__(self, other):
+ return self._result < other._result
+
+ def __gt__(self, other):
+ return self._result > other._result
+
+ def __le__(self, other):
+ return self._result <= other._result
+
+ def __ge__(self, other):
+ return self._result >= other._result
+
+ def __eq__(self, other):
+ return self._result == other._result
+
+ def __ne__(self, other):
+ return self._result != other._result
+
+cp = ChessPosition("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR")
+print(cp)
+#print(len(cp))
+#print(cp["E2"])
+print(cp.get_white_score())
+print(cp.get_black_score())
+print(cp.white_is_winning())
+print(cp.black_is_winning())
+print(cp.is_equal())
+
+score1 = ChessScore(['r', 'n', 'b', 'k', 'q', 'p'])
+score2 = ChessScore(['r', 'b'])
+#print(int(score1))
+#print(int(score2))
+#print(score1 + score2)
+#print(score1 - score2)

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

-# A note from the "developer": 2 parts of the code are not finished. I will finish them tomorrow
-# Uploading this intermediate version just so that I can receive comments on the other parts of the code.
-# Thanks :)
-
import re
class ChessException(Exception):
pass
class ChessPosition:
def __init__(self, FEN):
self._rows = FEN.split("/")
self._rows.reverse()
- # Checking for kings doesn't yet work as I was too tired to implement it. Will upload a new version tomorrow.
+ self._decoded_rows = self._rows
+ i = -1
+ for row in self._rows:
+ i += 1
+ for char in row:
+ if char.isnumeric():
+ new_char = int(char) * "0"
+ self._decoded_rows[i] = self._decoded_rows[i].replace(char, new_char)
+ to_check = []
+ i = -1
+ for row in self._decoded_rows:
+ i += 1
+ j = -1
+ for char in row:
+ j += 1
+ if char == "K" or char == "k":
+ converted_index = f"{chr(j + 65)}{i+1}" # actual king pos
+ to_check.append(f"{chr(j + 65)}{i+2}")
+ to_check.append(f"{chr(j + 65)}{i}")
+ to_check.append(f"{chr(j + 66)}{i+1}") # right
+ to_check.append(f"{chr(j + 66)}{i+2}")
+ to_check.append(f"{chr(j + 66)}{i}")
+ to_check.append(f"{chr(j + 64)}{i+1}") # left
+ to_check.append(f"{chr(j + 64)}{i+2}")
+ to_check.append(f"{chr(j + 64)}{i}")
+
+ figure = ""
+ for index in to_check:
+ try:
+ figure = self[index]
+ except IndexError:
+ continue
+
+ if figure == "K" or figure == "k":
+ pass
+ #raise ChessException("kings")
+ # In the end I couldn't do it. Better luck next time. :)
+
+
if FEN == "" or FEN is None:
raise Exception("FEN string is empty")
if FEN.count('K') != 1 or FEN.count('k') != 1:
raise ChessException("kings")
pawn_check = re.compile(r'[Pp]')
if pawn_check.search(self._rows[0]) or pawn_check.search(self._rows[7]):
raise ChessException("pawns")
self._FEN = FEN
def __str__(self):
return f"{self._FEN}"
def __len__(self):
length_regex = re.compile(r'[RrNnBbQqKkPp]')
return len(re.findall(length_regex, self._FEN))
def __getitem__(self, key):
- # Doesn't properly work yet. Will upload a new version tomorrow.
letter = ord(key[0]) - 65
number = ord(key[1]) - 49
- result = self._rows[number][letter]
+ result = self._decoded_rows[number][letter]
+ if result == "0":
+ result = None
return result
def get_white_score(self):
regex = re.compile(r'[RNBQKP]')
whites = re.findall(regex, self._FEN)
cs = ChessScore(whites)
- return int(cs)
+ return cs
def get_black_score(self):
regex = re.compile(r'[rnbqkp]')
blacks = re.findall(regex, self._FEN)
cs = ChessScore(blacks)
- return int(cs)
+ return cs
def white_is_winning(self):
white_score = self.get_white_score()
black_score = self.get_black_score()
- if (white_score > black_score):
- return True
- return False
+ return white_score > black_score
def black_is_winning(self):
white_score = self.get_white_score()
black_score = self.get_black_score()
- if (white_score < black_score):
- return True
- return False
+ return white_score < black_score
def is_equal(self):
white_score = self.get_white_score()
black_score = self.get_black_score()
- if (white_score == black_score):
- return True
- return False
+ return white_score == black_score
class ChessScore:
def __init__(self, letters):
self._list = [char.lower() for char in letters]
result = 0
for figure in self._list:
score = 0
match figure:
case 'r': score = 5
case 'n': score = 3
case 'b': score = 3
case 'k': score = 4
case 'q': score = 9
case 'p': score = 1
case '_': raise TypeError("Unexpected figure encountered.")
result += score
self._result = result
def __int__(self):
return self._result
def __add__(self, other):
return self._result + other._result
def __sub__(self, other):
return self._result - other._result
def __lt__(self, other):
return self._result < other._result
def __gt__(self, other):
return self._result > other._result
def __le__(self, other):
return self._result <= other._result
def __ge__(self, other):
return self._result >= other._result
def __eq__(self, other):
return self._result == other._result
def __ne__(self, other):
return self._result != other._result
-cp = ChessPosition("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR")
+cp = ChessPosition("rnbqkbnr/pppppppp/8/8/8/8/PPPPRPPP/RNBQKBNR")
print(cp)
+#print(cp._decoded_rows)
#print(len(cp))
-#print(cp["E2"])
-print(cp.get_white_score())
-print(cp.get_black_score())
-print(cp.white_is_winning())
-print(cp.black_is_winning())
-print(cp.is_equal())
+#print(cp["H2"])
+#print(cp.get_white_score())
+#print(cp.get_black_score())
+#print(cp.white_is_winning())
+#print(cp.black_is_winning())
+#print(cp.is_equal())
-score1 = ChessScore(['r', 'n', 'b', 'k', 'q', 'p'])
-score2 = ChessScore(['r', 'b'])
+#score1 = ChessScore(['r', 'n', 'b', 'k', 'q', 'p'])
+#score2 = ChessScore(['r', 'b'])
#print(int(score1))
#print(int(score2))
#print(score1 + score2)
#print(score1 - score2)