Advertisement
max2201111

posledni s 12 a OK legal_moves

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