Advertisement
max2201111

mozna remiza OK snad 2?

Aug 28th, 2024 (edited)
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.66 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. from collections import defaultdict
  8.  
  9. # Definice nových figur
  10. AMAZON = 7
  11. CYRIL = 8
  12. EVE = 9
  13.  
  14. # Rozšíření seznamu PIECE_SYMBOLS
  15. chess.PIECE_SYMBOLS.append('a')
  16. chess.PIECE_SYMBOLS.append('c')
  17. chess.PIECE_SYMBOLS.append('e')
  18.  
  19. class CustomBoard(chess.Board):
  20.     def __init__(self, fen=None):
  21.         self.amazons_white = chess.BB_EMPTY
  22.         self.amazons_black = chess.BB_EMPTY
  23.         self.cyrils_white = chess.BB_EMPTY
  24.         self.cyrils_black = chess.BB_EMPTY
  25.         self.eves_white = chess.BB_EMPTY
  26.         self.eves_black = chess.BB_EMPTY
  27.         super().__init__(None)
  28.         if fen:
  29.             self.set_custom_fen(fen)
  30.         self.debug_amazons()
  31.         self.debug_cyrils()
  32.         self.debug_eves()
  33.  
  34.     def clear_square(self, square):
  35.         super()._remove_piece_at(square)
  36.         self.amazons_white &= ~chess.BB_SQUARES[square]
  37.         self.amazons_black &= ~chess.BB_SQUARES[square]
  38.         self.cyrils_white &= ~chess.BB_SQUARES[square]
  39.         self.cyrils_black &= ~chess.BB_SQUARES[square]
  40.         self.eves_white &= ~chess.BB_SQUARES[square]
  41.         self.eves_black &= ~chess.BB_SQUARES[square]
  42.  
  43.     def set_custom_fen(self, fen):
  44.         parts = fen.split()
  45.         board_part = parts[0]
  46.    
  47.         self.clear()
  48.         self.amazons_white = chess.BB_EMPTY
  49.         self.amazons_black = chess.BB_EMPTY
  50.         self.cyrils_white = chess.BB_EMPTY
  51.         self.cyrils_black = chess.BB_EMPTY
  52.         self.eves_white = chess.BB_EMPTY
  53.         self.eves_black = chess.BB_EMPTY
  54.    
  55.         square = 56
  56.         for c in board_part:
  57.             if c == '/':
  58.                 square -= 16
  59.             elif c.isdigit():
  60.                 square += int(c)
  61.             else:
  62.                 color = chess.WHITE if c.isupper() else chess.BLACK
  63.                 if c.upper() == 'A':
  64.                     if color == chess.WHITE:
  65.                         self.amazons_white |= chess.BB_SQUARES[square]
  66.                     else:
  67.                         self.amazons_black |= chess.BB_SQUARES[square]
  68.                     piece_type = AMAZON
  69.                 elif c.upper() == 'C':
  70.                     if color == chess.WHITE:
  71.                         self.cyrils_white |= chess.BB_SQUARES[square]
  72.                     else:
  73.                         self.cyrils_black |= chess.BB_SQUARES[square]
  74.                     piece_type = CYRIL
  75.                 elif c.upper() == 'E':
  76.                     if color == chess.WHITE:
  77.                         self.eves_white |= chess.BB_SQUARES[square]
  78.                     else:
  79.                         self.eves_black |= chess.BB_SQUARES[square]
  80.                     piece_type = EVE
  81.                 elif c == 'P' and chess.square_rank(square) == 7:
  82.                     piece_type = AMAZON
  83.                     color = chess.WHITE
  84.                 elif c == 'p' and chess.square_rank(square) == 0:
  85.                     piece_type = AMAZON
  86.                     color = chess.BLACK
  87.                 else:
  88.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  89.                
  90.                 self._set_piece_at(square, piece_type, color)
  91.                 square += 1
  92.    
  93.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  94.         self.castling_rights = chess.BB_EMPTY
  95.         if '-' not in parts[2]:
  96.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  97.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  98.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  99.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  100.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  101.            
  102.  
  103.     def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
  104.         self.clear_square(square)
  105.         super()._set_piece_at(square, piece_type, color)
  106.         if piece_type == AMAZON:
  107.             if color == chess.WHITE:
  108.                 self.amazons_white |= chess.BB_SQUARES[square]
  109.             else:
  110.                 self.amazons_black |= chess.BB_SQUARES[square]
  111.         elif piece_type == CYRIL:
  112.             if color == chess.WHITE:
  113.                 self.cyrils_white |= chess.BB_SQUARES[square]
  114.             else:
  115.                 self.cyrils_black |= chess.BB_SQUARES[square]
  116.         elif piece_type == EVE:
  117.             if color == chess.WHITE:
  118.                 self.eves_white |= chess.BB_SQUARES[square]
  119.             else:
  120.                 self.eves_black |= chess.BB_SQUARES[square]
  121.  
  122.     def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
  123.         if self.amazons_white & chess.BB_SQUARES[square]:
  124.             return chess.Piece(AMAZON, chess.WHITE)
  125.         elif self.amazons_black & chess.BB_SQUARES[square]:
  126.             return chess.Piece(AMAZON, chess.BLACK)
  127.         elif self.cyrils_white & chess.BB_SQUARES[square]:
  128.             return chess.Piece(CYRIL, chess.WHITE)
  129.         elif self.cyrils_black & chess.BB_SQUARES[square]:
  130.             return chess.Piece(CYRIL, chess.BLACK)
  131.         elif self.eves_white & chess.BB_SQUARES[square]:
  132.             return chess.Piece(EVE, chess.WHITE)
  133.         elif self.eves_black & chess.BB_SQUARES[square]:
  134.             return chess.Piece(EVE, chess.BLACK)
  135.         return super().piece_at(square)
  136.  
  137.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  138.         our_pieces = self.occupied_co[self.turn]
  139.         if self.turn == chess.WHITE:
  140.             our_amazons = self.amazons_white
  141.             our_cyrils = self.cyrils_white
  142.             our_eves = self.eves_white
  143.         else:
  144.             our_amazons = self.amazons_black
  145.             our_cyrils = self.cyrils_black
  146.             our_eves = self.eves_black
  147.    
  148.         # Generování tahů pro amazonky
  149.         for from_square in chess.scan_forward(our_amazons & from_mask):
  150.             attacks = self.amazon_attacks(from_square)
  151.             valid_moves = attacks & ~our_pieces & to_mask
  152.             for to_square in chess.scan_forward(valid_moves):
  153.                 yield Move(from_square, to_square)
  154.    
  155.         # Generování tahů pro Cyrily
  156.         for from_square in chess.scan_forward(our_cyrils & from_mask):
  157.             attacks = self.cyril_attacks(from_square)
  158.             valid_moves = attacks & ~our_pieces & to_mask
  159.             for to_square in chess.scan_forward(valid_moves):
  160.                 yield Move(from_square, to_square)
  161.    
  162.         # Generování tahů pro Evy
  163.         for from_square in chess.scan_forward(our_eves & from_mask):
  164.             attacks = self.eve_attacks(from_square)
  165.             valid_moves = attacks & ~our_pieces & to_mask
  166.             for to_square in chess.scan_forward(valid_moves):
  167.                 yield Move(from_square, to_square)
  168.    
  169.         # Generování tahů pro standardní figury
  170.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  171.             piece = self.piece_at(move.from_square)
  172.             if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
  173.                 yield move
  174.  
  175.     def queen_attacks(self, square):
  176.         return self.bishop_attacks(square) | self.rook_attacks(square)
  177.  
  178.     def bishop_attacks(self, square):
  179.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  180.  
  181.     def rook_attacks(self, square):
  182.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  183.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  184.  
  185.     def amazon_attacks(self, square):
  186.         return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  187.  
  188.     def cyril_attacks(self, square):
  189.         return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS[quare]
  190.  
  191.     def eve_attacks(self, square):
  192.         return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  193.  
  194.     def is_pseudo_legal(self, move):
  195.         from_square = move.from_square
  196.         to_square = move.to_square
  197.         piece = self.piece_at(from_square)
  198.    
  199.         if not piece or piece.color != self.turn:
  200.             return False
  201.    
  202.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  203.             return False
  204.    
  205.         if self.is_castling(move):
  206.             return True
  207.    
  208.         if piece.piece_type == AMAZON:
  209.             return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
  210.         elif piece.piece_type == CYRIL:
  211.             return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
  212.         elif piece.piece_type == EVE:
  213.             return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
  214.         else:
  215.             return super().is_pseudo_legal(move)
  216.  
  217.     def is_legal(self, move):
  218.         if not self.is_pseudo_legal(move):
  219.             return False
  220.    
  221.         from_square = move.from_square
  222.         to_square = move.to_square
  223.         piece = self.piece_at(from_square)
  224.         captured_piece = self.piece_at(to_square)
  225.    
  226.         # Kontrola pro všechny figury: nelze brát figuru stejné barvy
  227.         if captured_piece and captured_piece.color == piece.color:
  228.             return False
  229.    
  230.         # Dočasně provést tah
  231.         self.clear_square(from_square)
  232.         self._set_piece_at(to_square, piece.piece_type, piece.color)
  233.    
  234.         # Najít pozici krále
  235.         king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
  236.    
  237.         # Kontrola, zda je král v šachu po tahu
  238.         is_check = self._is_attacked_by(not self.turn, king_square) if king_square is not None else False
  239.    
  240.         # Vrátit pozici do původního stavu
  241.         self.clear_square(to_square)
  242.         self._set_piece_at(from_square, piece.piece_type, piece.color)
  243.         if captured_piece:
  244.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  245.    
  246.         return not is_check
  247.        
  248.  
  249.     def _is_attacked_by(self, color, square):
  250.         attackers = self.attackers(color, square)
  251.         return bool(attackers)
  252.  
  253.     def attackers(self, color: Color, square: chess.Square) -> Bitboard:
  254.         if square is None:
  255.             return chess.BB_EMPTY
  256.    
  257.         attackers = chess.BB_EMPTY
  258.         occupied = self.occupied
  259.         occupied_co = self.occupied_co[color]
  260.    
  261.         # Jezdci
  262.         attackers |= chess.BB_KNIGHT_ATTACKS[square] & self.knights & occupied_co
  263.    
  264.         # Král
  265.         attackers |= chess.BB_KING_ATTACKS[square] & self.kings & occupied_co
  266.    
  267.         # Pěšci
  268.         if color == chess.WHITE:
  269.             attackers |= chess.BB_PAWN_ATTACKS[chess.BLACK][square] & self.pawns & occupied_co
  270.         else:
  271.             attackers |= chess.BB_PAWN_ATTACKS[chess.WHITE][square] & self.pawns & occupied_co
  272.    
  273.         # Střelcové útoky (včetně dam a amazonek)
  274.         bishop_attacks = chess.BB_DIAG_ATTACKS[square][occupied & chess.BB_DIAG_MASKS[square]]
  275.         attackers |= bishop_attacks & ((self.bishops | self.queens) & occupied_co)
  276.    
  277.         # Věžové útoky (včetně dam, amazonek a cyrilů)
  278.         rook_attacks = (
  279.             chess.BB_RANK_ATTACKS[square][occupied & chess.BB_RANK_MASKS[square]] |
  280.             chess.BB_FILE_ATTACKS[square][occupied & chess.BB_FILE_MASKS[square]]
  281.         )
  282.         attackers |= rook_attacks & ((self.rooks | self.queens) & occupied_co)
  283.    
  284.         # Amazonky (Dáma + Jezdec)
  285.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  286.         amazon_attacks = bishop_attacks | rook_attacks | chess.BB_KNIGHT_ATTACKS[square]
  287.         attackers |= amazon_attacks & amazons
  288.    
  289.         # Cyrilové (Věž + Jezdec)
  290.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  291.         cyril_attacks = rook_attacks | chess.BB_KNIGHT_ATTACKS[square]
  292.         attackers |= cyril_attacks & cyrils
  293.    
  294.         # Evy (Střelec + Jezdec)
  295.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  296.         eve_attacks = bishop_attacks | chess.BB_KNIGHT_ATTACKS[square]
  297.         attackers |= eve_attacks & eves
  298.    
  299.         return attackers
  300.        
  301.     def push(self, move):
  302.         if not self.is_legal(move):
  303.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  304.  
  305.         piece = self.piece_at(move.from_square)
  306.         captured_piece = self.piece_at(move.to_square)
  307.  
  308.         self.clear_square(move.from_square)
  309.         self.clear_square(move.to_square)
  310.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  311.  
  312.         self.turn = not self.turn
  313.  
  314.         self.move_stack.append((move, captured_piece))
  315.  
  316.     def pop(self):
  317.         if not self.move_stack:
  318.             return None
  319.  
  320.         move, captured_piece = self.move_stack.pop()
  321.  
  322.         piece = self.piece_at(move.to_square)
  323.        
  324.         self.clear_square(move.from_square)
  325.         self.clear_square(move.to_square)
  326.  
  327.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  328.  
  329.         if captured_piece:
  330.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  331.  
  332.         self.turn = not self.turn
  333.  
  334.         return move
  335.  
  336.     def is_check(self):
  337.         king_square = self.king(self.turn)
  338.         if king_square is None:
  339.             return False
  340.         is_check = self._is_attacked_by(not self.turn, king_square)
  341.         return is_check
  342.  
  343.     def is_checkmate(self):
  344.         if not self.is_check():
  345.             return False
  346.         legal_moves = list(self.generate_legal_moves())
  347.         return len(legal_moves) == 0
  348.  
  349.     def is_game_over(self):
  350.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  351.  
  352.     def is_stalemate(self):
  353.         if self.is_check():
  354.             return False
  355.         legal_moves = list(self.generate_legal_moves())
  356.         return len(legal_moves) == 0
  357.    
  358.     def is_insufficient_material(self):
  359.         return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  360.                 self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  361.             chess.popcount(self.occupied) <= 3
  362.         )
  363.  
  364.     def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
  365.         for move in self.generate_pseudo_legal_moves(from_mask, to_mask):
  366.             if self.is_legal(move):
  367.                 yield move
  368.  
  369.     def debug_amazons(self):
  370.         pass
  371.  
  372.     def debug_cyrils(self):
  373.         pass
  374.  
  375.     def debug_eves(self):
  376.         pass
  377.  
  378.     def piece_symbol(self, piece):
  379.         if piece is None:
  380.             return '.'
  381.         if piece.piece_type == AMAZON:
  382.             return 'A' if piece.color == chess.WHITE else 'a'
  383.         if piece.piece_type == CYRIL:
  384.             return 'C' if piece.color == chess.WHITE else 'c'
  385.         if piece.piece_type == EVE:
  386.             return 'E' if piece.color == chess.WHITE else 'e'
  387.         return piece.symbol()
  388.  
  389.     def piece_type_at(self, square):
  390.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  391.             return AMAZON
  392.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  393.             return CYRIL
  394.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  395.             return EVE
  396.         return super().piece_type_at(square)
  397.  
  398.     def color_at(self, square):
  399.         if self.amazons_white & chess.BB_SQUARES[square]:
  400.             return chess.WHITE
  401.         if self.amazons_black & chess.BB_SQUARES[square]:
  402.             return chess.BLACK
  403.         if self.cyrils_white & chess.BB_SQUARES[square]:
  404.             return chess.WHITE
  405.         if self.cyrils_black & chess.BB_SQUARES[square]:
  406.             return chess.BLACK
  407.         if self.eves_white & chess.BB_SQUARES[square]:
  408.             return chess.WHITE
  409.         if self.eves_black & chess.BB_SQUARES[square]:
  410.             return chess.BLACK
  411.         return super().color_at(square)
  412.  
  413.     @property
  414.     def legal_moves(self):
  415.         return list(self.generate_legal_moves())
  416.  
  417.     def __str__(self):
  418.         builder = []
  419.         for square in chess.SQUARES_180:
  420.             piece = self.piece_at(square)
  421.             symbol = self.piece_symbol(piece) if piece else '.'
  422.             builder.append(symbol)
  423.             if chess.square_file(square) == 7:
  424.                 if square != chess.H1:
  425.                     builder.append('\n')
  426.         return ''.join(builder)
  427.  
  428. def format_time(seconds):
  429.     hours, remainder = divmod(seconds, 3600)
  430.     minutes, seconds = divmod(remainder, 60)
  431.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  432.  
  433. def print_elapsed_time(stop_event, start_time):
  434.     while not stop_event.is_set():
  435.         elapsed_time = time.time() - start_time
  436.         print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
  437.         time.sleep(1)
  438.  
  439. def simplify_fen(fen):
  440.     return ' '.join(fen.split()[:4])
  441.  
  442.  
  443. def calculate_optimal_moves(start_fen: str) -> Dict[str, Tuple[int, str]]:
  444.     print("Funkce calculate_optimal_moves byla zavolána")
  445.     print(f"Počáteční FEN: {start_fen}")
  446.  
  447.     if not CustomBoard(start_fen).is_valid():
  448.         raise ValueError("Neplatný FEN")
  449.  
  450.     board = CustomBoard(start_fen)
  451.     POZ = {1: board.fen()}
  452.     AR = defaultdict(lambda: {'used': 0, 'to_end': None, 'depth': 0, 'type': 'normal', 'position_count': defaultdict(int)})
  453.     AR[board.fen()]['position_count'][board.epd()] = 1
  454.     N = 1
  455.     M = 0
  456.  
  457.     start_time = time.time()
  458.     current_depth = 0
  459.     positions_at_depth = defaultdict(int)
  460.     depth_start_time = start_time
  461.  
  462.     stop_event = threading.Event()
  463.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event, start_time))
  464.     timer_thread.start()
  465.  
  466.     try:
  467.         print("Začínám generovat pozice...")
  468.         print("Počáteční pozice:")
  469.         print_board(start_fen)
  470.  
  471.         depth_1_positions = []  # Seznam pro ukládání pozic v hloubce 1
  472.  
  473.         # Generate all positions
  474.         while M < N:
  475.             M += 1
  476.             current_fen = POZ[M]
  477.             board.set_fen(current_fen)
  478.             current_depth = AR[current_fen]['depth']
  479.  
  480.             if positions_at_depth[current_depth] == 0:
  481.                 if current_depth > 0:
  482.                     depth_time = time.time() - depth_start_time
  483.                     total_time = time.time() - start_time
  484.                     print(f"\nHloubka {current_depth - 1}: {positions_at_depth[current_depth - 1]} pozic, "
  485.                           f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  486.  
  487.                     if current_depth == 1:
  488.                         print("Všechny pozice v hloubce 1:")
  489.                         for pos in depth_1_positions:
  490.                             print_board(pos)
  491.                             print()
  492.  
  493.                 depth_start_time = time.time()
  494.  
  495.             positions_at_depth[current_depth] += 1
  496.  
  497.             if current_depth == 1:
  498.                 depth_1_positions.append(current_fen)
  499.  
  500.             if AR[current_fen]['used'] == 0:
  501.                 AR[current_fen]['used'] = 1
  502.                 for move in board.legal_moves:
  503.                     board.push(move)
  504.                     new_fen = board.fen()
  505.                     new_epd = board.epd()
  506.                     AR[new_fen]['position_count'][new_epd] += 1
  507.                     if new_fen not in POZ.values():
  508.                         N += 1
  509.                         POZ[N] = new_fen
  510.                         AR[new_fen]['depth'] = current_depth + 1
  511.                     board.pop()
  512.  
  513.             if stop_event.is_set():
  514.                 print("Výpočet byl přerušen uživatelem.")
  515.                 return {}
  516.  
  517.         # Print last depth
  518.         depth_time = time.time() - depth_start_time
  519.         total_time = time.time() - start_time
  520.         print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
  521.               f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  522.         print(f"Příklad pozice v hloubce {current_depth}:")
  523.         print_board(current_fen)
  524.  
  525.         print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
  526.  
  527.         # Initial evaluation
  528.         print("\nZačínám počáteční ohodnocení...")
  529.         F_checkmate = F_stalemate = F_drawing = F_check = F_normal = 0
  530.         for fen in POZ.values():
  531.             board.set_fen(fen)
  532.             if board.is_checkmate():
  533.                 AR[fen]['to_end'] = -1000 if board.turn == chess.WHITE else 1000
  534.                 AR[fen]['type'] = 'checkmate'
  535.                 F_checkmate += 1
  536.             elif board.is_stalemate():
  537.                 AR[fen]['to_end'] = 0
  538.                 AR[fen]['type'] = 'stalemate'
  539.                 F_stalemate += 1
  540.             elif max(AR[fen]['position_count'].values()) >= 3:
  541.                 AR[fen]['to_end'] = 0
  542.                 AR[fen]['type'] = 'threefold_repetition'
  543.                 F_drawing += 1
  544.             elif board.halfmove_clock >= 100:
  545.                 AR[fen]['to_end'] = 0
  546.                 AR[fen]['type'] = 'fifty_move_rule'
  547.                 F_drawing += 1
  548.             elif board.is_insufficient_material():
  549.                 AR[fen]['to_end'] = 0
  550.                 AR[fen]['type'] = 'insufficient_material'
  551.                 F_drawing += 1
  552.             elif board.is_check():
  553.                 AR[fen]['type'] = 'check'
  554.                 F_check += 1
  555.             else:
  556.                 AR[fen]['type'] = 'normal'
  557.                 F_normal += 1
  558.  
  559.         print(f"Počet pozic v matu je {F_checkmate}")
  560.         print(f"Počet pozic v patu je {F_stalemate}")
  561.         print(f"Počet pozic v remíze je {F_drawing}")
  562.         print(f"Počet pozic v šachu je {F_check}")
  563.         print(f"Počet normálních pozic je {F_normal}")
  564.  
  565.         print("\nZačínám iterativní ohodnocení...")
  566.         uroven = 0
  567.         while True:
  568.             uroven += 1
  569.             level_start_time = time.time()
  570.             print(f"Výpočet v úrovni {uroven}")
  571.  
  572.             changed = False
  573.             current_level_positions = 0
  574.             for fen in POZ.values():
  575.                 if AR[fen]['to_end'] is None or (AR[fen]['to_end'] == 0 and AR[fen]['type'] == 'normal'):
  576.                     board.set_fen(fen)
  577.                     hod = float('-inf') if board.turn == chess.WHITE else float('inf')
  578.                     for move in board.legal_moves:
  579.                         board.push(move)
  580.                         new_fen = board.fen()
  581.                         if AR[new_fen]['to_end'] is not None:
  582.                             hod2 = -AR[new_fen]['to_end']
  583.                             if board.turn == chess.WHITE:
  584.                                 hod = max(hod, hod2)
  585.                             else:
  586.                                 hod = min(hod, hod2)
  587.                         board.pop()
  588.  
  589.                     if hod == 1001 - uroven:
  590.                         new_to_end = 1000 - uroven
  591.                         new_type = 'winning'
  592.                     elif hod == -1001 + uroven:
  593.                         new_to_end = -1000 + uroven
  594.                         new_type = 'losing'
  595.                     elif hod == 0:
  596.                         new_to_end = 0
  597.                         new_type = 'drawing'
  598.                     elif hod != float('-inf') and hod != float('inf'):
  599.                         new_to_end = hod
  600.                         new_type = 'normal'
  601.                     else:
  602.                         new_to_end = 0
  603.                         new_type = 'drawing'
  604.  
  605.                     if AR[fen]['to_end'] != new_to_end or AR[fen]['type'] != new_type:
  606.                         AR[fen]['to_end'] = new_to_end
  607.                         AR[fen]['type'] = new_type
  608.                         changed = True
  609.                         current_level_positions += 1
  610.  
  611.             level_end_time = time.time()
  612.             total_elapsed_time = level_end_time - start_time
  613.             level_elapsed_time = level_end_time - level_start_time
  614.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  615.             print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
  616.  
  617.             if not changed:
  618.                 print("Hodnocení ukončeno - žádné další změny.")
  619.                 break
  620.  
  621.             if stop_event.is_set():
  622.                 print("Výpočet byl přerušen uživatelem.")
  623.                 return {}
  624.  
  625.         print(f"Celkem nalezeno {sum(1 for data in AR.values() if data['to_end'] is not None)} ohodnocených pozic")
  626.  
  627.         print("\nVýpočet dokončen.")
  628.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  629.  
  630.     finally:
  631.         stop_event.set()
  632.         timer_thread.join()
  633.  
  634. def print_board(fen):
  635.     board = chess.Board(fen)
  636.     print(board)
  637.  
  638. def find_min_positive_value(AR):
  639.     min_positive_value = float('inf')
  640.     min_fen = None
  641.  
  642.     for fen, (value, type_pozice) in AR.items():
  643.         if value is not None and value > 0 and value < min_positive_value:
  644.             min_positive_value = value
  645.             min_fen = fen
  646.  
  647.     if min_positive_value == float('inf'):
  648.         print("Žádná kladná hodnota nebyla nalezena.")
  649.     else:
  650.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  651.  
  652. def format_time(seconds):
  653.     hours, remainder = divmod(seconds, 3600)
  654.     minutes, seconds = divmod(remainder, 60)
  655.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  656.  
  657. def print_elapsed_time(stop_event, start_time):
  658.     while not stop_event.is_set():
  659.         elapsed_time = time.time() - start_time
  660.         print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
  661.         time.sleep(1)
  662.  
  663. if __name__ == "__main__":
  664.     start_fen = "8/5R2/8/8/2K5/8/kr6/8 w - - 0 1"
  665.    
  666.     try:
  667.         AR = calculate_optimal_moves(start_fen)
  668.     except KeyboardInterrupt:
  669.         print("\nVýpočet byl přerušen uživatelem.")
  670.         exit()
  671.  
  672.     find_min_positive_value(AR)
  673.  
  674.     simplified_start_fen = start_fen
  675.     if simplified_start_fen in AR:
  676.         value, position_type = AR[simplified_start_fen]
  677.         print(f"Počáteční pozice: Hodnota = {value}, Typ = {position_type}")
  678.         if value == 0:
  679.             print("Pozice je vyhodnocena jako remíza.")
  680.         elif value > 0:
  681.             print("Bílý má výhodu.")
  682.         else:
  683.             print("Černý má výhodu.")
  684.     else:
  685.         print("Počáteční pozice nebyla vyhodnocena.")
  686.  
  687.     current_fen = start_fen
  688.     optimal_moves = []
  689.  
  690.     while True:
  691.         board = chess.Board(current_fen)
  692.         if board.is_checkmate():
  693.             print("Mat detekován!")
  694.             break
  695.  
  696.         half_move_clock = int(current_fen.split()[-2])
  697.         if board.is_stalemate() or board.is_insufficient_material() or half_move_clock >= 100:
  698.             if board.is_stalemate():
  699.                 print("Pat detekován!")
  700.             elif board.is_insufficient_material():
  701.                 print("Nedostatečný materiál detekován!")
  702.             else:
  703.                 print("Remíza pravidlem 50 tahů detekována!")
  704.             AR[current_fen] = (0, 'drawing')
  705.             break
  706.  
  707.         if current_fen not in AR:
  708.             print(f"Pozice {current_fen} není v AR.")
  709.             break
  710.  
  711.         current_value, current_type = AR[current_fen]
  712.  
  713.         if current_type == 'drawing':
  714.             print("Remíza dosažena!")
  715.             break
  716.  
  717.         best_move = None
  718.         best_value = float('-inf') if current_value > 0 else float('inf')
  719.         for move in board.legal_moves:
  720.             board.push(move)
  721.             new_fen = board.fen()
  722.             board.pop()
  723.             if new_fen in AR:
  724.                 move_value = -AR[new_fen][0]
  725.                 if (current_value > 0 and move_value > best_value) or (current_value <= 0 and move_value < best_value):
  726.                     best_value = move_value
  727.                     best_move = move
  728.  
  729.         if best_move is None:
  730.             print("Žádný další tah nebyl nalezen.")
  731.             break
  732.        
  733.         board.push(best_move)
  734.         optimal_moves.append((current_fen, best_move, board.fen()))
  735.         current_fen = board.fen()
  736.  
  737.     print("\nOptimální tahy:")
  738.     for from_fen, move, to_fen in optimal_moves:
  739.         print_board(from_fen)
  740.         print(f"Tah: {move}")
  741.         hodnota, typ_pozice = AR[to_fen]
  742.         print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  743.         print(to_fen)
  744.         print("\n")
  745.  
  746.     print_board(start_fen)
  747.     hodnota, typ_pozice = AR[start_fen]
  748.     print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  749.     print(start_fen)
  750.     print("\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement