Advertisement
max2201111

posledni cerny bily pesec OK 12

Jul 24th, 2024
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 30.74 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
  245.         knights = self.knights & self.occupied_co[color]
  246.         if chess.BB_KNIGHT_ATTACKS[square] & knights:
  247.             attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  248.        
  249.         # King
  250.         king = self.kings & self.occupied_co[color]
  251.         if chess.BB_KING_ATTACKS[square] & king:
  252.             attackers |= king
  253.        
  254.         # Pawns
  255.         pawns = self.pawns & self.occupied_co[color]
  256.         pawn_attacks = chess.BB_PAWN_ATTACKS[not color][square]
  257.         if pawn_attacks & pawns:
  258.             attackers |= pawns & pawn_attacks
  259.        
  260.         # Queens
  261.         queens = self.queens & self.occupied_co[color]
  262.         queen_attacks = (
  263.             chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] |
  264.             chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  265.             chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
  266.         )
  267.         if queen_attacks & queens:
  268.             attackers |= queens & queen_attacks
  269.        
  270.         # Bishops
  271.         bishops = self.bishops & self.occupied_co[color]
  272.         bishop_attacks = chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  273.         if bishop_attacks & bishops:
  274.             attackers |= bishops & bishop_attacks
  275.        
  276.         # Rooks
  277.         rooks = self.rooks & self.occupied_co[color]
  278.         rook_attacks = (
  279.             chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  280.             chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
  281.         )
  282.         if rook_attacks & rooks:
  283.             attackers |= rooks & rook_attacks
  284.        
  285.         # Amazons (Queen + Knight)
  286.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  287.         for amazon_square in chess.scan_forward(amazons):
  288.             amazon_attacks = (
  289.                 chess.BB_DIAG_ATTACKS[amazon_square][self.occupied & chess.BB_DIAG_MASKS[amazon_square]] |
  290.                 chess.BB_RANK_ATTACKS[amazon_square][self.occupied & chess.BB_RANK_MASKS[amazon_square]] |
  291.                 chess.BB_FILE_ATTACKS[amazon_square][self.occupied & chess.BB_FILE_MASKS[amazon_square]] |
  292.                 chess.BB_KNIGHT_ATTACKS[amazon_square]
  293.             )
  294.             if amazon_attacks & chess.BB_SQUARES[square]:
  295.                 attackers |= chess.BB_SQUARES[amazon_square]
  296.        
  297.         # Cyrils (Rook + Knight)
  298.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  299.         for cyril_square in chess.scan_forward(cyrils):
  300.             cyril_attacks = (
  301.                 chess.BB_RANK_ATTACKS[cyril_square][self.occupied & chess.BB_RANK_MASKS[cyril_square]] |
  302.                 chess.BB_FILE_ATTACKS[cyril_square][self.occupied & chess.BB_FILE_MASKS[cyril_square]] |
  303.                 chess.BB_KNIGHT_ATTACKS[cyril_square]
  304.             )
  305.             if cyril_attacks & chess.BB_SQUARES[square]:
  306.                 attackers |= chess.BB_SQUARES[cyril_square]
  307.        
  308.         # Eves (Bishop + Knight)
  309.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  310.         for eve_square in chess.scan_forward(eves):
  311.             eve_attacks = (
  312.                 chess.BB_DIAG_ATTACKS[eve_square][self.occupied & chess.BB_DIAG_MASKS[eve_square]] |
  313.                 chess.BB_KNIGHT_ATTACKS[eve_square]
  314.             )
  315.             if eve_attacks & chess.BB_SQUARES[square]:
  316.                 attackers |= chess.BB_SQUARES[eve_square]
  317.        
  318.         return attackers
  319.        
  320.  
  321.     def push(self, move):
  322.         if not self.is_legal(move):
  323.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  324.  
  325.         piece = self.piece_at(move.from_square)
  326.         captured_piece = self.piece_at(move.to_square)
  327.  
  328.         self.clear_square(move.from_square)
  329.         self.clear_square(move.to_square)
  330.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  331.  
  332.         self.turn = not self.turn
  333.  
  334.         self.move_stack.append((move, captured_piece))
  335.  
  336.     def pop(self):
  337.         if not self.move_stack:
  338.             return None
  339.  
  340.         move, captured_piece = self.move_stack.pop()
  341.  
  342.         piece = self.piece_at(move.to_square)
  343.        
  344.         self.clear_square(move.from_square)
  345.         self.clear_square(move.to_square)
  346.  
  347.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  348.  
  349.         if captured_piece:
  350.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  351.  
  352.         self.turn = not self.turn
  353.  
  354.         return move
  355.  
  356.     def is_check(self):
  357.         king_square = self.king(self.turn)
  358.         if king_square is None:
  359.             return False
  360.         is_check = self._is_attacked_by(not self.turn, king_square)
  361.   #      print(f"[DEBUG] Checking if position is check: FEN: {self.fen()}, King at {chess.SQUARE_NAMES[king_square]}, is_check: {is_check}")
  362.         return is_check
  363.  
  364.     def is_checkmate(self):
  365.         if not self.is_check():
  366.   #          print(f"[DEBUG] Position is not check, hence not checkmate: FEN: {self.fen()}")
  367.             return False
  368.         legal_moves = list(self.generate_legal_moves())
  369.  #       print(f"[DEBUG] Checking if position is checkmate: FEN: {self.fen()}, Legal moves: {legal_moves}")
  370.         return len(legal_moves) == 0
  371.  
  372.     def is_game_over(self):
  373.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  374.  
  375.     def is_stalemate(self):
  376.         if self.is_check():
  377.             return False
  378.         legal_moves = list(self.generate_legal_moves())
  379.   #      print(f"[DEBUG] Checking if position is stalemate: FEN: {self.fen()}, Legal moves: {legal_moves}")
  380.         return len(legal_moves) == 0
  381.    
  382.     def is_insufficient_material(self):
  383.         return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  384.                 self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  385.             chess.popcount(self.occupied) <= 3
  386.         )
  387.  
  388.     def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
  389.         for move in self.generate_pseudo_legal_moves(from_mask, to_mask):
  390.             if self.is_legal(move):
  391.       #          print(f"[DEBUG] Legal move: {move}")
  392.                 yield move
  393.        #     else:
  394.         #        print(f"[DEBUG] Illegal move: {move}")
  395.  
  396.     def debug_amazons(self):
  397.         pass
  398.       #  print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  399.     #   print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  400.         for square in chess.SQUARES:
  401.             pass
  402.        #     if self.amazons_white & chess.BB_SQUARES[square]:
  403.        #         print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  404.      #       if self.amazons_black & chess.BB_SQUARES[square]:
  405.        #         print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  406.  
  407.     def debug_cyrils(self):
  408.         pass
  409.        # print(f"Bitboard bílých Cyrils: {format(self.cyrils_white, '064b')}")
  410.        # print(f"Bitboard černých Cyrils: {format(self.cyrils_black, '064b')}")
  411.        # for square in chess.SQUARES:
  412.        #     if self.cyrils_white & chess.BB_SQUARES[square]:
  413.       #          print(f"Bílý Cyril na {chess.SQUARE_NAMES[square]}")
  414.      #       if self.cyrils_black & chess.BB_SQUARES[square]:
  415.     #            print(f"Černý Cyril na {chess.SQUARE_NAMES[square]}")
  416.  
  417.     def debug_eves(self):
  418.         pass
  419.     #    print(f"Bitboard bílých Eves: {format(self.eves_white, '064b')}")
  420.      #   print(f"Bitboard černých Eves: {format(self.eves_black, '064b')}")
  421.       #  for square in chess.SQUARES:
  422.       #      if self.eves_white & chess.BB_SQUARES[square]:
  423.           #      print(f"Bílá Eve na {chess.SQUARE_NAMES[square]}")
  424.        #     if self.eves_black & chess.BB_SQUARES[square]:
  425.        #         print(f"Černá Eve na {chess.SQUARE_NAMES[square]}")
  426.  
  427.     def piece_symbol(self, piece):
  428.         if piece is None:
  429.             return '.'
  430.         if piece.piece_type == AMAZON:
  431.             return 'A' if piece.color == chess.WHITE else 'a'
  432.         if piece.piece_type == CYRIL:
  433.             return 'C' if piece.color == chess.WHITE else 'c'
  434.         if piece.piece_type == EVE:
  435.             return 'E' if piece.color == chess.WHITE else 'e'
  436.         return piece.symbol()
  437.  
  438.     def piece_type_at(self, square):
  439.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  440.             return AMAZON
  441.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  442.             return CYRIL
  443.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  444.             return EVE
  445.         return super().piece_type_at(square)
  446.  
  447.     def color_at(self, square):
  448.         if self.amazons_white & chess.BB_SQUARES[square]:
  449.             return chess.WHITE
  450.         if self.amazons_black & chess.BB_SQUARES[square]:
  451.             return chess.BLACK
  452.         if self.cyrils_white & chess.BB_SQUARES[square]:
  453.             return chess.WHITE
  454.         if self.cyrils_black & chess.BB_SQUARES[square]:
  455.             return chess.BLACK
  456.         if self.eves_white & chess.BB_SQUARES[square]:
  457.             return chess.WHITE
  458.         if self.eves_black & chess.BB_SQUARES[square]:
  459.             return chess.BLACK
  460.         return super().color_at(square)
  461.  
  462.     @property
  463.     def legal_moves(self):
  464.         return list(self.generate_legal_moves())
  465.  
  466.     def __str__(self):
  467.         builder = []
  468.         for square in chess.SQUARES_180:
  469.             piece = self.piece_at(square)
  470.             symbol = self.piece_symbol(piece) if piece else '.'
  471.             builder.append(symbol)
  472.             if chess.square_file(square) == 7:
  473.                 if square != chess.H1:
  474.                     builder.append('\n')
  475.         return ''.join(builder)
  476.  
  477.     def print_all_possible_moves(self):
  478.         pass
  479.     #    print(f"[DEBUG] All possible moves for FEN: {self.fen()}")
  480.   #      for move in self.generate_pseudo_legal_moves():
  481.    #         print(f"Move: {move}, Is legal: {self.is_legal(move)}")
  482.  
  483.  
  484. def format_time(seconds):
  485.     hours, remainder = divmod(seconds, 3600)
  486.     minutes, seconds = divmod(remainder, 60)
  487.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  488.  
  489. def print_elapsed_time(stop_event, start_time):
  490.     while not stop_event.is_set():
  491.         elapsed_time = time.time() - start_time
  492.         print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
  493.         time.sleep(1)
  494.  
  495. def simplify_fen_string(fen):
  496.     return ' '.join(fen.split()[:4])
  497.  
  498.  
  499. def calculate_optimal_moves(start_fen: str) -> Dict[str, Tuple[int, str]]:
  500.     print("Funkce calculate_optimal_moves byla zavolána")
  501.     print(f"Počáteční FEN: {start_fen}")
  502.    
  503.     board = CustomBoard(start_fen)
  504.     POZ = {1: simplify_fen_string(start_fen)}
  505.     AR = {simplify_fen_string(start_fen): {'used': 0, 'to_end': None, 'depth': 0, 'type': 'normal'}}
  506.     N = 1
  507.     M = 0
  508.  
  509.     start_time = time.time()
  510.     current_depth = 0
  511.     positions_at_depth = {0: 0}
  512.     depth_start_time = start_time
  513.  
  514.     stop_event = threading.Event()
  515.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event, start_time))
  516.     timer_thread.start()
  517.  
  518.     try:
  519.         print("Začínám generovat pozice...")
  520.         print("Počáteční pozice:")
  521.         print_board(start_fen)
  522.        
  523.         depth_1_positions = []  # Seznam pro ukládání pozic v hloubce 1
  524.  
  525.         # Generate all positions
  526.         while M < N:
  527.             M += 1
  528.             current_fen = POZ[M]
  529.             board.set_custom_fen(current_fen)
  530.             simplified_current_fen = simplify_fen_string(current_fen)
  531.             current_depth = AR[simplified_current_fen]['depth']
  532.  
  533.             if current_depth not in positions_at_depth:
  534.                 positions_at_depth[current_depth] = 0
  535.                 if current_depth > 0:
  536.                     depth_time = time.time() - depth_start_time
  537.                     total_time = time.time() - start_time
  538.                     print(f"\nHloubka {current_depth - 1}: {positions_at_depth[current_depth - 1]} pozic, "
  539.                           f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  540.                    
  541.                     if current_depth == 1:
  542.                         print("Všechny pozice v hloubce 1:")
  543.                         for pos in depth_1_positions:
  544.                             print_board(pos)
  545.                             print()
  546.     #                else:
  547.    #                     print(f"Příklad pozice v hloubce {current_depth - 1}:")
  548.   #                      print_board(current_fen)
  549.                
  550.                 depth_start_time = time.time()
  551.  
  552.             positions_at_depth[current_depth] += 1
  553.  
  554.             if current_depth == 1:
  555.                 depth_1_positions.append(current_fen)
  556.  
  557.             if AR[simplified_current_fen]['used'] == 0:
  558.                 AR[simplified_current_fen]['used'] = 1
  559.                 legal_moves = list(board.legal_moves)
  560.                 for move in legal_moves:
  561.                     board.push(move)
  562.                     # Kontrola promoce
  563.                     if move.promotion == chess.QUEEN:
  564.                         # Aktualizujeme FEN, aby obsahoval dámu místo pěšce
  565.                         fen = board.fen()
  566.                         fen_parts = fen.split()
  567.                         board_rows = fen_parts[0].split('/')
  568.                        
  569.                         # Určení řádku a sloupce, kde došlo k proměně
  570.                         promotion_row = 0 if board.turn == chess.BLACK else 7
  571.                         promotion_col = chess.square_file(move.to_square)
  572.                        
  573.                         # Nahrazení pěšce dámou na správné pozici
  574.                         row = list(board_rows[promotion_row])
  575.                         piece_count = 0
  576.                         for i, char in enumerate(row):
  577.                             if char.isdigit():
  578.                                 piece_count += int(char)
  579.                             else:
  580.                                 piece_count += 1
  581.                             if piece_count > promotion_col:
  582.                                 row[i] = 'Q' if board.turn == chess.BLACK else 'q'
  583.                                 break
  584.                         board_rows[promotion_row] = ''.join(row)
  585.                        
  586.                         fen_parts[0] = '/'.join(board_rows)
  587.                         POZ2 = ' '.join(fen_parts)
  588.                     else:
  589.                         POZ2 = board.fen()
  590.                     simplified_POZ2 = simplify_fen_string(POZ2)
  591.                     if simplified_POZ2 not in AR:
  592.                         N += 1
  593.                         POZ[N] = simplified_POZ2
  594.                         AR[simplified_POZ2] = {'used': 0, 'to_end': None, 'depth': current_depth + 1, 'type': 'normal'}
  595.                     board.pop()
  596.    
  597.         # Print last depth
  598.         depth_time = time.time() - depth_start_time
  599.         total_time = time.time() - start_time
  600.         print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
  601.               f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  602.         print(f"Příklad pozice v hloubce {current_depth}:")
  603.         print_board(current_fen)
  604.  
  605.         print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
  606.  
  607.         # Initial evaluation
  608.         print("\nZačínám počáteční ohodnocení...")
  609.         F = 0
  610.         for i in range(1, N + 1):
  611.             current_fen = POZ[i]
  612.             board.set_custom_fen(current_fen)
  613.             simplified_current_fen = simplify_fen_string(current_fen)
  614.  
  615.             if board.is_checkmate():
  616.                 AR[simplified_current_fen]['to_end'] = -1000
  617.                 F += 1
  618.             elif board.is_stalemate() or board.is_insufficient_material():
  619.                 AR[simplified_current_fen]['to_end'] = 0
  620.             else:
  621.                 AR[simplified_current_fen]['to_end'] = 0
  622.  
  623.         print(f"Počet pozic v matu je {F}")
  624.  
  625.         # Iterative evaluation
  626.         print("\nZačínám iterativní ohodnocení...")
  627.         uroven = 0
  628.         while F > 0:
  629.             uroven += 1
  630.             level_start_time = time.time()
  631.             print(f"Výpočet v úrovni {uroven}")
  632.            
  633.             F = 0
  634.             current_level_positions = 0
  635.             for i in range(1, N + 1):
  636.                 current_fen = POZ[i]
  637.                 board.set_custom_fen(current_fen)
  638.                 simplified_current_fen = simplify_fen_string(current_fen)
  639.                 if AR[simplified_current_fen]['to_end'] == 0:
  640.                     hod = -2000
  641.                     for move in board.legal_moves:
  642.                         board.push(move)
  643.                         POZ2 = board.fen()
  644.                         simplified_POZ2 = simplify_fen_string(POZ2)
  645.                         hod2 = -AR[simplified_POZ2]['to_end']
  646.                         if hod2 > hod:
  647.                             hod = hod2
  648.                         board.pop()
  649.                     if hod == 1001 - uroven:
  650.                         AR[simplified_current_fen]['to_end'] = 1000 - uroven
  651.                         F += 1
  652.                         current_level_positions += 1
  653.                     if hod == -1001 + uroven:
  654.                         AR[simplified_current_fen]['to_end'] = -1000 + uroven
  655.                         F += 1
  656.                         current_level_positions += 1
  657.             level_end_time = time.time()
  658.             total_elapsed_time = level_end_time - start_time
  659.             level_elapsed_time = level_end_time - level_start_time
  660.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  661.             print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  662.  
  663.         print(f"Nalezeno {F} pozic celkem")
  664.        
  665.         print("\nVýpočet dokončen.")
  666.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  667.  
  668.     finally:
  669.         stop_event.set()
  670.         timer_thread.join()
  671.        
  672. # Helper function to print the board
  673. def print_board(fen):
  674.     board = CustomBoard(fen)
  675.     print(board)
  676.  
  677. # Najděte nejmenší kladnou hodnotu to_end ve všech FEN záznamech v AR
  678. def find_min_positive_value(AR):
  679.     min_positive_value = float('inf')
  680.     min_fen = None
  681.    
  682.     for fen, (value, type_pozice) in AR.items():
  683.         if value > 0 and value < min_positive_value:
  684.             min_positive_value = value
  685.             min_fen = fen
  686.    
  687.     if min_positive_value == float('inf'):
  688.         print("Žádná kladná hodnota nebyla nalezena.")
  689.     else:
  690.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  691.  
  692. # Main execution
  693. # if __name__ == "__main__":
  694. #     start_fen = "8/3k4/8/8/8/8/R7/6K1 w - - 0 1"
  695. #     start_fen = "3K4/8/8/6A1/8/8/8/3k4 w - - 0 1"
  696.  
  697. # #   start_fen = "8/8/8/4k3/8/8/2A5/5K2 w - - 0 1"
  698. # #    start_fen = "7K/2P5/8/8/8/1k6/8/8 w - - 0 1"
  699.  
  700. # #    start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  701.    
  702. # #    AR = calculate_optimal_moves(start_fen)
  703.  
  704. #     find_min_positive_value(AR)
  705.  
  706. #     H = 0
  707. #     current_fen = start_fen
  708. #     optimal_moves = []
  709. #     simplified_current_fen1 = simplify_fen_string(start_fen)
  710.  
  711.    
  712. if __name__ == "__main__":
  713.     start_fen = "3K4/8/8/6A1/8/8/8/3k4 w - - 0 1"
  714.     start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  715.    
  716.     AR = calculate_optimal_moves(start_fen)
  717.  
  718.     find_min_positive_value(AR)
  719.  
  720.     H = 0
  721.     current_fen = start_fen
  722.     optimal_moves = []
  723.     simplified_current_fen1 = simplify_fen_string(start_fen)
  724.  
  725.     while True:
  726.         if not H % 100000:
  727.             print(f"{H//100000}", end='')
  728.         H += 1
  729.        
  730.         board = CustomBoard(current_fen)
  731.         if board.is_game_over():
  732.             break
  733.        
  734.         hod = -2000
  735.         best_fen = None
  736.        
  737.         for move in board.legal_moves:
  738.             board.push(move)
  739.             POZ2 = board.fen()
  740.             simplified_POZ2 = simplify_fen_string(POZ2)
  741.             if simplified_POZ2 in AR:
  742.                 hod2 = -AR[simplified_POZ2][0]
  743.                 if hod2 > hod:
  744.                     hod = hod2
  745.                     best_fen = simplified_POZ2
  746.             board.pop()
  747.    
  748.         if best_fen is None:
  749.             break
  750.    
  751.         optimal_moves.append(best_fen)
  752.         current_fen = best_fen
  753.  
  754.     print(f"U {len(optimal_moves)} Z")
  755.     print("\nOptimální tahy:")
  756.     for i, fen in enumerate(optimal_moves):
  757.         print(f"Tah {i+1}:")
  758.         print_board(fen)
  759.         simplified_fen = simplify_fen_string(fen)
  760.         print(f"AR data: {AR[simplified_fen]}")
  761.         print(f"FEN: {fen}")
  762.         print("\n")
  763.  
  764.     print("Počáteční pozice:")
  765.     print_board(simplified_current_fen1)
  766.     print(f"AR data: {AR[simplified_current_fen1]}")
  767.     print(f"FEN: {simplified_current_fen1}")
  768.     print("\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement