Advertisement
max2201111

mozna remiza OK snad 4?

Aug 29th, 2024
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.39 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(f"Počáteční FEN: {start_fen}")
  445.     if not CustomBoard(start_fen).is_valid():
  446.         raise ValueError("Neplatný FEN")
  447.  
  448.     board = CustomBoard(start_fen)
  449.     POZ = {1: board.fen()}
  450.     AR = defaultdict(lambda: {'used': 0, 'to_end': None, 'depth': 0, 'type': 'normal', 'position_count': defaultdict(int)})
  451.     AR[board.fen()]['position_count'][board.epd()] = 1
  452.     N = 1
  453.     M = 0
  454.  
  455.     transposition_table = {}
  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.         # Generate all positions
  472.         while M < N:
  473.             M += 1
  474.             current_fen = POZ[M]
  475.             board.set_fen(current_fen)
  476.             current_depth = AR[current_fen]['depth']
  477.  
  478.             if positions_at_depth[current_depth] == 0:
  479.                 if current_depth > 0:
  480.                     depth_time = time.time() - depth_start_time
  481.                     total_time = time.time() - start_time
  482.                     print(f"\nHloubka {current_depth - 1}: {positions_at_depth[current_depth - 1]} pozic, "
  483.                           f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  484.                 depth_start_time = time.time()
  485.  
  486.             positions_at_depth[current_depth] += 1
  487.  
  488.             if AR[current_fen]['used'] == 0:
  489.                 AR[current_fen]['used'] = 1
  490.                 for move in board.legal_moves:
  491.                     board.push(move)
  492.                     new_fen = board.fen()
  493.                     new_epd = board.epd()
  494.                     AR[new_fen]['position_count'][new_epd] += 1
  495.                     if new_fen not in POZ.values():
  496.                         N += 1
  497.                         POZ[N] = new_fen
  498.                         AR[new_fen]['depth'] = current_depth + 1
  499.                     board.pop()
  500.  
  501.             if stop_event.is_set():
  502.                 print("Výpočet byl přerušen uživatelem.")
  503.                 return {}
  504.  
  505.         # Print last depth
  506.         depth_time = time.time() - depth_start_time
  507.         total_time = time.time() - start_time
  508.         print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
  509.               f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
  510.  
  511.         print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
  512.  
  513.         # Initial evaluation
  514.         print("\nZačínám počáteční ohodnocení...")
  515.         F_checkmate = F_stalemate = F_drawing = F_check = F_normal = 0
  516.         for fen in POZ.values():
  517.             board.set_fen(fen)
  518.             if board.is_checkmate():
  519.                 AR[fen]['to_end'] = -1000 if board.turn == chess.WHITE else 1000
  520.                 AR[fen]['type'] = 'checkmate'
  521.                 F_checkmate += 1
  522.             elif board.is_stalemate():
  523.                 AR[fen]['to_end'] = 0
  524.                 AR[fen]['type'] = 'stalemate'
  525.                 F_stalemate += 1
  526.             elif max(AR[fen]['position_count'].values()) >= 3:
  527.                 AR[fen]['to_end'] = 0
  528.                 AR[fen]['type'] = 'threefold_repetition'
  529.                 F_drawing += 1
  530.             elif board.halfmove_clock >= 100:
  531.                 AR[fen]['to_end'] = 0
  532.                 AR[fen]['type'] = 'fifty_move_rule'
  533.                 F_drawing += 1
  534.             elif board.is_insufficient_material():
  535.                 AR[fen]['to_end'] = 0
  536.                 AR[fen]['type'] = 'insufficient_material'
  537.                 F_drawing += 1
  538.             elif board.is_check():
  539.                 AR[fen]['type'] = 'check'
  540.                 F_check += 1
  541.             else:
  542.                 AR[fen]['type'] = 'normal'
  543.                 F_normal += 1
  544.  
  545.         print(f"Počet pozic v matu je {F_checkmate}")
  546.         print(f"Počet pozic v patu je {F_stalemate}")
  547.         print(f"Počet pozic v remíze je {F_drawing}")
  548.         print(f"Počet pozic v šachu je {F_check}")
  549.         print(f"Počet normálních pozic je {F_normal}")
  550.  
  551.         print("\nZačínám iterativní ohodnocení...")
  552.         uroven = 0
  553.         while True:
  554.             uroven += 1
  555.             level_start_time = time.time()
  556.             print(f"Výpočet v úrovni {uroven}")
  557.  
  558.             changed = False
  559.             current_level_positions = 0
  560.             for fen in POZ.values():
  561.                 if fen in transposition_table:
  562.                     AR[fen]['to_end'], AR[fen]['type'] = transposition_table[fen]
  563.                     continue
  564.  
  565.                 if AR[fen]['to_end'] is None or (AR[fen]['to_end'] == 0 and AR[fen]['type'] == 'normal'):
  566.                     board.set_fen(fen)
  567.                     hod = float('-inf') if board.turn == chess.WHITE else float('inf')
  568.                     for move in board.legal_moves:
  569.                         board.push(move)
  570.                         new_fen = board.fen()
  571.                         if new_fen in transposition_table:
  572.                             hod2 = -transposition_table[new_fen][0]
  573.                         elif AR[new_fen]['to_end'] is not None:
  574.                             hod2 = -AR[new_fen]['to_end']
  575.                         else:
  576.                             board.pop()
  577.                             continue
  578.                         if board.turn == chess.WHITE:
  579.                             hod = max(hod, hod2)
  580.                         else:
  581.                             hod = min(hod, hod2)
  582.                         board.pop()
  583.  
  584.                     if hod == 1001 - uroven:
  585.                         new_to_end = 1000 - uroven
  586.                         new_type = 'winning'
  587.                     elif hod == -1001 + uroven:
  588.                         new_to_end = -1000 + uroven
  589.                         new_type = 'losing'
  590.                     elif hod == 0:
  591.                         new_to_end = 0
  592.                         new_type = 'drawing'
  593.                     elif hod != float('-inf') and hod != float('inf'):
  594.                         new_to_end = hod
  595.                         new_type = 'normal'
  596.                     else:
  597.                         new_to_end = 0
  598.                         new_type = 'drawing'
  599.  
  600.                     if AR[fen]['to_end'] != new_to_end or AR[fen]['type'] != new_type:
  601.                         AR[fen]['to_end'] = new_to_end
  602.                         AR[fen]['type'] = new_type
  603.                         transposition_table[fen] = (new_to_end, new_type)
  604.                         changed = True
  605.                         current_level_positions += 1
  606.  
  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.             if not changed:
  614.                 print("Hodnocení ukončeno - žádné další změny.")
  615.                 break
  616.  
  617.             if stop_event.is_set():
  618.                 print("Výpočet byl přerušen uživatelem.")
  619.                 return {}
  620.  
  621.         print(f"Celkem nalezeno {sum(1 for data in AR.values() if data['to_end'] is not None)} ohodnocených pozic")
  622.  
  623.         print("\nVýpočet dokončen.")
  624.         return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
  625.  
  626.     finally:
  627.         stop_event.set()
  628.         timer_thread.join()
  629.        
  630. def print_board(fen):
  631.     board = chess.Board(fen)
  632.     print(board)
  633.  
  634. def find_min_positive_value(AR):
  635.     min_positive_value = float('inf')
  636.     min_fen = None
  637.  
  638.     for fen, (value, type_pozice) in AR.items():
  639.         if value is not None and value > 0 and value < min_positive_value:
  640.             min_positive_value = value
  641.             min_fen = fen
  642.  
  643.     if min_positive_value == float('inf'):
  644.         print("Žádná kladná hodnota nebyla nalezena.")
  645.     else:
  646.         print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
  647.  
  648. def format_time(seconds):
  649.     hours, remainder = divmod(seconds, 3600)
  650.     minutes, seconds = divmod(remainder, 60)
  651.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  652.  
  653. def print_elapsed_time(stop_event, start_time):
  654.     while not stop_event.is_set():
  655.         elapsed_time = time.time() - start_time
  656.         print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
  657.         time.sleep(1)
  658.  
  659. if __name__ == "__main__":
  660.     start_fen = "8/5R2/8/8/2K5/8/kr6/8 w - - 0 1"
  661.  
  662.     try:
  663.         AR = calculate_optimal_moves(start_fen)
  664.     except KeyboardInterrupt:
  665.         print("\nVýpočet byl přerušen uživatelem.")
  666.         exit()
  667.  
  668.     find_min_positive_value(AR)
  669.  
  670.     simplified_start_fen = start_fen
  671.     if simplified_start_fen in AR:
  672.         value, position_type = AR[simplified_start_fen]
  673.         print(f"Počáteční pozice: Hodnota = {value}, Typ = {position_type}")
  674.         if value == 0:
  675.             print("Pozice je vyhodnocena jako remíza.")
  676.         elif value > 0:
  677.             print("Bílý má výhodu.")
  678.         else:
  679.             print("Černý má výhodu.")
  680.     else:
  681.         print("Počáteční pozice nebyla vyhodnocena.")
  682.  
  683.     current_fen = start_fen
  684.     optimal_moves = []
  685.  
  686.     while True:
  687.         board = CustomBoard(current_fen)
  688.         if board.is_game_over():
  689.             break
  690.  
  691.         if current_fen not in AR:
  692.             print(f"Pozice {current_fen} není v AR.")
  693.             break
  694.  
  695.         current_value, current_type = AR[current_fen]
  696.  
  697.         best_move = None
  698.         best_value = float('-inf') if board.turn == chess.WHITE else float('inf')
  699.         for move in board.legal_moves:
  700.             board.push(move)
  701.             new_fen = board.fen()
  702.             board.pop()
  703.             if new_fen in AR:
  704.                 move_value = AR[new_fen][0]
  705.                 if (board.turn == chess.WHITE and move_value > best_value) or (board.turn == chess.BLACK and move_value < best_value):
  706.                     best_value = move_value
  707.                     best_move = move
  708.  
  709.         if best_move is None:
  710.             print("Žádný další tah nebyl nalezen.")
  711.             break
  712.  
  713.         board.push(best_move)
  714.         optimal_moves.append((current_fen, best_move, board.fen()))
  715.         current_fen = board.fen()
  716.  
  717.     print("\nOptimální tahy:")
  718.     print("Počáteční pozice:")
  719.     print_board(start_fen)
  720.     hodnota, typ_pozice = AR[start_fen]
  721.     print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  722.     print(start_fen)
  723.     print("\n")
  724.  
  725.     for from_fen, move, to_fen in reversed(optimal_moves):
  726.         print_board(from_fen)
  727.         print(f"Tah: {move}")
  728.         hodnota, typ_pozice = AR[to_fen]
  729.         print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  730.         print(to_fen)
  731.         print("\n")
  732.  
  733.     if optimal_moves:
  734.         print("Konečná pozice:")
  735.         final_fen = optimal_moves[-1][2]  # Poslední 'to_fen'
  736.         print_board(final_fen)
  737.         hodnota, typ_pozice = AR[final_fen]
  738.         print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
  739.         print(final_fen)
  740.         print("\n")
  741.     else:
  742.         print("Žádné optimální tahy nebyly nalezeny.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement