Advertisement
max2201111

posledniii v OK

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