Advertisement
max2201111

cele OKK

Jul 26th, 2024
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 31.07 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.                     board.pop()
  547.    
  548.         # Tisk poslední hloubky
  549.         depth_time = time.time() - depth_start_time
  550.         total_time = time.time() - start_time
  551.         print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
  552.               f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  553.         print(f"Příklad pozice v hloubce {current_depth}:")
  554.         print_board(current_fen)
  555.  
  556.         print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
  557.  
  558.         # Počáteční ohodnocení
  559.         print("\nZačínám počáteční ohodnocení...")
  560.         F = 0
  561.         for i in range(1, N + 1):
  562.             current_fen = POZ[i]
  563.             board.set_custom_fen(current_fen)
  564.             simplified_current_fen = simplify_fen(current_fen)
  565.             if board.is_checkmate():
  566.                 AR[simplified_current_fen]['to_end'] = -1000 if board.turn == chess.WHITE else 1000
  567.                 AR[simplified_current_fen]['type'] = 'checkmate'
  568.                 F += 1
  569.             elif board.is_stalemate():
  570.                 AR[simplified_current_fen]['to_end'] = -1000 if board.turn == chess.WHITE else 1000
  571.                 AR[simplified_current_fen]['type'] = 'stalemate'
  572.             elif board.is_insufficient_material():
  573.                 AR[simplified_current_fen]['to_end'] = -1000 if board.turn == chess.WHITE else 1000
  574.                 AR[simplified_current_fen]['type'] = 'insufficient_material'
  575.             else:
  576.                 AR[simplified_current_fen]['type'] = 'check' if board.is_check() else 'normal'
  577.  
  578.         print(f"Počet pozic v matu je {F}")
  579.         print(f"Počet pozic v patu je {sum(1 for data in AR.values() if data['type'] == 'stalemate')}")
  580.         print(f"Počet pozic s nedostatečným materiálem je {sum(1 for data in AR.values() if data['type'] == 'insufficient_material')}")
  581.         print(f"Počet pozic v šachu je {sum(1 for data in AR.values() if data['type'] == 'check')}")
  582.         print(f"Počet normálních pozic je {sum(1 for data in AR.values() if data['type'] == 'normal')}")
  583.  
  584.         # Iterativní ohodnocení
  585.         print("\nZačínám iterativní ohodnocení...")
  586.         uroven = 0
  587.         while True:
  588.             uroven += 1
  589.             level_start_time = time.time()
  590.             print(f"Výpočet v úrovni {uroven}")
  591.            
  592.             F = 0
  593.             current_level_positions = 0
  594.             changes_made = False
  595.             for i in range(1, N + 1):
  596.                 current_fen = POZ[i]
  597.                 board.set_custom_fen(current_fen)
  598.                 simplified_current_fen = simplify_fen(current_fen)
  599.                 if AR[simplified_current_fen].get('to_end') is None:
  600.                     hod = None
  601.                     for move in board.legal_moves:
  602.                         board.push(move)
  603.                         POZ2 = board.fen()
  604.                         simplified_POZ2 = simplify_fen(POZ2)
  605.                         if simplified_POZ2 in AR:
  606.                             ar_entry = AR[simplified_POZ2]
  607.                             if ar_entry is not None and 'to_end' in ar_entry and ar_entry['to_end'] is not None:
  608.                                 hod2 = -ar_entry['to_end']
  609.                                 if hod is None or hod2 > hod:
  610.                                     hod = hod2
  611.                         board.pop()
  612.                    
  613.                     if hod is None:
  614.                         hod = 0
  615.                     elif hod > 900:
  616.                         hod = 1000 - uroven
  617.                     elif hod < -900:
  618.                         hod = -1000 + uroven
  619.                    
  620.                     if AR[simplified_current_fen]['to_end'] != hod:
  621.                         changes_made = True
  622.                     AR[simplified_current_fen]['to_end'] = hod
  623.                     F += 1
  624.                     current_level_positions += 1
  625.             level_end_time = time.time()
  626.             total_elapsed_time = level_end_time - start_time
  627.             level_elapsed_time = level_end_time - level_start_time
  628.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  629.             print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  630.            
  631.             if not changes_made:
  632.                 print("Žádné změny v této úrovni, ukončuji iterativní ohodnocení.")
  633.                 break
  634.        
  635.             if current_level_positions == 0:
  636.                 break
  637.        
  638.         print(f"Nalezeno {F} pozic celkem")
  639.         print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  640.  
  641.         print("\nKontrola počáteční pozice v AR na konci výpočtu:")
  642.         if simplified_start_fen in AR:
  643.             print(f"Počáteční pozice je v AR: {AR[simplified_start_fen]}")
  644.         else:
  645.             print("Počáteční pozice není v AR")
  646.  
  647.         print("\nVýpočet dokončen.")
  648.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  649.  
  650.     finally:
  651.         stop_event.set()
  652.         timer_thread.join()
  653.  
  654. def find_min_positive_value(AR):
  655.     min_positive_value = float('inf')
  656.     min_fen = None
  657.    
  658.     for fen, (value, type_pozice) in AR.items():
  659.         if value is not None and value > 0 and value < min_positive_value:
  660.             min_positive_value = value
  661.             min_fen = fen
  662.    
  663.     if min_positive_value == float('inf'):
  664.         print("Žádná kladná hodnota nebyla nalezena.")
  665.     else:
  666.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  667.  
  668. def print_board(fen):
  669.     board = CustomBoard(fen)
  670.     print(board)
  671.  
  672. # Hlavní provedení
  673. if __name__ == "__main__":
  674.     start_fen = "8/2P5/4K3/8/8/8/k7/8 w - - 0 1"
  675.  
  676.     start_fen = "8/8/4K3/6A1/8/8/8/3k4 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. # Tisk optimálních tahů
  718.     # current_fen = start_fen
  719.     # simplified_current_fen = simplify_fen(current_fen)
  720.     # optimal_moves = []
  721.    
  722.     while True:
  723.         board = CustomBoard(current_fen)
  724.         if board.is_game_over():
  725.             break
  726.    
  727.         simplified_current_fen = simplify_fen(current_fen)
  728.         if simplified_current_fen not in AR:
  729.             print(f"Pozice {simplified_current_fen} není v AR")
  730.             break
  731.    
  732.         current_value = AR[simplified_current_fen][0]
  733.         print(f"Aktuální hodnota: {current_value}")
  734.    
  735.         if abs(current_value) == 1000:
  736.             print("Dosažena koncová pozice")
  737.             break
  738.    
  739.         best_move = None
  740.         best_value = -2000 if board.turn == chess.WHITE else 2000
  741.    
  742.         for move in board.legal_moves:
  743.             board.push(move)
  744.             next_fen = board.fen()
  745.             simplified_next_fen = simplify_fen(next_fen)
  746.            
  747.             if simplified_next_fen in AR:
  748.                 next_value = AR[simplified_next_fen][0]
  749.                 if (board.turn == chess.BLACK and next_value > best_value) or \
  750.                    (board.turn == chess.WHITE and next_value < best_value):
  751.                     best_value = next_value
  752.                     best_move = move
  753.            
  754.             board.pop()
  755.    
  756.         if best_move is None:
  757.             print("Žádný další tah nenalezen")
  758.             break
  759.    
  760.         board.push(best_move)
  761.         current_fen = board.fen()
  762.         optimal_moves.append((best_move, current_fen, best_value))
  763.    
  764.     print("\nOptimální tahy:")
  765.     for move, fen, value in optimal_moves:
  766.         print(f"Tah: {move}")
  767.         print_board(fen)
  768.         print(f"Hodnota: {value}")
  769.         print(fen)
  770.         print("\n")
  771.    
  772.     print_board(start_fen)
  773.     simplified_start_fen = simplify_fen(start_fen)
  774.     if simplified_start_fen in AR:
  775.         print(AR[simplified_start_fen])
  776.     else:
  777.         print("Počáteční pozice není v AR")
  778.     print(start_fen)
  779.     print("\n")
  780.  
  781.     print("\nPrvních 20 položek z AR:")
  782.     for i, (fen, data) in enumerate(AR.items()):
  783.         if i >= 20:
  784.             break
  785.         to_end, type_pozice = data
  786.         print(f"{i+1}. FEN: {fen}")
  787.         print(f"   to_end: {to_end}")
  788.         print(f"   type: {type_pozice}")
  789.         print()
  790.        
  791.     print(f"Celkový počet pozic 'checkmate': {sum(1 for _, (_, type_pozice) in AR.items() if type_pozice == 'checkmate')}")
  792.     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