Advertisement
max2201111

jooo!!

Jul 28th, 2024 (edited)
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 29.96 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.                 elif c == 'p' and chess.square_rank(square) == 0:
  83.                     piece_type = AMAZON
  84.                     color = chess.BLACK
  85.                 else:
  86.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  87.                 self._set_piece_at(square, piece_type, color)
  88.                 square += 1
  89.  
  90.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  91.         self.castling_rights = chess.BB_EMPTY
  92.         if '-' not in parts[2]:
  93.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  94.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  95.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  96.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  97.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  98.  
  99.     def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
  100.         self.clear_square(square)
  101.         super()._set_piece_at(square, piece_type, color)
  102.         if piece_type == AMAZON:
  103.             if color == chess.WHITE:
  104.                 self.amazons_white |= chess.BB_SQUARES[square]
  105.             else:
  106.                 self.amazons_black |= chess.BB_SQUARES[square]
  107.         elif piece_type == CYRIL:
  108.             if color == chess.WHITE:
  109.                 self.cyrils_white |= chess.BB_SQUARES[square]
  110.             else:
  111.                 self.cyrils_black |= chess.BB_SQUARES[square]
  112.         elif piece_type == EVE:
  113.             if color == chess.WHITE:
  114.                 self.eves_white |= chess.BB_SQUARES[square]
  115.             else:
  116.                 self.eves_black |= chess.BB_SQUARES[square]
  117.  
  118.     def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
  119.         if self.amazons_white & chess.BB_SQUARES[square]:
  120.             return chess.Piece(AMAZON, chess.WHITE)
  121.         elif self.amazons_black & chess.BB_SQUARES[square]:
  122.             return chess.Piece(AMAZON, chess.BLACK)
  123.         elif self.cyrils_white & chess.BB_SQUARES[square]:
  124.             return chess.Piece(CYRIL, chess.WHITE)
  125.         elif self.cyrils_black & chess.BB_SQUARES[square]:
  126.             return chess.Piece(CYRIL, chess.BLACK)
  127.         elif self.eves_white & chess.BB_SQUARES[square]:
  128.             return chess.Piece(EVE, chess.WHITE)
  129.         elif self.eves_black & chess.BB_SQUARES[square]:
  130.             return chess.Piece(EVE, chess.BLACK)
  131.         return super().piece_at(square)
  132.  
  133.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  134.         our_pieces = self.occupied_co[self.turn]
  135.         if self.turn == chess.WHITE:
  136.             our_amazons = self.amazons_white
  137.             our_cyrils = self.cyrils_white
  138.             our_eves = self.eves_white
  139.         else:
  140.             our_amazons = self.amazons_black
  141.             our_cyrils = self.cyrils_black
  142.             our_eves = self.eves_black
  143.    
  144.         # Generování tahů pro amazonky
  145.         for from_square in chess.scan_forward(our_amazons & from_mask):
  146.             attacks = self.amazon_attacks(from_square)
  147.             valid_moves = attacks & ~our_pieces & to_mask
  148.             for to_square in chess.scan_forward(valid_moves):
  149.                 yield Move(from_square, to_square)
  150.    
  151.         # Generování tahů pro Cyrily
  152.         for from_square in chess.scan_forward(our_cyrils & from_mask):
  153.             attacks = self.cyril_attacks(from_square)
  154.             valid_moves = attacks & ~our_pieces & to_mask
  155.             for to_square in chess.scan_forward(valid_moves):
  156.                 yield Move(from_square, to_square)
  157.    
  158.         # Generování tahů pro Evy
  159.         for from_square in chess.scan_forward(our_eves & from_mask):
  160.             attacks = self.eve_attacks(from_square)
  161.             valid_moves = attacks & ~our_pieces & to_mask
  162.             for to_square in chess.scan_forward(valid_moves):
  163.                 yield Move(from_square, to_square)
  164.    
  165.         # Generování tahů pro standardní figury
  166.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  167.             piece = self.piece_at(move.from_square)
  168.             if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
  169.                 yield move
  170.  
  171.     def queen_attacks(self, square):
  172.         return self.bishop_attacks(square) | self.rook_attacks(square)
  173.  
  174.     def bishop_attacks(self, square):
  175.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  176.  
  177.     def rook_attacks(self, square):
  178.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  179.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  180.  
  181.     def amazon_attacks(self, square):
  182.         return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  183.  
  184.     def cyril_attacks(self, square):
  185.         return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS(square)
  186.  
  187.     def eve_attacks(self, square):
  188.         return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS(square)
  189.  
  190.     def is_pseudo_legal(self, move):
  191.         from_square = move.from_square
  192.         to_square = move.to_square
  193.         piece = self.piece_at(from_square)
  194.    
  195.         if not piece or piece.color != self.turn:
  196.             return False
  197.    
  198.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  199.             return False
  200.    
  201.         if self.is_castling(move):
  202.             return True
  203.    
  204.         if piece.piece_type == AMAZON:
  205.             return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
  206.         elif piece.piece_type == CYRIL:
  207.             return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
  208.         elif piece.piece_type == EVE:
  209.             return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
  210.         else:
  211.             return super().is_pseudo_legal(move)
  212.  
  213.     def is_legal(self, move):
  214.         if not self.is_pseudo_legal(move):
  215.             return False
  216.    
  217.         from_square = move.from_square
  218.         to_square = move.to_square
  219.         piece = self.piece_at(from_square)
  220.         captured_piece = self.piece_at(to_square)
  221.    
  222.         self.clear_square(from_square)
  223.         self.clear_square(to_square)
  224.         self._set_piece_at(to_square, piece.piece_type, piece.color)
  225.    
  226.         king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
  227.         is_check = False
  228.         if king_square is not None:
  229.             is_check = self._is_attacked_by(not self.turn, king_square)
  230.    
  231.         self.clear_square(to_square)
  232.         self._set_piece_at(from_square, piece.piece_type, piece.color)
  233.         if captured_piece:
  234.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  235.    
  236.         return not is_check
  237.    
  238.  
  239.     def _is_attacked_by(self, color, square):
  240.         attackers = self.attackers(color, square)
  241.         return bool(attackers)
  242.  
  243.     def attackers(self, color, square):
  244.         if square is None:
  245.             return chess.BB_EMPTY
  246.  
  247.         attackers = chess.BB_EMPTY
  248.        
  249.         # Knights
  250.         knights = self.knights & self.occupied_co[color]
  251.         if chess.BB_KNIGHT_ATTACKS[square] & knights:
  252.             attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  253.        
  254.         # King
  255.         king = self.kings & self.occupied_co[color]
  256.         if chess.BB_KING_ATTACKS[square] & king:
  257.             attackers |= king
  258.        
  259.         # Pawns
  260.         pawns = self.pawns & self.occupied_co[color]
  261.         pawn_attacks = chess.BB_PAWN_ATTACKS[not color][square]
  262.         if pawn_attacks & pawns:
  263.             attackers |= pawns & pawn_attacks
  264.        
  265.         # Queens
  266.         queens = self.queens & self.occupied_co[color]
  267.         queen_attacks = (
  268.             chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] |
  269.             chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  270.             chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
  271.         )
  272.         if queen_attacks & queens:
  273.             attackers |= queens & queen_attacks
  274.        
  275.         # Bishops
  276.         bishops = self.bishops & self.occupied_co[color]
  277.         bishop_attacks = chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  278.         if bishop_attacks & bishops:
  279.             attackers |= bishops & bishop_attacks
  280.        
  281.         # Rooks
  282.         rooks = self.rooks & self.occupied_co[color]
  283.         rook_attacks = (
  284.             chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  285.             chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
  286.         )
  287.         if rook_attacks & rooks:
  288.             attackers |= rooks & rook_attacks
  289.        
  290.         # Amazons (Queen + Knight)
  291.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  292.         for amazon_square in chess.scan_forward(amazons):
  293.             amazon_attacks = (
  294.                 chess.BB_DIAG_ATTACKS[amazon_square][self.occupied & chess.BB_DIAG_MASKS[amazon_square]] |
  295.                 chess.BB_RANK_ATTACKS[amazon_square][self.occupied & chess.BB_RANK_MASKS[amazon_square]] |
  296.                 chess.BB_FILE_ATTACKS[amazon_square][self.occupied & chess.BB_FILE_MASKS[amazon_square]] |
  297.                 chess.BB_KNIGHT_ATTACKS[amazon_square]
  298.             )
  299.             if amazon_attacks & chess.BB_SQUARES[square]:
  300.                 attackers |= chess.BB_SQUARES[amazon_square]
  301.        
  302.         # Cyrils (Rook + Knight)
  303.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  304.         for cyril_square in chess.scan_forward(cyrils):
  305.             cyril_attacks = (
  306.                 chess.BB_RANK_ATTACKS[cyril_square][self.occupied & chess.BB_RANK_MASKS[cyril_square]] |
  307.                 chess.BB_FILE_ATTACKS[cyril_square][self.occupied & chess.BB_FILE_MASKS[cyril_square]] |
  308.                 chess.BB_KNIGHT_ATTACKS[cyril_square]
  309.             )
  310.             if cyril_attacks & chess.BB_SQUARES[square]:
  311.                 attackers |= chess.BB_SQUARES[cyril_square]
  312.        
  313.         # Eves (Bishop + Knight)
  314. # Eves (Bishop + Knight)
  315.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  316.         for eve_square in chess.scan_forward(eves):
  317.             eve_attacks = (
  318.                 chess.BB_DIAG_ATTACKS[eve_square][self.occupied & chess.BB_DIAG_MASKS[eve_square]] |
  319.                 chess.BB_KNIGHT_ATTACKS[eve_square]
  320.             )
  321.             if eve_attacks & chess.BB_SQUARES[square]:
  322.                 attackers |= chess.BB_SQUARES[eve_square]
  323.        
  324.         return attackers
  325.  
  326.     def push(self, move):
  327.         if not self.is_legal(move):
  328.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  329.  
  330.         piece = self.piece_at(move.from_square)
  331.         captured_piece = self.piece_at(move.to_square)
  332.  
  333.         self.clear_square(move.from_square)
  334.         self.clear_square(move.to_square)
  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.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  353.  
  354.         if captured_piece:
  355.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  356.  
  357.         self.turn = not self.turn
  358.  
  359.         return move
  360.  
  361.     def is_check(self):
  362.         king_square = self.king(self.turn)
  363.         if king_square is None:
  364.             return False
  365.         is_check = self._is_attacked_by(not self.turn, king_square)
  366.         return is_check
  367.  
  368.     def is_checkmate(self):
  369.         if not self.is_check():
  370.             return False
  371.         legal_moves = list(self.generate_legal_moves())
  372.         return len(legal_moves) == 0
  373.  
  374.     def is_game_over(self):
  375.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  376.  
  377.     def is_stalemate(self):
  378.         if self.is_check():
  379.             return False
  380.         legal_moves = list(self.generate_legal_moves())
  381.         return len(legal_moves) == 0
  382.    
  383.     def is_insufficient_material(self):
  384.         return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  385.                 self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  386.             chess.popcount(self.occupied) <= 3
  387.         )
  388.  
  389.     def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
  390.         for move in self.generate_pseudo_legal_moves(from_mask, to_mask):
  391.             if self.is_legal(move):
  392.                 yield move
  393.  
  394.     def debug_amazons(self):
  395.         pass
  396.  
  397.     def debug_cyrils(self):
  398.         pass
  399.  
  400.     def debug_eves(self):
  401.         pass
  402.  
  403.     def piece_symbol(self, piece):
  404.         if piece is None:
  405.             return '.'
  406.         if piece.piece_type == AMAZON:
  407.             return 'A' if piece.color == chess.WHITE else 'a'
  408.         if piece.piece_type == CYRIL:
  409.             return 'C' if piece.color == chess.WHITE else 'c'
  410.         if piece.piece_type == EVE:
  411.             return 'E' if piece.color == chess.WHITE else 'e'
  412.         return piece.symbol()
  413.  
  414.     def piece_type_at(self, square):
  415.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  416.             return AMAZON
  417.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  418.             return CYRIL
  419.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  420.             return EVE
  421.         return super().piece_type_at(square)
  422.  
  423.     def color_at(self, square):
  424.         if self.amazons_white & chess.BB_SQUARES[square]:
  425.             return chess.WHITE
  426.         if self.amazons_black & chess.BB_SQUARES[square]:
  427.             return chess.BLACK
  428.         if self.cyrils_white & chess.BB_SQUARES[square]:
  429.             return chess.WHITE
  430.         if self.cyrils_black & chess.BB_SQUARES[square]:
  431.             return chess.BLACK
  432.         if self.eves_white & chess.BB_SQUARES[square]:
  433.             return chess.WHITE
  434.         if self.eves_black & chess.BB_SQUARES[square]:
  435.             return chess.BLACK
  436.         return super().color_at(square)
  437.  
  438.     @property
  439.     def legal_moves(self):
  440.         return list(self.generate_legal_moves())
  441.  
  442.     def __str__(self):
  443.         builder = []
  444.         for square in chess.SQUARES_180:
  445.             piece = self.piece_at(square)
  446.             symbol = self.piece_symbol(piece) if piece else '.'
  447.             builder.append(symbol)
  448.             if chess.square_file(square) == 7:
  449.                 if square != chess.H1:
  450.                     builder.append('\n')
  451.         return ''.join(builder)
  452.  
  453. def format_time(seconds):
  454.     hours, remainder = divmod(seconds, 3600)
  455.     minutes, seconds = divmod(remainder, 60)
  456.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  457.  
  458. def print_elapsed_time(stop_event, start_time):
  459.     while not stop_event.is_set():
  460.         elapsed_time = time.time() - start_time
  461.         print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
  462.         time.sleep(1)
  463.  
  464. def simplify_fen(fen):
  465.     return ' '.join(fen.split()[:4])
  466.  
  467. def calculate_optimal_moves(start_fen: str) -> Dict[str, Tuple[int, str]]:
  468.     print("Funkce calculate_optimal_moves byla zavolána")
  469.     print(f"Počáteční FEN: {start_fen}")
  470.    
  471.     board = CustomBoard(start_fen)
  472.     POZ = {1: simplify_fen(start_fen)}
  473.     AR = {simplify_fen(start_fen): {'used': 0, 'to_end': None, 'depth': 0, 'type': 'normal'}}
  474.     N = 1
  475.     M = 0
  476.  
  477.     start_time = time.time()
  478.     current_depth = 0
  479.     positions_at_depth = {0: 0}
  480.     depth_start_time = start_time
  481.  
  482.     stop_event = threading.Event()
  483.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event, start_time))
  484.     timer_thread.start()
  485.  
  486.     try:
  487.         print("Začínám generovat pozice...")
  488.         print("Počáteční pozice:")
  489.         print_board(start_fen)
  490.        
  491.         depth_1_positions = []  # Seznam pro ukládání pozic v hloubce 1
  492.  
  493.         # Generate all positions
  494.         while M < N:
  495.             M += 1
  496.             current_fen = POZ[M]
  497.             board.set_custom_fen(current_fen)
  498.             simplified_current_fen = simplify_fen(current_fen)
  499.             current_depth = AR[simplified_current_fen]['depth']
  500.  
  501.             if current_depth not in positions_at_depth:
  502.                 positions_at_depth[current_depth] = 0
  503.                 if current_depth > 0:
  504.                     depth_time = time.time() - depth_start_time
  505.                     total_time = time.time() - start_time
  506.                     print(f"\nHloubka {current_depth - 1}: {positions_at_depth[current_depth - 1]} pozic, "
  507.                           f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  508.                    
  509.                     if current_depth == 1:
  510.                         print("Všechny pozice v hloubce 1:")
  511.                         for pos in depth_1_positions:
  512.                             print_board(pos)
  513.                             print()
  514.                
  515.                 depth_start_time = time.time()
  516.  
  517.             positions_at_depth[current_depth] += 1
  518.  
  519.             if current_depth == 1:
  520.                 depth_1_positions.append(current_fen)
  521.  
  522.             if AR[simplified_current_fen]['used'] == 0:
  523.                 AR[simplified_current_fen]['used'] = 1
  524.                 legal_moves = list(board.legal_moves)
  525.                 for move in legal_moves:
  526.                     board.push(move)
  527.                     POZ2 = board.fen()
  528.                     simplified_POZ2 = simplify_fen(POZ2)
  529.                     if simplified_POZ2 not in AR:
  530.                         N += 1
  531.                         POZ[N] = simplified_POZ2
  532.                         AR[simplified_POZ2] = {'used': 0, 'to_end': None, 'depth': current_depth + 1, 'type': 'normal'}
  533.                     board.pop()
  534.    
  535.         # Print last depth
  536.         depth_time = time.time() - depth_start_time
  537.         total_time = time.time() - start_time
  538.         print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
  539.               f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  540.         print(f"Příklad pozice v hloubce {current_depth}:")
  541.         print_board(current_fen)
  542.  
  543.         print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
  544.  
  545.         # Initial evaluation
  546.         print("\nZačínám počáteční ohodnocení...")
  547.         F = 0
  548.         for i in range(1, N + 1):
  549.             current_fen = POZ[i]
  550.             board.set_custom_fen(current_fen)
  551.             simplified_current_fen = simplify_fen(current_fen)
  552.  
  553.             if board.is_checkmate():
  554.                 AR[simplified_current_fen]['to_end'] = -1000
  555.                 AR[simplified_current_fen]['type'] = 'checkmate'
  556.                 F += 1
  557.             elif board.is_stalemate():
  558.                 AR[simplified_current_fen]['to_end'] = 0
  559.                 AR[simplified_current_fen]['type'] = 'stalemate'
  560.             elif board.is_insufficient_material():
  561.                 AR[simplified_current_fen]['to_end'] = 0
  562.                 AR[simplified_current_fen]['type'] = 'drawing'
  563.             elif board.is_check():
  564.                 AR[simplified_current_fen]['to_end'] = 0
  565.                 AR[simplified_current_fen]['type'] = 'check'
  566.             else:
  567.                 AR[simplified_current_fen]['to_end'] = 0
  568.                 AR[simplified_current_fen]['type'] = 'normal'
  569.  
  570.         print(f"Počet pozic v matu je {F}")
  571.  
  572.         # Iterative evaluation
  573. # Iterative evaluation
  574. # Iterative evaluation
  575.         print("\nZačínám iterativní ohodnocení...")
  576.         uroven = 0
  577.         while True:
  578.             uroven += 1
  579.             level_start_time = time.time()
  580.             print(f"Výpočet v úrovni {uroven}")
  581.            
  582.             changed = False
  583.             current_level_positions = 0
  584.             for i in range(1, N + 1):
  585.                 current_fen = POZ[i]
  586.                 board.set_custom_fen(current_fen)
  587.                 simplified_current_fen = simplify_fen(current_fen)
  588.                 if AR[simplified_current_fen]['to_end'] is None or AR[simplified_current_fen]['to_end'] == 0:
  589.                     hod = -2000
  590.                     for move in board.legal_moves:
  591.                         board.push(move)
  592.                         POZ2 = board.fen()
  593.                         simplified_POZ2 = simplify_fen(POZ2)
  594.                         if simplified_POZ2 in AR and AR[simplified_POZ2]['to_end'] is not None:
  595.                             hod2 = -AR[simplified_POZ2]['to_end']
  596.                             if hod2 > hod:
  597.                                 hod = hod2
  598.                         board.pop()
  599.                    
  600.                     new_to_end = None
  601.                     if hod == 1001 - uroven:
  602.                         new_to_end = 1000 - uroven
  603.                         new_type = 'winning'
  604.                     elif hod == -1001 + uroven:
  605.                         new_to_end = -1000 + uroven
  606.                         new_type = 'losing'
  607.                     elif hod > -2000:  # Pokud byl nalezen alespoň jeden platný tah
  608.                         new_to_end = hod
  609.                         new_type = 'normal'
  610.                    
  611.                     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):
  612.                         AR[simplified_current_fen]['to_end'] = new_to_end
  613.                         AR[simplified_current_fen]['type'] = new_type
  614.                         changed = True
  615.                         current_level_positions += 1
  616.        
  617.             level_end_time = time.time()
  618.             total_elapsed_time = level_end_time - start_time
  619.             level_elapsed_time = level_end_time - level_start_time
  620.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  621.             print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  622.            
  623.             if not changed:
  624.                 print("Hodnocení ukončeno - žádné další změny.")
  625.                 break
  626.        
  627.         print(f"Celkem nalezeno {sum(1 for data in AR.values() if data['to_end'] is not None)} ohodnocených pozic")
  628.  
  629.  
  630.         print("\nVýpočet dokončen.")
  631.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  632.  
  633.     finally:
  634.         stop_event.set()
  635.         timer_thread.join()
  636.  
  637. # Helper function to print the board
  638. def print_board(fen):
  639.     board = CustomBoard(fen)
  640.     print(board)
  641.  
  642. # Najděte nejmenší kladnou hodnotu to_end ve všech FEN záznamech v AR
  643. def find_min_positive_value(AR):
  644.     min_positive_value = float('inf')
  645.     min_fen = None
  646.    
  647.     for fen, (value, type_pozice) in AR.items():
  648.         if value is not None and value > 0 and value < min_positive_value:
  649.             min_positive_value = value
  650.             min_fen = fen
  651.    
  652.     if min_positive_value == float('inf'):
  653.         print("Žádná kladná hodnota nebyla nalezena.")
  654.     else:
  655.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  656.  
  657. # Main execution
  658. # Main execution
  659. if __name__ == "__main__":
  660.     start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  661.  
  662.     start_fen = "7K/2P5/8/8/8/k7/8/8 w - - 0 1"
  663.    
  664.     AR = calculate_optimal_moves(start_fen)
  665.  
  666.     find_min_positive_value(AR)
  667.  
  668.     # print("\nVýsledky:")
  669.     # for hodnota in range(-996, -1001, -1):  # Generuje hodnoty -996, -997, -998, -999, -1000
  670.     #     for fen, (fen_hodnota, typ_pozice) in AR.items():
  671.     #         if fen_hodnota == hodnota:
  672.     #             print(f"FEN: {fen}")
  673.     #             print(f"Hodnota: {fen_hodnota}")
  674.     #             print(f"Typ pozice: {typ_pozice}")
  675.                
  676.     #             temp_board = CustomBoard(fen)
  677.                
  678.     #             if temp_board.is_checkmate():
  679.     #                 print("Stav: Mat")
  680.     #             elif temp_board.is_stalemate():
  681.     #                 print("Stav: Pat")
  682.     #             elif temp_board.is_insufficient_material():
  683.     #                 print("Stav: Nedostatečný materiál")
  684.     #             elif temp_board.is_check():
  685.     #                 print("Stav: Šach")
  686.     #             else:
  687.     #                 print("Stav: Normální pozice")
  688.      
  689.     #             print_board(fen)
  690.                
  691.     #             print()
  692.  
  693.     # Print optimal moves
  694. # Print optimal moves
  695.     current_fen = start_fen
  696.     simplified_current_fen = simplify_fen(current_fen)
  697.     optimal_moves = []
  698.    
  699.     while True:
  700.         board = CustomBoard(current_fen)
  701.         if board.is_checkmate():
  702.             print("Mat detekován!")
  703.             break
  704.        
  705.         # Opravená část
  706.         half_move_clock = current_fen.split()[-2]
  707.         if board.is_insufficient_material() or (half_move_clock != '-' and int(half_move_clock) >= 100):
  708.             if board.is_insufficient_material():
  709.                 print("Nedostatečný materiál detekován!")
  710.             else:
  711.                 print("Remíza pravidlem 50 tahů detekována!")
  712.             AR[simplified_current_fen] = (0, 'drawing')  # Aktualizujeme AR pro tuto pozici
  713.             break
  714.        
  715.         if simplified_current_fen not in AR:
  716.             print(f"Pozice {simplified_current_fen} není v AR.")
  717.             break
  718.        
  719.         current_value = AR[simplified_current_fen][0]
  720.        
  721.         if current_value == 0:
  722.             print("Remíza dosažena!")
  723.             break
  724.        
  725.         hod = -2000 if current_value > 0 else 2000
  726.         best_fen = None
  727.         for move in board.legal_moves:
  728.             board.push(move)
  729.             POZ2 = board.fen()
  730.             simplified_POZ2 = simplify_fen(POZ2)
  731.             if simplified_POZ2 in AR:
  732.                 hod2 = -AR[simplified_POZ2][0]
  733.                 if current_value > 0:  # Silnější hráč
  734.                     if hod2 > hod:
  735.                         hod = hod2
  736.                         best_fen = simplified_POZ2
  737.                 else:  # Slabší hráč
  738.                     if hod2 < hod:
  739.                         hod = hod2
  740.                         best_fen = simplified_POZ2
  741.             board.pop()
  742.        
  743.         if best_fen is None:
  744.             print("Žádný další tah nebyl nalezen.")
  745.             break
  746.         optimal_moves.append(best_fen)
  747.         current_fen = best_fen
  748.         simplified_current_fen = simplify_fen(current_fen)
  749.            
  750.    
  751.     print("\nOptimální tahy:")
  752.     for fen in reversed(optimal_moves):
  753.         print_board(fen)
  754.         hodnota, typ_pozice = AR[simplify_fen(fen)]
  755.         print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  756.         print(fen)
  757.         print("\n")
  758.        
  759.     print_board(simplified_current_fen1)
  760.     hodnota, typ_pozice = AR[simplified_current_fen1]
  761.     print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  762.     print(simplified_current_fen1)
  763.     print("\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement