Advertisement
max2201111

L

Aug 13th, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 31.00 KB | Science | 0 0
  1. import chess
  2. from typing import Iterator, Optional, Dict, Tuple
  3. from chess import Move, BB_ALL, Bitboard, PieceType, Color
  4. import time
  5. from collections import deque
  6. import threading
  7.  
  8. # Definice nových figur
  9. AMAZON = 7
  10. CYRIL = 8
  11. EVE = 9
  12.  
  13. # Rozšíření seznamu PIECE_SYMBOLS
  14. chess.PIECE_SYMBOLS.append('a')
  15. chess.PIECE_SYMBOLS.append('c')
  16. chess.PIECE_SYMBOLS.append('e')
  17.  
  18. class CustomBoard(chess.Board):
  19.     def __init__(self, fen=None):
  20.         self.amazons_white = chess.BB_EMPTY
  21.         self.amazons_black = chess.BB_EMPTY
  22.         self.cyrils_white = chess.BB_EMPTY
  23.         self.cyrils_black = chess.BB_EMPTY
  24.         self.eves_white = chess.BB_EMPTY
  25.         self.eves_black = chess.BB_EMPTY
  26.         super().__init__(None)
  27.         if fen:
  28.             self.set_custom_fen(fen)
  29.         self.debug_amazons()
  30.         self.debug_cyrils()
  31.         self.debug_eves()
  32.  
  33.     def clear_square(self, square):
  34.         super()._remove_piece_at(square)
  35.         self.amazons_white &= ~chess.BB_SQUARES[square]
  36.         self.amazons_black &= ~chess.BB_SQUARES[square]
  37.         self.cyrils_white &= ~chess.BB_SQUARES[square]
  38.         self.cyrils_black &= ~chess.BB_SQUARES[square]
  39.         self.eves_white &= ~chess.BB_SQUARES[square]
  40.         self.eves_black &= ~chess.BB_SQUARES[square]
  41.  
  42.     def set_custom_fen(self, fen):
  43.         parts = fen.split()
  44.         board_part = parts[0]
  45.    
  46.         self.clear()
  47.         self.amazons_white = chess.BB_EMPTY
  48.         self.amazons_black = chess.BB_EMPTY
  49.         self.cyrils_white = chess.BB_EMPTY
  50.         self.cyrils_black = chess.BB_EMPTY
  51.         self.eves_white = chess.BB_EMPTY
  52.         self.eves_black = chess.BB_EMPTY
  53.    
  54.         square = 56
  55.         for c in board_part:
  56.             if c == '/':
  57.                 square -= 16
  58.             elif c.isdigit():
  59.                 square += int(c)
  60.             else:
  61.                 color = chess.WHITE if c.isupper() else chess.BLACK
  62.                 if c.upper() == 'A':
  63.                     if color == chess.WHITE:
  64.                         self.amazons_white |= chess.BB_SQUARES[square]
  65.                     else:
  66.                         self.amazons_black |= chess.BB_SQUARES[square]
  67.                     piece_type = AMAZON
  68.                 elif c.upper() == 'C':
  69.                     if color == chess.WHITE:
  70.                         self.cyrils_white |= chess.BB_SQUARES[square]
  71.                     else:
  72.                         self.cyrils_black |= chess.BB_SQUARES[square]
  73.                     piece_type = CYRIL
  74.                 elif c.upper() == 'E':
  75.                     if color == chess.WHITE:
  76.                         self.eves_white |= chess.BB_SQUARES[square]
  77.                     else:
  78.                         self.eves_black |= chess.BB_SQUARES[square]
  79.                     piece_type = EVE
  80.                 elif c == 'P' and chess.square_rank(square) == 7:
  81.                     piece_type = AMAZON
  82.                     color = chess.WHITE
  83.                 elif c == 'p' and chess.square_rank(square) == 0:
  84.                     piece_type = AMAZON
  85.                     color = chess.BLACK
  86.                 else:
  87.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  88.                
  89.                 self._set_piece_at(square, piece_type, color)
  90.                 square += 1
  91.    
  92.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  93.         self.castling_rights = chess.BB_EMPTY
  94.         if '-' not in parts[2]:
  95.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  96.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  97.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  98.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  99.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  100.            
  101.  
  102.     def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
  103.         self.clear_square(square)
  104.         super()._set_piece_at(square, piece_type, color)
  105.         if piece_type == AMAZON:
  106.             if color == chess.WHITE:
  107.                 self.amazons_white |= chess.BB_SQUARES[square]
  108.             else:
  109.                 self.amazons_black |= chess.BB_SQUARES[square]
  110.         elif piece_type == CYRIL:
  111.             if color == chess.WHITE:
  112.                 self.cyrils_white |= chess.BB_SQUARES[square]
  113.             else:
  114.                 self.cyrils_black |= chess.BB_SQUARES[square]
  115.         elif piece_type == EVE:
  116.             if color == chess.WHITE:
  117.                 self.eves_white |= chess.BB_SQUARES[square]
  118.             else:
  119.                 self.eves_black |= chess.BB_SQUARES[square]
  120.  
  121.     def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
  122.         if self.amazons_white & chess.BB_SQUARES[square]:
  123.             return chess.Piece(AMAZON, chess.WHITE)
  124.         elif self.amazons_black & chess.BB_SQUARES[square]:
  125.             return chess.Piece(AMAZON, chess.BLACK)
  126.         elif self.cyrils_white & chess.BB_SQUARES[square]:
  127.             return chess.Piece(CYRIL, chess.WHITE)
  128.         elif self.cyrils_black & chess.BB_SQUARES[square]:
  129.             return chess.Piece(CYRIL, chess.BLACK)
  130.         elif self.eves_white & chess.BB_SQUARES[square]:
  131.             return chess.Piece(EVE, chess.WHITE)
  132.         elif self.eves_black & chess.BB_SQUARES[square]:
  133.             return chess.Piece(EVE, chess.BLACK)
  134.         return super().piece_at(square)
  135.  
  136.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  137.         our_pieces = self.occupied_co[self.turn]
  138.         if self.turn == chess.WHITE:
  139.             our_amazons = self.amazons_white
  140.             our_cyrils = self.cyrils_white
  141.             our_eves = self.eves_white
  142.         else:
  143.             our_amazons = self.amazons_black
  144.             our_cyrils = self.cyrils_black
  145.             our_eves = self.eves_black
  146.    
  147.         # Generování tahů pro amazonky
  148.         for from_square in chess.scan_forward(our_amazons & from_mask):
  149.             attacks = self.amazon_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 Cyrily
  155.         for from_square in chess.scan_forward(our_cyrils & from_mask):
  156.             attacks = self.cyril_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 Evy
  162.         for from_square in chess.scan_forward(our_eves & from_mask):
  163.             attacks = self.eve_attacks(from_square)
  164.             valid_moves = attacks & ~our_pieces & to_mask
  165.             for to_square in chess.scan_forward(valid_moves):
  166.                 yield Move(from_square, to_square)
  167.    
  168.         # Generování tahů pro standardní figury
  169.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  170.             piece = self.piece_at(move.from_square)
  171.             if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
  172.                 yield move
  173.  
  174.     def queen_attacks(self, square):
  175.         return self.bishop_attacks(square) | self.rook_attacks(square)
  176.  
  177.     def bishop_attacks(self, square):
  178.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  179.  
  180.     def rook_attacks(self, square):
  181.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  182.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  183.  
  184.     def amazon_attacks(self, square):
  185.         return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  186.  
  187.     def cyril_attacks(self, square):
  188.         return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS[quare]
  189.  
  190.     def eve_attacks(self, square):
  191.         return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  192.  
  193.     def is_pseudo_legal(self, move):
  194.         from_square = move.from_square
  195.         to_square = move.to_square
  196.         piece = self.piece_at(from_square)
  197.    
  198.         if not piece or piece.color != self.turn:
  199.             return False
  200.    
  201.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  202.             return False
  203.    
  204.         if self.is_castling(move):
  205.             return True
  206.    
  207.         if piece.piece_type == AMAZON:
  208.             return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
  209.         elif piece.piece_type == CYRIL:
  210.             return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
  211.         elif piece.piece_type == EVE:
  212.             return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
  213.         else:
  214.             return super().is_pseudo_legal(move)
  215.  
  216.     def is_legal(self, move):
  217.         if not self.is_pseudo_legal(move):
  218.             return False
  219.    
  220.         from_square = move.from_square
  221.         to_square = move.to_square
  222.         piece = self.piece_at(from_square)
  223.         captured_piece = self.piece_at(to_square)
  224.    
  225.         self.clear_square(from_square)
  226.         self.clear_square(to_square)
  227.         self._set_piece_at(to_square, piece.piece_type, piece.color)
  228.    
  229.         king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
  230.         is_check = False
  231.         if king_square is not None:
  232.             is_check = self._is_attacked_by(not self.turn, king_square)
  233.    
  234.         self.clear_square(to_square)
  235.         self._set_piece_at(from_square, piece.piece_type, piece.color)
  236.         if captured_piece:
  237.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  238.    
  239.         return not is_check
  240.    
  241.  
  242.     def _is_attacked_by(self, color, square):
  243.         attackers = self.attackers(color, square)
  244.         return bool(attackers)
  245.  
  246.     def attackers(self, color, square):
  247.         if square is None:
  248.             return chess.BB_EMPTY
  249.  
  250.         attackers = chess.BB_EMPTY
  251.         occupied = self.occupied
  252.        
  253.         # Knights
  254.         knights = self.knights & self.occupied_co[color]
  255.         if chess.BB_KNIGHT_ATTACKS[square] & knights:
  256.             attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  257.        
  258.         # King
  259.         king = self.kings & self.occupied_co[color]
  260.         if chess.BB_KING_ATTACKS[square] & king:
  261.             attackers |= king
  262.        
  263.         # Pawns
  264.         pawns = self.pawns & self.occupied_co[color]
  265.         pawn_attacks = chess.BB_PAWN_ATTACKS[not color][square]
  266.         if pawn_attacks & pawns:
  267.             attackers |= pawns & pawn_attacks
  268.        
  269.         # Queens
  270.         queens = self.queens & self.occupied_co[color]
  271.         queen_attacks = (
  272.             chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] |
  273.             chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  274.             chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
  275.         )
  276.         if queen_attacks & queens:
  277.             attackers |= queens & queen_attacks
  278.        
  279.         # Bishops
  280.         bishops = self.bishops & self.occupied_co[color]
  281.         bishop_attacks = chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  282.         if bishop_attacks & bishops:
  283.             attackers |= bishops & bishop_attacks
  284.        
  285.         # Rooks
  286.         rooks = self.rooks & self.occupied_co[color]
  287.         rook_attacks = (
  288.             chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  289.             chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
  290.         )
  291.         if rook_attacks & rooks:
  292.             attackers |= rooks & rook_attacks
  293.        
  294.         # Amazons (Queen + Knight)
  295.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  296.         for amazon_square in chess.scan_forward(amazons):
  297.             amazon_attacks = (
  298.                 chess.BB_DIAG_ATTACKS[amazon_square][self.occupied & chess.BB_DIAG_MASKS[amazon_square]] |
  299.                 chess.BB_RANK_ATTACKS[amazon_square][self.occupied & chess.BB_RANK_MASKS[amazon_square]] |
  300.                 chess.BB_FILE_ATTACKS[amazon_square][self.occupied & chess.BB_FILE_MASKS[amazon_square]] |
  301.                 chess.BB_KNIGHT_ATTACKS[amazon_square]
  302.             )
  303.             if amazon_attacks & chess.BB_SQUARES[square]:
  304.                 attackers |= chess.BB_SQUARES[amazon_square]
  305.        
  306.         # Cyrils (Rook + Knight)
  307.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  308.         for cyril_square in chess.scan_forward(cyrils):
  309.             cyril_attacks = (
  310.                 chess.BB_RANK_ATTACKS[cyril_square][self.occupied & chess.BB_RANK_MASKS[cyril_square]] |
  311.                 chess.BB_FILE_ATTACKS[cyril_square][self.occupied & chess.BB_FILE_MASKS[cyril_square]] |
  312.                 chess.BB_KNIGHT_ATTACKS[cyril_square]
  313.             )
  314.             if cyril_attacks & chess.BB_SQUARES[square]:
  315.                 attackers |= chess.BB_SQUARES[cyril_square]
  316.        
  317.         # Eves (Bishop + Knight)
  318. # Eves (Bishop + Knight)
  319.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  320.         for eve_square in chess.scan_forward(eves):
  321.             eve_attacks = (
  322.                 chess.BB_DIAG_ATTACKS[eve_square][self.occupied & chess.BB_DIAG_MASKS[eve_square]] |
  323.                 chess.BB_KNIGHT_ATTACKS[eve_square]
  324.             )
  325.             if eve_attacks & chess.BB_SQUARES[square]:
  326.                 attackers |= chess.BB_SQUARES[eve_square]
  327.        
  328.         return attackers
  329.  
  330.     def push(self, move):
  331.         if not self.is_legal(move):
  332.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  333.  
  334.         piece = self.piece_at(move.from_square)
  335.         captured_piece = self.piece_at(move.to_square)
  336.  
  337.         self.clear_square(move.from_square)
  338.         self.clear_square(move.to_square)
  339.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  340.  
  341.         self.turn = not self.turn
  342.  
  343.         self.move_stack.append((move, captured_piece))
  344.  
  345.     def pop(self):
  346.         if not self.move_stack:
  347.             return None
  348.  
  349.         move, captured_piece = self.move_stack.pop()
  350.  
  351.         piece = self.piece_at(move.to_square)
  352.        
  353.         self.clear_square(move.from_square)
  354.         self.clear_square(move.to_square)
  355.  
  356.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  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 format_time(seconds):
  458.     hours, remainder = divmod(seconds, 3600)
  459.     minutes, seconds = divmod(remainder, 60)
  460.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  461.  
  462. def print_elapsed_time(stop_event, start_time):
  463.     while not stop_event.is_set():
  464.         elapsed_time = time.time() - start_time
  465.         print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
  466.         time.sleep(1)
  467.  
  468. def simplify_fen(fen):
  469.     return ' '.join(fen.split()[:4])
  470.  
  471. def calculate_optimal_moves(start_fen: str) -> Dict[str, Tuple[int, str]]:
  472.     print("Funkce calculate_optimal_moves byla zavolána")
  473.     print(f"Počáteční FEN: {start_fen}")
  474.    
  475.     board = CustomBoard(start_fen)
  476.     POZ = {1: simplify_fen(start_fen)}
  477.     AR = {simplify_fen(start_fen): {'used': 0, 'to_end': None, 'depth': 0, 'type': 'normal'}}
  478.     N = 1
  479.     M = 0
  480.  
  481.     start_time = time.time()
  482.     current_depth = 0
  483.     positions_at_depth = {0: 0}
  484.     depth_start_time = start_time
  485.  
  486.     stop_event = threading.Event()
  487.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event, start_time))
  488.     timer_thread.start()
  489.  
  490.     try:
  491.         print("Začínám generovat pozice...")
  492.         print("Počáteční pozice:")
  493.         print_board(start_fen)
  494.        
  495.         depth_1_positions = []  # Seznam pro ukládání pozic v hloubce 1
  496.  
  497.         # Generate all positions
  498.         while M < N:
  499.             M += 1
  500.             current_fen = POZ[M]
  501.             board.set_custom_fen(current_fen)
  502.             simplified_current_fen = simplify_fen(current_fen)
  503.             current_depth = AR[simplified_current_fen]['depth']
  504.  
  505.             if current_depth not in positions_at_depth:
  506.                 positions_at_depth[current_depth] = 0
  507.                 if current_depth > 0:
  508.                     depth_time = time.time() - depth_start_time
  509.                     total_time = time.time() - start_time
  510.                     print(f"\nHloubka {current_depth - 1}: {positions_at_depth[current_depth - 1]} pozic, "
  511.                           f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  512.                    
  513.                     if current_depth == 1:
  514.                         print("Všechny pozice v hloubce 1:")
  515.                         for pos in depth_1_positions:
  516.                             print_board(pos)
  517.                             print()
  518.                
  519.                 depth_start_time = time.time()
  520.  
  521.             positions_at_depth[current_depth] += 1
  522.  
  523.             if current_depth == 1:
  524.                 depth_1_positions.append(current_fen)
  525.  
  526.             if AR[simplified_current_fen]['used'] == 0:
  527.                 AR[simplified_current_fen]['used'] = 1
  528.                 legal_moves = list(board.legal_moves)
  529.                 for move in legal_moves:
  530.                     board.push(move)
  531.                     POZ2 = board.fen()
  532.                     simplified_POZ2 = simplify_fen(POZ2)
  533.                     if simplified_POZ2 not in AR:
  534.                         N += 1
  535.                         POZ[N] = simplified_POZ2
  536.                         AR[simplified_POZ2] = {'used': 0, 'to_end': None, 'depth': current_depth + 1, 'type': 'normal'}
  537.                     board.pop()
  538.    
  539.         # Print last depth
  540.         depth_time = time.time() - depth_start_time
  541.         total_time = time.time() - start_time
  542.         print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
  543.               f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  544.         print(f"Příklad pozice v hloubce {current_depth}:")
  545.         print_board(current_fen)
  546.  
  547.         print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
  548.  
  549.         # Initial evaluation
  550.         print("\nZačínám počáteční ohodnocení...")
  551.         F_checkmate = 0
  552.         F_stalemate = 0
  553.         F_drawing = 0
  554.         F_check = 0
  555.         F_normal = 0
  556.         for i in range(1, N + 1):
  557.             current_fen = POZ[i]
  558.             board.set_custom_fen(current_fen)
  559.             simplified_current_fen = simplify_fen(current_fen)
  560.  
  561.             if board.is_checkmate():
  562.                 AR[simplified_current_fen]['to_end'] = -1000
  563.                 AR[simplified_current_fen]['type'] = 'checkmate'
  564.                 F_checkmate += 1
  565.             elif board.is_stalemate():
  566.                 AR[simplified_current_fen]['to_end'] = 0
  567.                 AR[simplified_current_fen]['type'] = 'stalemate'
  568.                 F_stalemate += 1
  569.             elif board.is_insufficient_material():
  570.                 AR[simplified_current_fen]['to_end'] = 0
  571.                 AR[simplified_current_fen]['type'] = 'drawing'
  572.                 F_drawing += 1
  573.             elif board.is_check():
  574.                 AR[simplified_current_fen]['to_end'] = None
  575.                 AR[simplified_current_fen]['type'] = 'check'
  576.                 F_check += 1
  577.             else:
  578.                 AR[simplified_current_fen]['to_end'] = None
  579.                 AR[simplified_current_fen]['type'] = 'normal'
  580.                 F_normal += 1
  581.  
  582.         print(f"Počet pozic v matu je {F_checkmate}")
  583.         print(f"Počet pozic v patu je {F_stalemate}")
  584.         print(f"Počet pozic v remíze je {F_drawing}")
  585.         print(f"Počet pozic v šachu je {F_check}")
  586.         print(f"Počet normálních pozic je {F_normal}")
  587.  
  588.         # Iterative evaluation
  589.         print("\nZačínám iterativní ohodnocení...")
  590.         uroven = 0
  591.         while True:
  592.             uroven += 1
  593.             level_start_time = time.time()
  594.             print(f"Výpočet v úrovni {uroven}")
  595.            
  596.             changed = False
  597.             current_level_positions = 0
  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]['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 and AR[simplified_POZ2]['to_end'] is not None:
  609.                             hod2 = -AR[simplified_POZ2]['to_end']
  610.                             if hod2 > hod:
  611.                                 hod = hod2
  612.                         board.pop()
  613.                    
  614.                     if hod == 1001 - uroven:
  615.                         new_to_end = 1000 - uroven
  616.                         new_type = 'winning'
  617.                     elif hod == -1001 + uroven:
  618.                         new_to_end = -1000 + uroven
  619.                         new_type = 'losing'
  620.                     elif hod == 0:
  621.                         new_to_end = 0
  622.                         new_type = 'drawing'
  623.                     elif hod > -2000:  # Pokud byl nalezen alespoň jeden platný tah
  624.                         new_to_end = hod
  625.                         new_type = 'normal'
  626.                     else:
  627.                         new_to_end = None
  628.                         new_type = None
  629.                    
  630.                     if new_to_end is not None and (AR[simplified_current_fen]['to_end'] != new_to_end or AR[simplified_current_fen]['type'] != new_type):
  631.                         AR[simplified_current_fen]['to_end'] = new_to_end
  632.                         AR[simplified_current_fen]['type'] = new_type
  633.                         changed = True
  634.                         current_level_positions += 1
  635.            
  636.             level_end_time = time.time()
  637.             total_elapsed_time = level_end_time - start_time
  638.             level_elapsed_time = level_end_time - level_start_time
  639.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  640.             print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  641.            
  642.             if not changed:
  643.                 print("Hodnocení ukončeno - žádné další změny.")
  644.                 break
  645.        
  646.         print(f"Celkem nalezeno {sum(1 for data in AR.values() if data['to_end'] is not None)} ohodnocených pozic")
  647.  
  648.         print("\nVýpočet dokončen.")
  649.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  650.  
  651.     finally:
  652.         stop_event.set()
  653.         timer_thread.join()
  654.  
  655.  
  656. # Helper function to print the board
  657. def print_board(fen):
  658.     board = CustomBoard(fen)
  659.     print(board)
  660.  
  661. # Najděte nejmenší kladnou hodnotu to_end ve všech FEN záznamech v AR
  662. def find_min_positive_value(AR):
  663.     min_positive_value = float('inf')
  664.     min_fen = None
  665.    
  666.     for fen, (value, type_pozice) in AR.items():
  667.         if value is not None and value > 0 and value < min_positive_value:
  668.             min_positive_value = value
  669.             min_fen = fen
  670.    
  671.     if min_positive_value == float('inf'):
  672.         print("Žádná kladná hodnota nebyla nalezena.")
  673.     else:
  674.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  675.  
  676. # Main execution
  677. # Main execution
  678. if __name__ == "__main__":
  679.     start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  680.  
  681.     start_fen = "7K/8/8/8/8/k7/8/7A w - - 0 1"
  682.  
  683.  #   start_fen = "7K/8/8/2a5/8/1k6/8/7A w - - 0 1"
  684.  
  685.     start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  686.  
  687.     start_fen = "6K1/3E4/8/8/8/k7/8/8 w - - 0 1"
  688.  
  689.     start_fen = "8/5A2/8/8/2K5/8/ka6/8 w - - 0 1"
  690.  
  691.     start_fen = "8/3A4/7K/8/4a3/8/4k3/8 w - - 0 1"
  692.    
  693.     AR = calculate_optimal_moves(start_fen)
  694.  
  695.     find_min_positive_value(AR)
  696.  
  697.     # print("\nVýsledky:")
  698.     # for hodnota in range(-996, -1001, -1):  # Generuje hodnoty -996, -997, -998, -999, -1000
  699.     #     for fen, (fen_hodnota, typ_pozice) in AR.items():
  700.     #         if fen_hodnota == hodnota:
  701.     #             print(f"FEN: {fen}")
  702.     #             print(f"Hodnota: {fen_hodnota}")
  703.     #             print(f"Typ pozice: {typ_pozice}")
  704.                
  705.     #             temp_board = CustomBoard(fen)
  706.                
  707.     #             if temp_board.is_checkmate():
  708.     #                 print("Stav: Mat")
  709.     #             elif temp_board.is_stalemate():
  710.     #                 print("Stav: Pat")
  711.     #             elif temp_board.is_insufficient_material():
  712.     #                 print("Stav: Nedostatečný materiál")
  713.     #             elif temp_board.is_check():
  714.     #                 print("Stav: Šach")
  715.     #             else:
  716.     #                 print("Stav: Normální pozice")
  717.      
  718.     #             print_board(fen)
  719.                
  720.     #             print()
  721.  
  722.     # Print optimal moves
  723. # Print optimal moves
  724.     current_fen = start_fen
  725.     simplified_current_fen = simplify_fen(current_fen)
  726.     simplified_current_fen1 = simplified_current_fen
  727.     optimal_moves = []
  728.    
  729.     while True:
  730.         board = CustomBoard(current_fen)
  731.         if board.is_checkmate():
  732.             print("Mat detekován!")
  733.             break
  734.        
  735.         # Opravená část
  736.         half_move_clock = current_fen.split()[-2]
  737.         if board.is_insufficient_material() or (half_move_clock != '-' and int(half_move_clock) >= 100):
  738.             if board.is_insufficient_material():
  739.                 print("Nedostatečný materiál detekován!")
  740.             else:
  741.                 print("Remíza pravidlem 50 tahů detekována!")
  742.             AR[simplified_current_fen] = (0, 'drawing')  # Aktualizujeme AR pro tuto pozici
  743.             break
  744.        
  745.         if simplified_current_fen not in AR:
  746.             print(f"Pozice {simplified_current_fen} není v AR.")
  747.             break
  748.        
  749.         current_value = AR[simplified_current_fen][0]
  750.        
  751.         if current_value == 0:
  752.             print("Remíza dosažena!")
  753.             break
  754.        
  755.         hod = -2000 if current_value > 0 else 2000
  756.         best_fen = None
  757.         for move in board.legal_moves:
  758.             board.push(move)
  759.             POZ2 = board.fen()
  760.             simplified_POZ2 = simplify_fen(POZ2)
  761.             if simplified_POZ2 in AR:
  762.                 hod2 = -AR[simplified_POZ2][0]
  763.                 if current_value > 0:  # Silnější hráč
  764.                     if hod2 > hod:
  765.                         hod = hod2
  766.                         best_fen = simplified_POZ2
  767.                 else:  # Slabší hráč
  768.                     if hod2 < hod:
  769.                         hod = hod2
  770.                         best_fen = simplified_POZ2
  771.             board.pop()
  772.        
  773.         if best_fen is None:
  774.             print("Žádný další tah nebyl nalezen.")
  775.             break
  776.         optimal_moves.append(best_fen)
  777.         current_fen = best_fen
  778.         simplified_current_fen = simplify_fen(current_fen)
  779.            
  780.    
  781.     print("\nOptimální tahy:")
  782.     for fen in reversed(optimal_moves):
  783.         print_board(fen)
  784.         hodnota, typ_pozice = AR[simplify_fen(fen)]
  785.         print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  786.         print(fen)
  787.         print("\n")
  788.        
  789.     print_board(simplified_current_fen1)
  790.     hodnota, typ_pozice = AR[simplified_current_fen1]
  791.     print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  792.     print(simplified_current_fen1)
  793.     print("\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement