Advertisement
max2201111

amazonka,bob a cyril, Petr posledni verze

Jun 27th, 2024
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.59 KB | Science | 0 0
  1. import chess
  2. import time
  3. from itertools import permutations, combinations
  4. from functools import lru_cache
  5.  
  6. class CustomPiece(chess.Piece):
  7.     def __init__(self, piece_type, color):
  8.         super().__init__(piece_type, color)
  9.  
  10. class Amazon(CustomPiece):
  11.     def __init__(self, color):
  12.         super().__init__(chess.QUEEN, color)
  13.  
  14.     def symbol(self):
  15.         return 'A' if self.color == chess.WHITE else 'a'
  16.  
  17. class Bob(CustomPiece):
  18.     def __init__(self, color):
  19.         super().__init__(chess.ROOK, color)
  20.  
  21.     def symbol(self):
  22.         return 'B' if self.color == chess.WHITE else 'b'
  23.  
  24. class Cyryl(CustomPiece):
  25.     def __init__(self, color):
  26.         super().__init__(chess.QUEEN, color)
  27.  
  28.     def symbol(self):
  29.         return 'C' if self.color == chess.WHITE else 'c'
  30.  
  31. class CustomBoard(chess.Board):
  32.     def __init__(self, fen=None):
  33.         self.custom_pieces = {
  34.             'A': Amazon(chess.WHITE), 'a': Amazon(chess.BLACK),
  35.             'B': Bob(chess.WHITE), 'b': Bob(chess.BLACK),
  36.             'C': Cyryl(chess.WHITE), 'c': Cyryl(chess.BLACK)
  37.         }
  38.         super().__init__(fen)
  39.  
  40.     def set_fen(self, fen):
  41.         parts = fen.split(' ')
  42.         while len(parts) < 6:
  43.             parts.append("0")
  44.         board_part = parts[0]
  45.         turn_part = parts[1]
  46.         castling_part = parts[2]
  47.         en_passant_part = parts[3]
  48.         halfmove_clock = parts[4]
  49.         fullmove_number = parts[5]
  50.  
  51.         self.set_board_fen(board_part)
  52.         self.turn = chess.WHITE if turn_part == 'w' else chess.BLACK
  53.         self.castling_rights = chess.BB_EMPTY if castling_part == '-' else chess.SquareSet.from_square(chess.parse_square(castling_part))
  54.         self.ep_square = None if en_passant_part == '-' else chess.parse_square(en_passant_part)
  55.         self.halfmove_clock = int(halfmove_clock)
  56.         self.fullmove_number = int(fullmove_number)
  57.  
  58.     def set_board_fen(self, fen):
  59.         self.clear()
  60.         rows = fen.split('/')
  61.         for rank, row in enumerate(rows):
  62.             file = 0
  63.             for char in row:
  64.                 if char.isdigit():
  65.                     file += int(char)
  66.                 else:
  67.                     square = chess.square(file, 7 - rank)
  68.                     if char in self.custom_pieces:
  69.                         self.set_piece_at(square, self.custom_pieces[char])
  70.                     else:
  71.                         self.set_piece_at(square, chess.Piece.from_symbol(char))
  72.                     file += 1
  73.  
  74.     def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
  75.         for move in super().generate_legal_moves(from_mask, to_mask):
  76.             yield move
  77.        
  78.         for square in self.piece_map():
  79.             piece = self.piece_at(square)
  80.             if piece.symbol().lower() in ['a', 'b', 'c']:
  81.                 yield from self.generate_custom_piece_moves(square, piece)
  82.  
  83.     def generate_custom_piece_moves(self, square, piece):
  84.         knight_moves = [
  85.             (2, 1), (2, -1), (-2, 1), (-2, -1),
  86.             (1, 2), (1, -2), (-1, 2), (-1, -2)
  87.         ]
  88.        
  89.         directions = []
  90.         if piece.symbol().lower() == 'a':  # Amazon: Bishop + Knight moves
  91.             directions = [
  92.                 chess.BB_DIAG_A1H8, chess.BB_DIAG_A8H1
  93.             ]
  94.         elif piece.symbol().lower() == 'b':  # Bob: Rook + Knight moves
  95.             directions = [
  96.                 chess.BB_RANK_1, chess.BB_FILE_A
  97.             ]
  98.         elif piece.symbol().lower() == 'c':  # Cyryl: Queen + Knight moves
  99.             directions = [
  100.                 chess.BB_DIAG_A1H8, chess.BB_DIAG_A8H1, chess.BB_RANK_1, chess.BB_FILE_A
  101.             ]
  102.        
  103.         for direction in directions:
  104.             for dest_square in chess.SquareSet(direction):
  105.                 move = chess.Move(square, dest_square)
  106.                 if self.is_pseudo_legal(move):
  107.                     yield move
  108.        
  109.         # Handle knight moves
  110.         for dx, dy in knight_moves:
  111.             dest_square = chess.square(chess.square_file(square) + dx, chess.square_rank(square) + dy)
  112.             if 0 <= chess.square_file(dest_square) < 8 and 0 <= chess.square_rank(dest_square) < 8:
  113.                 move = chess.Move(square, dest_square)
  114.                 if self.is_pseudo_legal(move):
  115.                     yield move
  116.  
  117. @lru_cache(maxsize=None)
  118. def simplify_fen_string(fen):
  119.     parts = fen.split(' ')
  120.     simplified_fen = ' '.join(parts[:4])  # Zachováváme pouze informace o pozici
  121.     if len(parts) < 6:
  122.         simplified_fen += " 0 1"
  123.     return simplified_fen
  124.  
  125. def print_board(fen):
  126.     board = CustomBoard(fen)
  127.     print(board)
  128.  
  129. # Startovní pozice
  130. start_fen = "8/6A1/8/8/8/k1K5/8/8 w - - 0 1"
  131. simplified_POZ2 = simplify_fen_string(start_fen)
  132. POZ = {1: simplified_POZ2}
  133.  
  134. AR = {simplify_fen_string(start_fen): {'used': 0, 'to_end': 0}}
  135. N = 1
  136. M = 0
  137.  
  138. start_time = time.time()
  139.  
  140. def format_elapsed_time(elapsed_time):
  141.     hours, remainder = divmod(elapsed_time, 3600)
  142.     minutes, seconds = divmod(remainder, 60)
  143.     return f"{int(hours)}h {int(minutes)}m {int(seconds)}s"
  144.  
  145. def print_elapsed_time(total_time, level_time):
  146.     print(f"{format_elapsed_time(total_time)} / {format_elapsed_time(level_time)}")
  147.  
  148. while M < N:
  149.     M += 1
  150.     current_fen = POZ[M]
  151.     board = CustomBoard(current_fen)
  152.     simplified_current_fen = simplify_fen_string(current_fen)
  153.  
  154.     if simplified_current_fen not in AR:
  155.         AR[simplified_current_fen] = {'used': 0, 'to_end': 0}
  156.  
  157.     if AR[simplified_current_fen]['used'] == 0:
  158.         AR[simplified_current_fen]['used'] = 1
  159.         for move in board.legal_moves:
  160.             # Check if the move is a promotion
  161.             if board.is_pseudo_legal(move) and move.promotion:
  162.                 move.promotion = chess.QUEEN  # Set promotion to queen only
  163.  
  164.             board.push(move)
  165.             POZ2 = board.fen()
  166.             simplified_POZ2 = simplify_fen_string(POZ2)
  167.  
  168.             if simplified_POZ2 not in AR:
  169.                 AR[simplified_POZ2] = {'used': None, 'to_end': 0}
  170.  
  171.             if AR[simplified_POZ2]['used'] is None:
  172.                 N += 1
  173.                 POZ[N] = simplified_POZ2
  174.                 AR[simplified_POZ2] = {'used': 0, 'to_end': 0}
  175.  
  176.             board.pop()  # Vrátíme tah zpět
  177.  
  178. print(f"Počet pozic je {N}")
  179.  
  180. # Přidání kontroly pro mat, remízu a výchozí hodnotu
  181. F = 0
  182. for i in range(1, N + 1):
  183.     current_fen = POZ[i]
  184.     board = CustomBoard(current_fen)
  185.     simplified_current_fen = simplify_fen_string(current_fen)
  186.  
  187.     if simplified_current_fen not in AR:
  188.         AR[simplified_current_fen] = {'used': 0, 'to_end': 0}
  189.  
  190.     if board.is_checkmate():
  191.         AR[simplified_current_fen]['to_end'] = -1000
  192.         F += 1
  193.     elif board.is_stalemate() or board.is_insufficient_material() or board.is_seventyfive_moves() or board.is_fivefold_repetition():
  194.         AR[simplified_current_fen]['to_end'] = 0
  195.     else:
  196.         AR[simplified_current_fen]['to_end'] = 0
  197.  
  198. print(f"Počet pozic v matu je {F}")
  199.  
  200. uroven = 0
  201. while F > 0:
  202.     uroven += 1
  203.     level_start_time = time.time()
  204.     print(f"Výpočet v úrovni {uroven}")
  205.    
  206.     F = 0
  207.     current_level_positions = 0
  208.     for i in range(1, N + 1):
  209.         current_fen = POZ[i]
  210.         board = CustomBoard(current_fen)
  211.         simplified_current_fen = simplify_fen_string(current_fen)
  212.         if AR[simplified_current_fen]['to_end'] == 0:
  213.             hod = -2000
  214.             for move in board.legal_moves:
  215.                 # Check if the move is a promotion
  216.                 if board.is_pseudo_legal(move) and move.promotion:
  217.                     move.promotion = chess.QUEEN  # Set promotion to queen only
  218.  
  219.                 board.push(move)
  220.                 POZ2 = board.fen()
  221.                 simplified_POZ2 = simplify_fen_string(POZ2)
  222.                 if simplified_POZ2 not in AR or AR[simplified_POZ2]['to_end'] is None:
  223.                     hod2 = 0
  224.                 else:
  225.                     hod2 = -AR[simplified_POZ2]['to_end']
  226.                 if hod2 > hod:
  227.                     hod = hod2
  228.                 board.pop()  # Vrátíme tah zpět
  229.             if hod == 1001 - uroven:
  230.                 AR[simplified_current_fen]['to_end'] = 1000 - uroven
  231.                 F += 1
  232.                 current_level_positions += 1
  233.             if hod == -1001 + uroven:
  234.                 AR[simplified_current_fen]['to_end'] = -1000 + uroven
  235.                 F += 1
  236.                 current_level_positions += 1
  237.     level_end_time = time.time()
  238.     total_elapsed_time = level_end_time - start_time
  239.     level_elapsed_time = level_end_time - level_start_time
  240.     print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  241.     print_elapsed_time(total_elapsed_time, level_elapsed_time)
  242.  
  243. print(f"Nalezeno {F} pozic celkem")
  244.  
  245. # Výpis všech pozic s to_end == 17
  246. print("Pozice s to_end == 17:")
  247. for fen, data in AR.items():
  248.     if data['to_end'] is not None and data['to_end'] < 983 and data['to_end'] > 0:
  249.         print(f"{fen} -> to_end: {data['to_end']}")
  250.  
  251. print("*****")
  252.  
  253. print("Pozice s to_end == -20:")
  254. for fen, data in AR.items():
  255.     if data['to_end'] is not None and data['to_end'] > -981 and data['to_end'] < 0:
  256.         print(f"{fen} -> to_end: {data['to_end']}")
  257.  
  258. current_fen = POZ[1]
  259. board = CustomBoard(current_fen)
  260. simplified_current_fen = simplify_fen_string(current_fen)
  261. hod = AR[simplified_current_fen]['to_end']
  262. print(f"Hodnocení počáteční pozice je {hod}")
  263.  
  264. # Závěrečný kód pro procházení nejlepších tahů
  265. current_fen = start_fen
  266. simplified_current_fen = simplify_fen_string(current_fen)
  267.  
  268. optimal_moves = []
  269. while AR[simplified_current_fen]['to_end'] is not None and AR[simplified_current_fen]['to_end'] > -1000:
  270.     board = CustomBoard(current_fen)
  271.     simplified_current_fen = simplify_fen_string(current_fen)
  272.     hod = -2000
  273.     for move in board.legal_moves:
  274.         # Check if the move is a promotion
  275.         if board.is_pseudo_legal(move) and move.promotion:
  276.             move.promotion = chess.QUEEN  # Set promotion to queen only
  277.  
  278.         board.push(move)
  279.         POZ2 = board.fen()
  280.         simplified_POZ2 = simplify_fen_string(POZ2)
  281.         if simplified_POZ2 not in AR or AR[simplified_POZ2]['to_end'] is None:
  282.             hod2 = 0
  283.         else:
  284.             hod2 = -AR[simplified_POZ2]['to_end']
  285.         if hod2 > hod:
  286.             hod = hod2
  287.             best_fen = simplified_POZ2
  288.         board.pop()  # Vrátíme tah zpět
  289.  
  290.     optimal_moves.append(best_fen)
  291.     current_fen = best_fen
  292.     simplified_current_fen = simplify_fen_string(current_fen)
  293.  
  294. # Tisk šachovnic v opačném pořadí
  295. for fen in reversed(optimal_moves):
  296.     print_board(fen)
  297.     print("\n")
  298.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement