Advertisement
max2201111

very good legalni tahy OK

Jul 13th, 2024
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 24.13 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.         print("Šachovnice inicializována")
  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.                 else:
  82.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  83.                 self._set_piece_at(square, piece_type, color)
  84.                 square += 1
  85.  
  86.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  87.         self.castling_rights = chess.BB_EMPTY
  88.         if '-' not in parts[2]:
  89.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  90.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  91.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  92.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  93.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  94.  
  95.     def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
  96.         self.clear_square(square)
  97.         super()._set_piece_at(square, piece_type, color)
  98.         if piece_type == AMAZON:
  99.             if color == chess.WHITE:
  100.                 self.amazons_white |= chess.BB_SQUARES[square]
  101.             else:
  102.                 self.amazons_black |= chess.BB_SQUARES[square]
  103.         elif piece_type == CYRIL:
  104.             if color == chess.WHITE:
  105.                 self.cyrils_white |= chess.BB_SQUARES[square]
  106.             else:
  107.                 self.cyrils_black |= chess.BB_SQUARES[square]
  108.         elif piece_type == EVE:
  109.             if color == chess.WHITE:
  110.                 self.eves_white |= chess.BB_SQUARES[square]
  111.             else:
  112.                 self.eves_black |= chess.BB_SQUARES[square]
  113.  
  114.     def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
  115.         if self.amazons_white & chess.BB_SQUARES[square]:
  116.             return chess.Piece(AMAZON, chess.WHITE)
  117.         elif self.amazons_black & chess.BB_SQUARES[square]:
  118.             return chess.Piece(AMAZON, chess.BLACK)
  119.         elif self.cyrils_white & chess.BB_SQUARES[square]:
  120.             return chess.Piece(CYRIL, chess.WHITE)
  121.         elif self.cyrils_black & chess.BB_SQUARES[square]:
  122.             return chess.Piece(CYRIL, chess.BLACK)
  123.         elif self.eves_white & chess.BB_SQUARES[square]:
  124.             return chess.Piece(EVE, chess.WHITE)
  125.         elif self.eves_black & chess.BB_SQUARES[square]:
  126.             return chess.Piece(EVE, chess.BLACK)
  127.         return super().piece_at(square)
  128.  
  129.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  130.         our_pieces = self.occupied_co[self.turn]
  131.         if self.turn == chess.WHITE:
  132.             our_amazons = self.amazons_white
  133.             our_cyrils = self.cyrils_white
  134.             our_eves = self.eves_white
  135.         else:
  136.             our_amazons = self.amazons_black
  137.             our_cyrils = self.cyrils_black
  138.             our_eves = self.eves_black
  139.    
  140.         # Generování tahů pro amazonky
  141.         for from_square in chess.scan_forward(our_amazons & from_mask):
  142.             attacks = self.amazon_attacks(from_square)
  143.             valid_moves = attacks & ~our_pieces & to_mask
  144.             for to_square in chess.scan_forward(valid_moves):
  145.                 yield Move(from_square, to_square)
  146.    
  147.         # Generování tahů pro Cyrily
  148.         for from_square in chess.scan_forward(our_cyrils & from_mask):
  149.             attacks = self.cyril_attacks(from_square)
  150.             valid_moves = attacks & ~our_pieces & to_mask
  151.             for to_square in chess.scan_forward(valid_moves):
  152.                 yield Move(from_square, to_square)
  153.    
  154.         # Generování tahů pro Evy
  155.         for from_square in chess.scan_forward(our_eves & from_mask):
  156.             attacks = self.eve_attacks(from_square)
  157.             valid_moves = attacks & ~our_pieces & to_mask
  158.             for to_square in chess.scan_forward(valid_moves):
  159.                 yield Move(from_square, to_square)
  160.    
  161.         # Generování tahů pro standardní figury
  162.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  163.             piece = self.piece_at(move.from_square)
  164.             if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
  165.                 yield move
  166.  
  167.     def queen_attacks(self, square):
  168.         return self.bishop_attacks(square) | self.rook_attacks(square)
  169.  
  170.     def bishop_attacks(self, square):
  171.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  172.  
  173.     def rook_attacks(self, square):
  174.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  175.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  176.  
  177.     def amazon_attacks(self, square):
  178.         return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  179.  
  180.     def cyril_attacks(self, square):
  181.         return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  182.  
  183.     def eve_attacks(self, square):
  184.         return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  185.  
  186.     def is_pseudo_legal(self, move):
  187.         from_square = move.from_square
  188.         to_square = move.to_square
  189.         piece = self.piece_at(from_square)
  190.    
  191.         if not piece or piece.color != self.turn:
  192.             return False
  193.    
  194.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  195.             return False
  196.    
  197.         if self.is_castling(move):
  198.             return True
  199.    
  200.         if piece.piece_type == AMAZON:
  201.             return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
  202.         elif piece.piece_type == CYRIL:
  203.             return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
  204.         elif piece.piece_type == EVE:
  205.             return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
  206.         else:
  207.             return super().is_pseudo_legal(move)
  208.  
  209.     def is_legal(self, move):
  210.         if not self.is_pseudo_legal(move):
  211.             return False
  212.  
  213.         from_square = move.from_square
  214.         to_square = move.to_square
  215.         piece = self.piece_at(from_square)
  216.         captured_piece = self.piece_at(to_square)
  217.  
  218.         self.clear_square(from_square)
  219.         self.clear_square(to_square)
  220.         self._set_piece_at(to_square, piece.piece_type, piece.color)
  221.  
  222.         king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
  223.         is_check = self._is_attacked_by(not self.turn, king_square)
  224.  
  225.         self.clear_square(to_square)
  226.         self._set_piece_at(from_square, piece.piece_type, piece.color)
  227.         if captured_piece:
  228.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  229.  
  230.         if is_check:
  231.             attackers = self.attackers(not self.turn, king_square)
  232.             print(f"[DEBUG] King at {chess.SQUARE_NAMES[king_square]} is attacked by pieces at: {[chess.SQUARE_NAMES[sq] for sq in chess.scan_forward(attackers)]}")
  233.  
  234.         return not is_check
  235.  
  236.     def _is_attacked_by(self, color, square):
  237.         attackers = self.attackers(color, square)
  238.         return bool(attackers)
  239.  
  240.     def attackers(self, color, square):
  241.         attackers = chess.BB_EMPTY
  242.  
  243.         knights = self.knights & self.occupied_co[color]
  244.         attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  245.  
  246.         king = self.kings & self.occupied_co[color]
  247.         attackers |= king & chess.BB_KING_ATTACKS[square]
  248.  
  249.         pawns = self.pawns & self.occupied_co[color]
  250.         if color == chess.WHITE:
  251.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.BLACK][square]
  252.         else:
  253.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.WHITE][square]
  254.  
  255.         queens = self.queens & self.occupied_co[color]
  256.         bishops = (self.bishops | queens) & self.occupied_co[color]
  257.         rooks = (self.rooks | queens) & self.occupied_co[color]
  258.  
  259.         attackers |= chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] & bishops
  260.         attackers |= (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  261.                       chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]) & rooks
  262.  
  263.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  264.         for amazon_square in chess.scan_forward(amazons):
  265.             if self.amazon_attacks(amazon_square) & chess.BB_SQUARES[square]:
  266.                 attackers |= chess.BB_SQUARES[amazon_square]
  267.  
  268.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  269.         for cyril_square in chess.scan_forward(cyrils):
  270.             if self.cyril_attacks(cyril_square) & chess.BB_SQUARES[square]:
  271.                 attackers |= chess.BB_SQUARES[cyril_square]
  272.  
  273.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  274.         for eve_square in chess.scan_forward(eves):
  275.             if self.eve_attacks(eve_square) & chess.BB_SQUARES[square]:
  276.                 attackers |= chess.BB_SQUARES[eve_square]
  277.  
  278.         return attackers
  279.  
  280.     def push(self, move):
  281.         if not self.is_legal(move):
  282.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  283.  
  284.         piece = self.piece_at(move.from_square)
  285.         captured_piece = self.piece_at(move.to_square)
  286.  
  287.         self.clear_square(move.from_square)
  288.         self.clear_square(move.to_square)
  289.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  290.  
  291.         self.turn = not self.turn
  292.  
  293.         self.move_stack.append((move, captured_piece))
  294.  
  295.     def pop(self):
  296.         if not self.move_stack:
  297.             return None
  298.  
  299.         move, captured_piece = self.move_stack.pop()
  300.  
  301.         piece = self.piece_at(move.to_square)
  302.        
  303.         self.clear_square(move.from_square)
  304.         self.clear_square(move.to_square)
  305.  
  306.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  307.  
  308.         if captured_piece:
  309.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  310.  
  311.         self.turn = not self.turn
  312.  
  313.         return move
  314.  
  315.     def is_check(self):
  316.         king_square = self.king(self.turn)
  317.         if king_square is None:
  318.             return False
  319.         is_check = self._is_attacked_by(not self.turn, king_square)
  320.         print(f"[DEBUG] Checking if position is check: FEN: {self.fen()}, King at {chess.SQUARE_NAMES[king_square]}, is_check: {is_check}")
  321.         return is_check
  322.  
  323.     def is_checkmate(self):
  324.         if not self.is_check():
  325.             print(f"[DEBUG] Position is not check, hence not checkmate: FEN: {self.fen()}")
  326.             return False
  327.         legal_moves = list(self.generate_legal_moves())
  328.         print(f"[DEBUG] Checking if position is checkmate: FEN: {self.fen()}, Legal moves: {legal_moves}")
  329.         return len(legal_moves) == 0
  330.  
  331.     def is_game_over(self):
  332.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  333.  
  334.     def is_stalemate(self):
  335.         if self.is_check():
  336.             return False
  337.         legal_moves = list(self.generate_legal_moves())
  338.         print(f"[DEBUG] Checking if position is stalemate: FEN: {self.fen()}, Legal moves: {legal_moves}")
  339.         return len(legal_moves) == 0
  340.    
  341.     def is_insufficient_material(self):
  342.         return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  343.                 self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  344.             chess.popcount(self.occupied) <= 3
  345.         )
  346.  
  347.     def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
  348.         for move in self.generate_pseudo_legal_moves(from_mask, to_mask):
  349.             if self.is_legal(move):
  350.                 print(f"[DEBUG] Legal move: {move}")
  351.                 yield move
  352.             else:
  353.                 print(f"[DEBUG] Illegal move: {move}")
  354.  
  355.     def debug_amazons(self):
  356.         print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  357.         print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  358.         for square in chess.SQUARES:
  359.             if self.amazons_white & chess.BB_SQUARES[square]:
  360.                 print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  361.             if self.amazons_black & chess.BB_SQUARES[square]:
  362.                 print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  363.  
  364.     def debug_cyrils(self):
  365.         print(f"Bitboard bílých Cyrils: {format(self.cyrils_white, '064b')}")
  366.         print(f"Bitboard černých Cyrils: {format(self.cyrils_black, '064b')}")
  367.         for square in chess.SQUARES:
  368.             if self.cyrils_white & chess.BB_SQUARES[square]:
  369.                 print(f"Bílý Cyril na {chess.SQUARE_NAMES[square]}")
  370.             if self.cyrils_black & chess.BB_SQUARES[square]:
  371.                 print(f"Černý Cyril na {chess.SQUARE_NAMES[square]}")
  372.  
  373.     def debug_eves(self):
  374.         print(f"Bitboard bílých Eves: {format(self.eves_white, '064b')}")
  375.         print(f"Bitboard černých Eves: {format(self.eves_black, '064b')}")
  376.         for square in chess.SQUARES:
  377.             if self.eves_white & chess.BB_SQUARES[square]:
  378.                 print(f"Bílá Eve na {chess.SQUARE_NAMES[square]}")
  379.             if self.eves_black & chess.BB_SQUARES[square]:
  380.                 print(f"Černá Eve na {chess.SQUARE_NAMES[square]}")
  381.  
  382.     def piece_symbol(self, piece):
  383.         if piece is None:
  384.             return '.'
  385.         if piece.piece_type == AMAZON:
  386.             return 'A' if piece.color == chess.WHITE else 'a'
  387.         if piece.piece_type == CYRIL:
  388.             return 'C' if piece.color == chess.WHITE else 'c'
  389.         if piece.piece_type == EVE:
  390.             return 'E' if piece.color == chess.WHITE else 'e'
  391.         return piece.symbol()
  392.  
  393.     def piece_type_at(self, square):
  394.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  395.             return AMAZON
  396.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  397.             return CYRIL
  398.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  399.             return EVE
  400.         return super().piece_type_at(square)
  401.  
  402.     def color_at(self, square):
  403.         if self.amazons_white & chess.BB_SQUARES[square]:
  404.             return chess.WHITE
  405.         if self.amazons_black & chess.BB_SQUARES[square]:
  406.             return chess.BLACK
  407.         if self.cyrils_white & chess.BB_SQUARES[square]:
  408.             return chess.WHITE
  409.         if self.cyrils_black & chess.BB_SQUARES[square]:
  410.             return chess.BLACK
  411.         if self.eves_white & chess.BB_SQUARES[square]:
  412.             return chess.WHITE
  413.         if self.eves_black & chess.BB_SQUARES[square]:
  414.             return chess.BLACK
  415.         return super().color_at(square)
  416.  
  417.     @property
  418.     def legal_moves(self):
  419.         return list(self.generate_legal_moves())
  420.  
  421.     def __str__(self):
  422.         builder = []
  423.         for square in chess.SQUARES_180:
  424.             piece = self.piece_at(square)
  425.             symbol = self.piece_symbol(piece) if piece else '.'
  426.             builder.append(symbol)
  427.             if chess.square_file(square) == 7:
  428.                 if square != chess.H1:
  429.                     builder.append('\n')
  430.         return ''.join(builder)
  431.  
  432.     def print_all_possible_moves(self):
  433.         print(f"[DEBUG] All possible moves for FEN: {self.fen()}")
  434.         for move in self.generate_pseudo_legal_moves():
  435.             print(f"Move: {move}, Is legal: {self.is_legal(move)}")
  436.  
  437. def simplify_fen_string(fen):
  438.     parts = fen.split(' ')
  439.     return ' '.join(parts[:4])  # Zachováváme pouze informace o pozici, barvě na tahu, rošádách a en passant
  440.  
  441. def format_time(seconds):
  442.     hours, remainder = divmod(seconds, 3600)
  443.     minutes, seconds = divmod(remainder, 60)
  444.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  445.  
  446. def print_elapsed_time(stop_event):
  447.     start_time = time.time()
  448.     while not stop_event.is_set():
  449.         elapsed_time = time.time() - start_time
  450.         formatted_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
  451.         print(f"Uplynulý čas: {formatted_time}", end='\r')
  452.         time.sleep(1)
  453.  
  454. def calculate_optimal_moves(start_fen: str) -> Dict[str, int]:
  455.     board = CustomBoard(start_fen)
  456.     AR = {simplify_fen_string(start_fen): 0}
  457.     queue = deque([(simplify_fen_string(start_fen), 0)])
  458.     visited = set()
  459.  
  460.     start_time = time.time()
  461.     current_level = 0
  462.     pozice_na_urovni = 0
  463.     level_start_time = start_time
  464.  
  465.     stop_event = threading.Event()
  466.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event,))
  467.     timer_thread.start()
  468.  
  469.     try:
  470.         # Fáze 1: Generování všech pozic
  471.         while queue:
  472.             fen, hloubka = queue.popleft()
  473.  
  474.             if hloubka > current_level:
  475.                 level_time = time.time() - level_start_time
  476.                 print(f"\nHloubka {current_level + 1}: {pozice_na_urovni} pozic, Čas: {format_time(level_time)}")
  477.                 current_level = hloubka
  478.                 pozice_na_urovni = 0
  479.                 level_start_time = time.time()
  480.  
  481.             if fen in visited:
  482.                 continue
  483.  
  484.             visited.add(fen)
  485.             pozice_na_urovni += 1
  486.             board.set_custom_fen(fen)
  487.  
  488.             if board.is_checkmate():
  489.                 AR[fen] = -1000 if board.turn == chess.WHITE else 1000
  490.             elif board.is_stalemate() or board.is_insufficient_material():
  491.                 AR[fen] = 0
  492.             else:
  493.                 legal_moves = list(board.legal_moves)
  494.                 if not legal_moves:
  495.                     print(f"Warning: No legal moves for position ({pozice_na_urovni}):")
  496.                     print(f"FEN: {fen}")
  497.                     print(f"Is game over: {board.is_game_over()}")
  498.                     print(f"Is checkmate: {board.is_checkmate()}")
  499.                     print(f"Is stalemate: {board.is_stalemate()}")
  500.                     print(f"Is insufficient material: {board.is_insufficient_material()}")
  501.                     print(f"King square: {board.king(board.turn)}")
  502.                     print(f"Pieces: {board.piece_map()}")
  503.                     board.print_all_possible_moves()
  504.                 for move in legal_moves:
  505.                     board.push(move)
  506.                     new_fen = simplify_fen_string(board.fen())
  507.                     if new_fen not in AR:
  508.                         AR[new_fen] = 0
  509.                         queue.append((new_fen, hloubka + 1))
  510.                     board.pop()
  511.  
  512.         print(f"\nCelkový počet pozic: {len(AR)}")
  513.  
  514.         # Fáze 2: Aktualizace hodnot
  515.         print("\nZačíná aktualizace hodnot...")
  516.         changed = True
  517.         uroven = 0
  518.         while changed:
  519.             uroven += 1
  520.             level_start_time = time.time()
  521.             print(f"\nVýpočet v úrovni {uroven}")
  522.            
  523.             changed = False
  524.             current_level_positions = 0
  525.             for fen in list(AR.keys()):
  526.                 board.set_custom_fen(fen)
  527.                 if board.is_game_over():
  528.                     continue
  529.  
  530.                 legal_moves = list(board.legal_moves)
  531.                 if not legal_moves:
  532.                     print(f"Warning: No legal moves for position ({current_level_positions}):")
  533.                     print(f"FEN: {fen}")
  534.                     print(f"Is game over: {board.is_game_over()}")
  535.                     print(f"Is checkmate: {board.is_checkmate()}")
  536.                     print(f"Is stalemate: {board.is_stalemate()}")
  537.                     print(f"Is insufficient material: {board.is_insufficient_material()}")
  538.                     print(f"King square: {board.king(board.turn)}")
  539.                     print(f"Pieces: {board.piece_map()}")
  540.                     board.print_all_possible_moves()
  541.                     current_level_positions += 1
  542.                     continue
  543.  
  544.                 values = []
  545.                 for move in legal_moves:
  546.                     board.push(move)
  547.                     new_fen = simplify_fen_string(board.fen())
  548.                     if new_fen in AR:
  549.                         values.append(AR[new_fen])
  550.                     board.pop()
  551.  
  552.                 if values:
  553.                     if board.turn == chess.WHITE:
  554.                         best_value = max(values)
  555.                         if best_value == 1001 - uroven:
  556.                             AR[fen] = 1000 - uroven
  557.                             changed = True
  558.                             current_level_positions += 1
  559.                     else:
  560.                         best_value = min(values)
  561.                         if best_value == -1001 + uroven:
  562.                             AR[fen] = -1000 + uroven
  563.                             changed = True
  564.                             current_level_positions += 1
  565.  
  566.             level_end_time = time.time()
  567.             level_elapsed_time = level_end_time - level_start_time
  568.             print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
  569.             print(f"Čas úrovně: {format_time(level_elapsed_time)}")
  570.  
  571.             if not changed:
  572.                 break
  573.  
  574.     finally:
  575.         stop_event.set()
  576.         timer_thread.join()
  577.  
  578.     total_time = time.time() - start_time
  579.     print(f"\nCelkový čas výpočtu: {format_time(total_time)}")
  580.  
  581.     return AR
  582.  
  583. if __name__ == "__main__":
  584.     start_fen = "8/3k4/8/8/8/8/A7/6K1 w - - 0 1"
  585.     AR = calculate_optimal_moves(start_fen)
  586.     F = 0
  587.  
  588.     # Výpis výsledků
  589.     for fen, hodnota in AR.items():
  590.         F = F + 1
  591.         if F < 50 or hodnota != 0:
  592.             print(f"FEN: {fen}")
  593.             print(f"Hodnota: {hodnota}")
  594.             print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement