Advertisement
max2201111

posledni s 12 a OK legal_moves LAST

Jul 14th, 2024
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.51 KB | Science | 0 0
  1. # Import knihovny chess a dalších potřebných modulů
  2. import chess
  3. from typing import Iterator, Optional, Dict, Tuple
  4. from chess import Move, BB_ALL, Bitboard, PieceType, Color
  5. import time
  6. from collections import deque
  7. import threading
  8.  
  9. # Definice nových figur
  10. AMAZON = 7
  11. CYRIL = 8
  12. EVE = 9
  13.  
  14. # Rozšíření seznamu PIECE_SYMBOLS
  15. chess.PIECE_SYMBOLS.append('a')
  16. chess.PIECE_SYMBOLS.append('c')
  17. chess.PIECE_SYMBOLS.append('e')
  18.  
  19. class CustomBoard(chess.Board):
  20.     def __init__(self, fen=None):
  21.         self.amazons_white = chess.BB_EMPTY
  22.         self.amazons_black = chess.BB_EMPTY
  23.         self.cyrils_white = chess.BB_EMPTY
  24.         self.cyrils_black = chess.BB_EMPTY
  25.         self.eves_white = chess.BB_EMPTY
  26.         self.eves_black = chess.BB_EMPTY
  27.         super().__init__(None)
  28.         if fen:
  29.             self.set_custom_fen(fen)
  30.     #    print("Šachovnice inicializována")
  31.         self.debug_amazons()
  32.         self.debug_cyrils()
  33.         self.debug_eves()
  34.  
  35.     def clear_square(self, square):
  36.         super()._remove_piece_at(square)
  37.         self.amazons_white &= ~chess.BB_SQUARES[square]
  38.         self.amazons_black &= ~chess.BB_SQUARES[square]
  39.         self.cyrils_white &= ~chess.BB_SQUARES[square]
  40.         self.cyrils_black &= ~chess.BB_SQUARES[square]
  41.         self.eves_white &= ~chess.BB_SQUARES[square]
  42.         self.eves_black &= ~chess.BB_SQUARES[square]
  43.  
  44.     def set_custom_fen(self, fen):
  45.         parts = fen.split()
  46.         board_part = parts[0]
  47.  
  48.         self.clear()
  49.         self.amazons_white = chess.BB_EMPTY
  50.         self.amazons_black = chess.BB_EMPTY
  51.         self.cyrils_white = chess.BB_EMPTY
  52.         self.cyrils_black = chess.BB_EMPTY
  53.         self.eves_white = chess.BB_EMPTY
  54.         self.eves_black = chess.BB_EMPTY
  55.  
  56.         square = 56
  57.         for c in board_part:
  58.             if c == '/':
  59.                 square -= 16
  60.             elif c.isdigit():
  61.                 square += int(c)
  62.             else:
  63.                 color = chess.WHITE if c.isupper() else chess.BLACK
  64.                 if c.upper() == 'A':
  65.                     if color == chess.WHITE:
  66.                         self.amazons_white |= chess.BB_SQUARES[square]
  67.                     else:
  68.                         self.amazons_black |= chess.BB_SQUARES[square]
  69.                     piece_type = AMAZON
  70.                 elif c.upper() == 'C':
  71.                     if color == chess.WHITE:
  72.                         self.cyrils_white |= chess.BB_SQUARES[square]
  73.                     else:
  74.                         self.cyrils_black |= chess.BB_SQUARES[square]
  75.                     piece_type = CYRIL
  76.                 elif c.upper() == 'E':
  77.                     if color == chess.WHITE:
  78.                         self.eves_white |= chess.BB_SQUARES[square]
  79.                     else:
  80.                         self.eves_black |= chess.BB_SQUARES[square]
  81.                     piece_type = EVE
  82.                 else:
  83.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  84.                 self._set_piece_at(square, piece_type, color)
  85.                 square += 1
  86.  
  87.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  88.         self.castling_rights = chess.BB_EMPTY
  89.         if '-' not in parts[2]:
  90.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  91.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  92.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  93.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  94.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  95.  
  96.     def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
  97.         self.clear_square(square)
  98.         super()._set_piece_at(square, piece_type, color)
  99.         if piece_type == AMAZON:
  100.             if color == chess.WHITE:
  101.                 self.amazons_white |= chess.BB_SQUARES[square]
  102.             else:
  103.                 self.amazons_black |= chess.BB_SQUARES[square]
  104.         elif piece_type == CYRIL:
  105.             if color == chess.WHITE:
  106.                 self.cyrils_white |= chess.BB_SQUARES[square]
  107.             else:
  108.                 self.cyrils_black |= chess.BB_SQUARES[square]
  109.         elif piece_type == EVE:
  110.             if color == chess.WHITE:
  111.                 self.eves_white |= chess.BB_SQUARES[square]
  112.             else:
  113.                 self.eves_black |= chess.BB_SQUARES[square]
  114.  
  115.     def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
  116.         if self.amazons_white & chess.BB_SQUARES[square]:
  117.             return chess.Piece(AMAZON, chess.WHITE)
  118.         elif self.amazons_black & chess.BB_SQUARES[square]:
  119.             return chess.Piece(AMAZON, chess.BLACK)
  120.         elif self.cyrils_white & chess.BB_SQUARES[square]:
  121.             return chess.Piece(CYRIL, chess.WHITE)
  122.         elif self.cyrils_black & chess.BB_SQUARES[square]:
  123.             return chess.Piece(CYRIL, chess.BLACK)
  124.         elif self.eves_white & chess.BB_SQUARES[square]:
  125.             return chess.Piece(EVE, chess.WHITE)
  126.         elif self.eves_black & chess.BB_SQUARES[square]:
  127.             return chess.Piece(EVE, chess.BLACK)
  128.         return super().piece_at(square)
  129.  
  130.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  131.         our_pieces = self.occupied_co[self.turn]
  132.         if self.turn == chess.WHITE:
  133.             our_amazons = self.amazons_white
  134.             our_cyrils = self.cyrils_white
  135.             our_eves = self.eves_white
  136.         else:
  137.             our_amazons = self.amazons_black
  138.             our_cyrils = self.cyrils_black
  139.             our_eves = self.eves_black
  140.    
  141.         # Generování tahů pro amazonky
  142.         for from_square in chess.scan_forward(our_amazons & from_mask):
  143.             attacks = self.amazon_attacks(from_square)
  144.             valid_moves = attacks & ~our_pieces & to_mask
  145.             for to_square in chess.scan_forward(valid_moves):
  146.                 yield Move(from_square, to_square)
  147.    
  148.         # Generování tahů pro Cyrily
  149.         for from_square in chess.scan_forward(our_cyrils & from_mask):
  150.             attacks = self.cyril_attacks(from_square)
  151.             valid_moves = attacks & ~our_pieces & to_mask
  152.             for to_square in chess.scan_forward(valid_moves):
  153.                 yield Move(from_square, to_square)
  154.    
  155.         # Generování tahů pro Evy
  156.         for from_square in chess.scan_forward(our_eves & from_mask):
  157.             attacks = self.eve_attacks(from_square)
  158.             valid_moves = attacks & ~our_pieces & to_mask
  159.             for to_square in chess.scan_forward(valid_moves):
  160.                 yield Move(from_square, to_square)
  161.    
  162.         # Generování tahů pro standardní figury
  163.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  164.             piece = self.piece_at(move.from_square)
  165.             if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
  166.                 yield move
  167.  
  168.     def queen_attacks(self, square):
  169.         return self.bishop_attacks(square) | self.rook_attacks(square)
  170.  
  171.     def bishop_attacks(self, square):
  172.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  173.  
  174.     def rook_attacks(self, square):
  175.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  176.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  177.  
  178.     def amazon_attacks(self, square):
  179.         return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  180.  
  181.     def cyril_attacks(self, square):
  182.         return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS(square)
  183.  
  184.     def eve_attacks(self, square):
  185.         return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS(square)
  186.  
  187.     def is_pseudo_legal(self, move):
  188.         from_square = move.from_square
  189.         to_square = move.to_square
  190.         piece = self.piece_at(from_square)
  191.    
  192.         if not piece or piece.color != self.turn:
  193.             return False
  194.    
  195.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  196.             return False
  197.    
  198.         if self.is_castling(move):
  199.             return True
  200.    
  201.         if piece.piece_type == AMAZON:
  202.             return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
  203.         elif piece.piece_type == CYRIL:
  204.             return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
  205.         elif piece.piece_type == EVE:
  206.             return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
  207.         else:
  208.             return super().is_pseudo_legal(move)
  209.  
  210.     def is_legal(self, move):
  211.         if not self.is_pseudo_legal(move):
  212.             return False
  213.  
  214.         from_square = move.from_square
  215.         to_square = move.to_square
  216.         piece = self.piece_at(from_square)
  217.         captured_piece = self.piece_at(to_square)
  218.  
  219.         self.clear_square(from_square)
  220.         self.clear_square(to_square)
  221.         self._set_piece_at(to_square, piece.piece_type, piece.color)
  222.  
  223.         king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
  224.         is_check = self._is_attacked_by(not self.turn, king_square)
  225.  
  226.         self.clear_square(to_square)
  227.         self._set_piece_at(from_square, piece.piece_type, piece.color)
  228.         if captured_piece:
  229.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  230.  
  231.         if is_check:
  232.             attackers = self.attackers(not self.turn, king_square)
  233.     #        print(f"[DEBUG] King at {chess.SQUARE_NAMES[king_square]} is attacked by pieces at: {[chess.SQUARE_NAMES[sq] for sq in chess.scan_forward(attackers)]}")
  234.  
  235.         return not is_check
  236.  
  237.     def _is_attacked_by(self, color, square):
  238.         attackers = self.attackers(color, square)
  239.         return bool(attackers)
  240.  
  241.     def attackers(self, color, square):
  242.         attackers = chess.BB_EMPTY
  243.  
  244.         knights = self.knights & self.occupied_co[color]
  245.         attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  246.  
  247.         king = self.kings & self.occupied_co[color]
  248.         attackers |= king & chess.BB_KING_ATTACKS[square]
  249.  
  250.         pawns = self.pawns & self.occupied_co[color]
  251.         if color == chess.WHITE:
  252.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.BLACK][square]
  253.         else:
  254.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.WHITE][square]
  255.  
  256.         queens = self.queens & self.occupied_co[color]
  257.         bishops = (self.bishops | queens) & self.occupied_co[color]
  258.         rooks = (self.rooks | queens) & self.occupied_co[color]
  259.  
  260.         attackers |= chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] & bishops
  261.         attackers |= (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  262.                       chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]) & rooks
  263.  
  264.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  265.         for amazon_square in chess.scan_forward(amazons):
  266.             if self.amazon_attacks(amazon_square) & chess.BB_SQUARES[square]:
  267.                 attackers |= chess.BB_SQUARES[amazon_square]
  268.  
  269.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  270.         for cyril_square in chess.scan_forward(cyrils):
  271.             if self.cyril_attacks(cyril_square) & chess.BB_SQUARES[square]:
  272.                 attackers |= chess.BB_SQUARES[cyril_square]
  273.  
  274.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  275.         for eve_square in chess.scan_forward(eves):
  276.             if self.eve_attacks(eve_square) & chess.BB_SQUARES[square]:
  277.                 attackers |= chess.BB_SQUARES[eve_square]
  278.  
  279.         return attackers
  280.  
  281.     def push(self, move):
  282.         if not self.is_legal(move):
  283.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  284.  
  285.         piece = self.piece_at(move.from_square)
  286.         captured_piece = self.piece_at(move.to_square)
  287.  
  288.         self.clear_square(move.from_square)
  289.         self.clear_square(move.to_square)
  290.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  291.  
  292.         self.turn = not self.turn
  293.  
  294.         self.move_stack.append((move, captured_piece))
  295.  
  296.     def pop(self):
  297.         if not self.move_stack:
  298.             return None
  299.  
  300.         move, captured_piece = self.move_stack.pop()
  301.  
  302.         piece = self.piece_at(move.to_square)
  303.        
  304.         self.clear_square(move.from_square)
  305.         self.clear_square(move.to_square)
  306.  
  307.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  308.  
  309.         if captured_piece:
  310.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  311.  
  312.         self.turn = not self.turn
  313.  
  314.         return move
  315.  
  316.     def is_check(self):
  317.         king_square = self.king(self.turn)
  318.         if king_square is None:
  319.             return False
  320.         is_check = self._is_attacked_by(not self.turn, king_square)
  321.   #      print(f"[DEBUG] Checking if position is check: FEN: {self.fen()}, King at {chess.SQUARE_NAMES[king_square]}, is_check: {is_check}")
  322.         return is_check
  323.  
  324.     def is_checkmate(self):
  325.         if not self.is_check():
  326.   #          print(f"[DEBUG] Position is not check, hence not checkmate: FEN: {self.fen()}")
  327.             return False
  328.         legal_moves = list(self.generate_legal_moves())
  329.  #       print(f"[DEBUG] Checking if position is checkmate: FEN: {self.fen()}, Legal moves: {legal_moves}")
  330.         return len(legal_moves) == 0
  331.  
  332.     def is_game_over(self):
  333.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  334.  
  335.     def is_stalemate(self):
  336.         if self.is_check():
  337.             return False
  338.         legal_moves = list(self.generate_legal_moves())
  339.   #      print(f"[DEBUG] Checking if position is stalemate: FEN: {self.fen()}, Legal moves: {legal_moves}")
  340.         return len(legal_moves) == 0
  341.    
  342.     def is_insufficient_material(self):
  343.         return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  344.                 self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  345.             chess.popcount(self.occupied) <= 3
  346.         )
  347.  
  348.     def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
  349.         for move in self.generate_pseudo_legal_moves(from_mask, to_mask):
  350.             if self.is_legal(move):
  351.       #          print(f"[DEBUG] Legal move: {move}")
  352.                 yield move
  353.        #     else:
  354.         #        print(f"[DEBUG] Illegal move: {move}")
  355.  
  356.     def debug_amazons(self):
  357.         pass
  358.       #  print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  359.     #   print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  360.         for square in chess.SQUARES:
  361.             pass
  362.        #     if self.amazons_white & chess.BB_SQUARES[square]:
  363.        #         print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  364.      #       if self.amazons_black & chess.BB_SQUARES[square]:
  365.        #         print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  366.  
  367.     def debug_cyrils(self):
  368.         pass
  369.        # print(f"Bitboard bílých Cyrils: {format(self.cyrils_white, '064b')}")
  370.        # print(f"Bitboard černých Cyrils: {format(self.cyrils_black, '064b')}")
  371.        # for square in chess.SQUARES:
  372.        #     if self.cyrils_white & chess.BB_SQUARES[square]:
  373.       #          print(f"Bílý Cyril na {chess.SQUARE_NAMES[square]}")
  374.      #       if self.cyrils_black & chess.BB_SQUARES[square]:
  375.     #            print(f"Černý Cyril na {chess.SQUARE_NAMES[square]}")
  376.  
  377.     def debug_eves(self):
  378.         pass
  379.     #    print(f"Bitboard bílých Eves: {format(self.eves_white, '064b')}")
  380.      #   print(f"Bitboard černých Eves: {format(self.eves_black, '064b')}")
  381.       #  for square in chess.SQUARES:
  382.       #      if self.eves_white & chess.BB_SQUARES[square]:
  383.           #      print(f"Bílá Eve na {chess.SQUARE_NAMES[square]}")
  384.        #     if self.eves_black & chess.BB_SQUARES[square]:
  385.        #         print(f"Černá Eve na {chess.SQUARE_NAMES[square]}")
  386.  
  387.     def piece_symbol(self, piece):
  388.         if piece is None:
  389.             return '.'
  390.         if piece.piece_type == AMAZON:
  391.             return 'A' if piece.color == chess.WHITE else 'a'
  392.         if piece.piece_type == CYRIL:
  393.             return 'C' if piece.color == chess.WHITE else 'c'
  394.         if piece.piece_type == EVE:
  395.             return 'E' if piece.color == chess.WHITE else 'e'
  396.         return piece.symbol()
  397.  
  398.     def piece_type_at(self, square):
  399.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  400.             return AMAZON
  401.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  402.             return CYRIL
  403.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  404.             return EVE
  405.         return super().piece_type_at(square)
  406.  
  407.     def color_at(self, square):
  408.         if self.amazons_white & chess.BB_SQUARES[square]:
  409.             return chess.WHITE
  410.         if self.amazons_black & chess.BB_SQUARES[square]:
  411.             return chess.BLACK
  412.         if self.cyrils_white & chess.BB_SQUARES[square]:
  413.             return chess.WHITE
  414.         if self.cyrils_black & chess.BB_SQUARES[square]:
  415.             return chess.BLACK
  416.         if self.eves_white & chess.BB_SQUARES[square]:
  417.             return chess.WHITE
  418.         if self.eves_black & chess.BB_SQUARES[square]:
  419.             return chess.BLACK
  420.         return super().color_at(square)
  421.  
  422.     @property
  423.     def legal_moves(self):
  424.         return list(self.generate_legal_moves())
  425.  
  426.     def __str__(self):
  427.         builder = []
  428.         for square in chess.SQUARES_180:
  429.             piece = self.piece_at(square)
  430.             symbol = self.piece_symbol(piece) if piece else '.'
  431.             builder.append(symbol)
  432.             if chess.square_file(square) == 7:
  433.                 if square != chess.H1:
  434.                     builder.append('\n')
  435.         return ''.join(builder)
  436.  
  437.     def print_all_possible_moves(self):
  438.         pass
  439.     #    print(f"[DEBUG] All possible moves for FEN: {self.fen()}")
  440.   #      for move in self.generate_pseudo_legal_moves():
  441.    #         print(f"Move: {move}, Is legal: {self.is_legal(move)}")
  442.  
  443. def simplify_fen_string(fen):
  444.     parts = fen.split(' ')
  445.     return ' '.join(parts[:4])  # Zachováváme pouze informace o pozici, barvě na tahu, rošádách a en passant
  446.  
  447. def format_time(seconds):
  448.     hours, remainder = divmod(seconds, 3600)
  449.     minutes, seconds = divmod(remainder, 60)
  450.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  451.  
  452. def print_elapsed_time(stop_event):
  453.     start_time = time.time()
  454.     while not stop_event.is_set():
  455.         elapsed_time = time.time() - start_time
  456.         formatted_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
  457.         print(f"Uplynulý čas: {formatted_time}", end='\r')
  458.         time.sleep(1)
  459.  
  460. def calculate_optimal_moves(start_fen: str) -> Dict[str, int]:
  461.     board = CustomBoard(start_fen)
  462.     AR = {simplify_fen_string(start_fen): 0}
  463.     queue = deque([(simplify_fen_string(start_fen), 0)])
  464.     visited = set()
  465.  
  466.     start_time = time.time()
  467.     current_level = 0
  468.     pozice_na_urovni = 0
  469.     level_start_time = start_time
  470.  
  471.     stop_event = threading.Event()
  472.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event,))
  473.     timer_thread.start()
  474.  
  475.     try:
  476.         # Fáze 1: Generování všech pozic
  477.         while queue:
  478.             fen, hloubka = queue.popleft()
  479.  
  480.             if hloubka > current_level:
  481.                 level_time = time.time() - level_start_time
  482.                 print(f"\nHloubka {current_level + 1}: {pozice_na_urovni} pozic, Čas: {format_time(level_time)}")
  483.                 current_level = hloubka
  484.                 pozice_na_urovni = 0
  485.                 level_start_time = time.time()
  486.  
  487.             if fen in visited:
  488.                 continue
  489.  
  490.             visited.add(fen)
  491.             pozice_na_urovni += 1
  492.             board.set_custom_fen(fen)
  493.  
  494.             if board.is_checkmate():
  495.                 AR[fen] = -1000 if board.turn == chess.WHITE else 1000
  496.             elif board.is_stalemate() or board.is_insufficient_material():
  497.                 AR[fen] = 0
  498.             else:
  499.                 legal_moves = list(board.legal_moves)
  500.                 # if not legal_moves:
  501.                 #     print(f"Warning: No legal moves for position ({pozice_na_urovni}):")
  502.                 #     print(f"FEN: {fen}")
  503.                 #     print(f"Is game over: {board.is_game_over()}")
  504.                 #     print(f"Is checkmate: {board.is_checkmate()}")
  505.                 #     print(f"Is stalemate: {board.is_stalemate()}")
  506.                 #     print(f"Is insufficient material: {board.is_insufficient_material()}")
  507.                 #     print(f"King square: {board.king(board.turn)}")
  508.                 #     print(f"Pieces: {board.piece_map()}")
  509.                 #     board.print_all_possible_moves()
  510.                 for move in legal_moves:
  511.                     board.push(move)
  512.                     new_fen = simplify_fen_string(board.fen())
  513.                     if new_fen not in AR:
  514.                         AR[new_fen] = 0
  515.                         queue.append((new_fen, hloubka + 1))
  516.                     board.pop()
  517.  
  518.         print(f"\nCelkový počet pozic: {len(AR)}")
  519.  
  520.         # Fáze 2: Aktualizace hodnot
  521.         print("\nZačíná aktualizace hodnot...")
  522.         POZ = {1: simplify_fen_string(start_fen)}
  523.         AR = {simplify_fen_string(start_fen): {'used': 0, 'to_end': None}}
  524.         N = 1
  525.         M = 0
  526.  
  527.         while M < N:
  528.             M += 1
  529.             current_fen = POZ[M]
  530.             board = CustomBoard(current_fen)
  531.             simplified_current_fen = simplify_fen_string(current_fen)
  532.  
  533.             if AR[simplified_current_fen]['used'] == 0:
  534.                 AR[simplified_current_fen]['used'] = 1
  535.                 for move in board.legal_moves:
  536.                     if board.is_pseudo_legal(move) and move.promotion:
  537.                         move.promotion = chess.QUEEN
  538.  
  539.                     board.push(move)
  540.                     POZ2 = board.fen()
  541.                     simplified_POZ2 = simplify_fen_string(POZ2)
  542.  
  543.                     if simplified_POZ2 not in AR:
  544.                         AR[simplified_POZ2] = {'used': None, 'to_end': None}
  545.  
  546.                     if AR[simplified_POZ2]['used'] is None:
  547.                         N += 1
  548.                         POZ[N] = simplified_POZ2
  549.                         AR[simplified_POZ2] = {'used': 0, 'to_end': None}
  550.  
  551.                     board.pop()
  552.  
  553.         print(f"Počet pozic je {N}")
  554.  
  555.         F = 0
  556.         for i in range(1, N + 1):
  557.             current_fen = POZ[i]
  558.             board = CustomBoard(current_fen)
  559.             simplified_current_fen = simplify_fen_string(current_fen)
  560.  
  561.             if board.is_checkmate():
  562.                 AR[simplified_current_fen]['to_end'] = -1000
  563.                 F += 1
  564.             elif board.is_stalemate() or board.is_insufficient_material() or board.is_seventyfive_moves() or board.is_fivefold_repetition():
  565.                 AR[simplified_current_fen]['to_end'] = 0
  566.             else:
  567.                 AR[simplified_current_fen]['to_end'] = 0
  568.  
  569.         print(f"Počet pozic v matu je {F}")
  570.  
  571.         uroven = 0
  572.         while F > 0:
  573.             uroven += 1
  574.             level_start_time = time.time()
  575.             print(f"Výpočet v úrovni {uroven}")
  576.  
  577.             F = 0
  578.             current_level_positions = 0
  579.             for i in range(1, N + 1):
  580.                 current_fen = POZ[i]
  581.                 board = CustomBoard(current_fen)
  582.                 simplified_current_fen = simplify_fen_string(current_fen)
  583.                 if AR[simplified_current_fen]['to_end'] == 0:
  584.                     hod = -2000
  585.                     for move in board.legal_moves:
  586.                         if board.is_pseudo_legal(move) and move.promotion:
  587.                             move.promotion = chess.QUEEN
  588.  
  589.                         board.push(move)
  590.                         POZ2 = board.fen()
  591.                         simplified_POZ2 = simplify_fen_string(POZ2)
  592.                         hod2 = -AR[simplified_POZ2]['to_end']
  593.                         if hod2 > hod:
  594.                             hod = hod2
  595.                         board.pop()
  596.                     if hod == 1001 - uroven:
  597.                         AR[simplified_current_fen]['to_end'] = 1000 - uroven
  598.                         F += 1
  599.                         current_level_positions += 1
  600.                     if hod == -1001 + uroven:
  601.                         AR[simplified_current_fen]['to_end'] = -1000 + uroven
  602.                         F += 1
  603.                         current_level_positions += 1
  604.             level_end_time = time.time()
  605.             total_elapsed_time = level_end_time - start_time
  606.             level_elapsed_time = level_end_time - level_start_time
  607.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  608.             print_elapsed_time(total_elapsed_time, level_elapsed_time)
  609.  
  610.         print(f"Nalezeno {F} pozic celkem")
  611.  
  612.     finally:
  613.         stop_event.set()
  614.         timer_thread.join()
  615.  
  616.     total_time = time.time() - start_time
  617.     print(f"\nCelkový čas výpočtu: {format_time(total_time)}")
  618.  
  619.     return AR
  620.  
  621. if __name__ == "__main__":
  622.     start_fen = "8/3k4/8/8/8/8/A7/6K1 w - - 0 1"
  623.     AR = calculate_optimal_moves(start_fen)
  624.     F = 0
  625.  
  626.     # Výpis výsledků
  627.     for fen, hodnota in AR.items():
  628.         F = F + 1
  629.         if F < 50 or hodnota != 0:
  630.             print(f"FEN: {fen}")
  631.             print(f"Hodnota: {hodnota}")
  632.             print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement