Advertisement
max2201111

bez fenstring1 snad OK pro P s typ winning / loosing / drawing / repetition!

Jul 28th, 2024
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.80 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 = chess.QUEEN
  82.                 elif c == 'p' and chess.square_rank(square) == 0:
  83.                     piece_type = chess.QUEEN
  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.                 return {simplified_current_fen: (0, 'drawing')}  # End the function here
  564.             elif board.is_check():
  565.                 AR[simplified_current_fen]['to_end'] = 0
  566.                 AR[simplified_current_fen]['type'] = 'check'
  567.             else:
  568.                 AR[simplified_current_fen]['to_end'] = 0
  569.                 AR[simplified_current_fen]['type'] = 'normal'
  570.  
  571.         print(f"Počet pozic v matu je {F}")
  572.  
  573.         # Iterative evaluation
  574.         print("\nZačínám iterativní ohodnocení...")
  575.         uroven = 0
  576.         while F > 0:
  577.             uroven += 1
  578.             level_start_time = time.time()
  579.             print(f"Výpočet v úrovni {uroven}")
  580.            
  581.             F = 0
  582.             current_level_positions = 0
  583.             for i in range(1, N + 1):
  584.                 current_fen = POZ[i]
  585.                 board.set_custom_fen(current_fen)
  586.                 simplified_current_fen = simplify_fen(current_fen)
  587.                 if AR[simplified_current_fen]['to_end'] == 0:
  588.                     hod = -2000
  589.                     for move in board.legal_moves:
  590.                         board.push(move)
  591.                         POZ2 = board.fen()
  592.                         simplified_POZ2 = simplify_fen(POZ2)
  593.                         hod2 = -AR[simplified_POZ2]['to_end']
  594.                         if hod2 > hod:
  595.                             hod = hod2
  596.                         board.pop()
  597.                     if hod == 1001 - uroven:
  598.                         AR[simplified_current_fen]['to_end'] = 1000 - uroven
  599.                         AR[simplified_current_fen]['type'] = 'winning'
  600.                         F += 1
  601.                         current_level_positions += 1
  602.                     if hod == -1001 + uroven:
  603.                         AR[simplified_current_fen]['to_end'] = -1000 + uroven
  604.                         AR[simplified_current_fen]['type'] = 'losing'
  605.                         F += 1
  606.                         current_level_positions += 1
  607.             level_end_time = time.time()
  608.             total_elapsed_time = level_end_time - start_time
  609.             level_elapsed_time = level_end_time - level_start_time
  610.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  611.             print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  612.  
  613.         print(f"Nalezeno {F} pozic celkem")
  614.        
  615.         print("\nVýpočet dokončen.")
  616.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  617.  
  618.     finally:
  619.         stop_event.set()
  620.         timer_thread.join()
  621.        
  622. # Helper function to print the board
  623. def print_board(fen):
  624.     board = CustomBoard(fen)
  625.     print(board)
  626.  
  627. # Najděte nejmenší kladnou hodnotu to_end ve všech FEN záznamech v AR
  628. def find_min_positive_value(AR):
  629.     min_positive_value = float('inf')
  630.     min_fen = None
  631.    
  632.     for fen, (value, type_pozice) in AR.items():
  633.         if value > 0 and value < min_positive_value:
  634.             min_positive_value = value
  635.             min_fen = fen
  636.    
  637.     if min_positive_value == float('inf'):
  638.         print("Žádná kladná hodnota nebyla nalezena.")
  639.     else:
  640.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  641.  
  642. # Main execution
  643. if __name__ == "__main__":
  644.     start_fen = "7K/8/8/8/8/1k6/8/8 w - - 0 1"
  645.  
  646.     start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  647.    
  648.     AR = calculate_optimal_moves(start_fen)
  649.  
  650.     find_min_positive_value(AR)
  651.  
  652.     print("\nVýsledky:")
  653.     for fen, (hodnota, typ_pozice) in AR.items():
  654.         if False and (hodnota == 984 or hodnota == -980):
  655.             print(f"FEN: {fen}")
  656.             print(f"Hodnota: {hodnota}")
  657.             print(f"Typ pozice: {typ_pozice}")
  658.            
  659.             temp_board = CustomBoard(fen)
  660.            
  661.             if temp_board.is_checkmate():
  662.                 print("Stav: Mat")
  663.             elif temp_board.is_stalemate():
  664.                 print("Stav: Pat")
  665.             elif temp_board.is_insufficient_material():
  666.                 print("Stav: Nedostatečný materiál")
  667.             elif temp_board.is_check():
  668.                 print("Stav: Šach")
  669.             else:
  670.                 print("Stav: Normální pozice")
  671.  
  672.             print_board(fen)
  673.            
  674.             print()
  675.  
  676.     # Print optimal moves
  677. # Print optimal moves
  678. # Print optimal moves
  679. # Print optimal moves
  680.     current_fen = start_fen
  681.     simplified_current_fen = simplify_fen(current_fen)
  682.     simplified_current_fen1 = simplify_fen(current_fen)
  683.     optimal_moves = []
  684.    
  685.     while True:
  686.         board = CustomBoard(current_fen)
  687.         if board.is_checkmate():
  688.             print("Mat detekován!")
  689.             break
  690.         if board.is_insufficient_material() or int(current_fen.split()[-2]) >= 100:
  691.             if board.is_insufficient_material():
  692.                 print("Nedostatečný materiál detekován!")
  693.             else:
  694.                 print("Remíza pravidlem 50 tahů detekována!")
  695.             AR[simplified_current_fen] = (0, 'drawing')  # Aktualizujeme AR pro tuto pozici
  696.             break
  697.        
  698.         if simplified_current_fen not in AR:
  699.             print(f"Pozice {simplified_current_fen} není v AR.")
  700.             break
  701.        
  702.         current_value = AR[simplified_current_fen][0]
  703.        
  704.         if current_value == 0:
  705.             print("Remíza dosažena!")
  706.             break
  707.        
  708.         hod = -2000 if current_value > 0 else 2000
  709.         best_fen = None
  710.         for move in board.legal_moves:
  711.             board.push(move)
  712.             POZ2 = board.fen()
  713.             simplified_POZ2 = simplify_fen(POZ2)
  714.             if simplified_POZ2 in AR:
  715.                 hod2 = -AR[simplified_POZ2][0]
  716.                 if current_value > 0:  # Silnější hráč
  717.                     if hod2 > hod:
  718.                         hod = hod2
  719.                         best_fen = simplified_POZ2
  720.                 else:  # Slabší hráč
  721.                     if hod2 < hod:
  722.                         hod = hod2
  723.                         best_fen = simplified_POZ2
  724.             board.pop()
  725.        
  726.         if best_fen is None:
  727.             print("Žádný další tah nebyl nalezen.")
  728.             break
  729.         optimal_moves.append(best_fen)
  730.         current_fen = best_fen
  731.         simplified_current_fen = simplify_fen(current_fen)
  732.    
  733.     print("\nOptimální tahy:")
  734.     for fen in reversed(optimal_moves):
  735.         print_board(fen)
  736.         hodnota, typ_pozice = AR[simplify_fen(fen)]
  737.         print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  738.         print(fen)
  739.         print("\n")
  740.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement