Advertisement
max2201111

cele OK!!

Jul 12th, 2024
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 21.00 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, attacker_square = 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.         return not is_check
  231.  
  232.     def _is_attacked_by(self, color, square):
  233.         attackers = self.attackers(color, square)
  234.         if attackers:
  235.             for attacker_square in chess.scan_forward(attackers):
  236.                 return True, attacker_square
  237.         return False, None
  238.  
  239.     def attackers(self, color, square):
  240.         attackers = chess.BB_EMPTY
  241.  
  242.         knights = self.knights & self.occupied_co[color]
  243.         attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  244.  
  245.         king = self.kings & self.occupied_co[color]
  246.         attackers |= king & chess.BB_KING_ATTACKS[square]
  247.  
  248.         pawns = self.pawns & self.occupied_co[color]
  249.         if color == chess.WHITE:
  250.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.BLACK][square]
  251.         else:
  252.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.WHITE][square]
  253.  
  254.         queens = self.queens & self.occupied_co[color]
  255.         bishops = (self.bishops | queens) & self.occupied_co[color]
  256.         rooks = (self.rooks | queens) & self.occupied_co[color]
  257.  
  258.         attackers |= chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] & bishops
  259.         attackers |= (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  260.                       chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]) & rooks
  261.  
  262.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  263.         for amazon_square in chess.scan_forward(amazons):
  264.             if self.amazon_attacks(amazon_square) & chess.BB_SQUARES[square]:
  265.                 attackers |= chess.BB_SQUARES[amazon_square]
  266.  
  267.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  268.         for cyril_square in chess.scan_forward(cyrils):
  269.             if self.cyril_attacks(cyril_square) & chess.BB_SQUARES[square]:
  270.                 attackers |= chess.BB_SQUARES[cyril_square]
  271.  
  272.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  273.         for eve_square in chess.scan_forward(eves):
  274.             if self.eve_attacks(eve_square) & chess.BB_SQUARES[square]:
  275.                 attackers |= chess.BB_SQUARES[eve_square]
  276.  
  277.         return attackers
  278.  
  279.     def push(self, move):
  280.         if not self.is_legal(move):
  281.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  282.  
  283.         piece = self.piece_at(move.from_square)
  284.         captured_piece = self.piece_at(move.to_square)
  285.  
  286.         self.clear_square(move.from_square)
  287.         self.clear_square(move.to_square)
  288.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  289.  
  290.         self.turn = not self.turn
  291.  
  292.         self.move_stack.append((move, captured_piece))
  293.  
  294.     def pop(self):
  295.         if not self.move_stack:
  296.             return None
  297.  
  298.         move, captured_piece = self.move_stack.pop()
  299.  
  300.         piece = self.piece_at(move.to_square)
  301.        
  302.         self.clear_square(move.from_square)
  303.         self.clear_square(move.to_square)
  304.  
  305.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  306.  
  307.         if captured_piece:
  308.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  309.  
  310.         self.turn = not self.turn
  311.  
  312.         return move
  313.  
  314.     def is_check(self):
  315.         king_square = self.king(self.turn)
  316.         if king_square is None:
  317.             return False
  318.         return self._is_attacked_by(not self.turn, king_square)[0]
  319.  
  320.     def is_checkmate(self):
  321.         if not self.is_check():
  322.             return False
  323.         return not any(self.generate_legal_moves())
  324.  
  325.     def is_stalemate(self):
  326.         if self.is_check():
  327.             return False
  328.         return not any(self.generate_legal_moves())
  329.    
  330.     def is_insufficient_material(self):
  331.             return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  332.                     self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  333.                 chess.popcount(self.occupied) <= 3
  334.             )
  335.  
  336.     def is_game_over(self):
  337.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  338.  
  339.     def debug_amazons(self):
  340.         print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  341.         print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  342.         for square in chess.SQUARES:
  343.             if self.amazons_white & chess.BB_SQUARES[square]:
  344.                 print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  345.             if self.amazons_black & chess.BB_SQUARES[square]:
  346.                 print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  347.  
  348.     def debug_cyrils(self):
  349.         print(f"Bitboard bílých Cyrils: {format(self.cyrils_white, '064b')}")
  350.         print(f"Bitboard černých Cyrils: {format(self.cyrils_black, '064b')}")
  351.         for square in chess.SQUARES:
  352.             if self.cyrils_white & chess.BB_SQUARES[square]:
  353.                 print(f"Bílý Cyril na {chess.SQUARE_NAMES[square]}")
  354.             if self.cyrils_black & chess.BB_SQUARES[square]:
  355.                 print(f"Černý Cyril na {chess.SQUARE_NAMES[square]}")
  356.  
  357.     def debug_eves(self):
  358.         print(f"Bitboard bílých Eves: {format(self.eves_white, '064b')}")
  359.         print(f"Bitboard černých Eves: {format(self.eves_black, '064b')}")
  360.         for square in chess.SQUARES:
  361.             if self.eves_white & chess.BB_SQUARES[square]:
  362.                 print(f"Bílá Eve na {chess.SQUARE_NAMES[square]}")
  363.             if self.eves_black & chess.BB_SQUARES[square]:
  364.                 print(f"Černá Eve na {chess.SQUARE_NAMES[square]}")
  365.  
  366.     def piece_symbol(self, piece):
  367.         if piece is None:
  368.             return '.'
  369.         if piece.piece_type == AMAZON:
  370.             return 'A' if piece.color == chess.WHITE else 'a'
  371.         if piece.piece_type == CYRIL:
  372.             return 'C' if piece.color == chess.WHITE else 'c'
  373.         if piece.piece_type == EVE:
  374.             return 'E' if piece.color == chess.WHITE else 'e'
  375.         return piece.symbol()
  376.  
  377.     def piece_type_at(self, square):
  378.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  379.             return AMAZON
  380.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  381.             return CYRIL
  382.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  383.             return EVE
  384.         return super().piece_type_at(square)
  385.  
  386.     def color_at(self, square):
  387.         if self.amazons_white & chess.BB_SQUARES[square]:
  388.             return chess.WHITE
  389.         if self.amazons_black & chess.BB_SQUARES[square]:
  390.             return chess.BLACK
  391.         if self.cyrils_white & chess.BB_SQUARES[square]:
  392.             return chess.WHITE
  393.         if self.cyrils_black & chess.BB_SQUARES[square]:
  394.             return chess.BLACK
  395.         if self.eves_white & chess.BB_SQUARES[square]:
  396.             return chess.WHITE
  397.         if self.eves_black & chess.BB_SQUARES[square]:
  398.             return chess.BLACK
  399.         return super().color_at(square)
  400.  
  401.     @property
  402.     def legal_moves(self):
  403.         return [move for move in self.generate_pseudo_legal_moves() if self.is_legal(move)]
  404.  
  405.     def __str__(self):
  406.         builder = []
  407.         for square in chess.SQUARES_180:
  408.             piece = self.piece_at(square)
  409.             symbol = self.piece_symbol(piece) if piece else '.'
  410.             builder.append(symbol)
  411.             if chess.square_file(square) == 7:
  412.                 if square != chess.H1:
  413.                     builder.append('\n')
  414.         return ''.join(builder)
  415.  
  416. def simplify_fen_string(fen):
  417.     parts = fen.split(' ')
  418.     return ' '.join(parts[:4])  # Zachováváme pouze informace o pozici, barvě na tahu, rošádách a en passant
  419.  
  420. def format_time(seconds):
  421.     hours, remainder = divmod(seconds, 3600)
  422.     minutes, seconds = divmod(remainder, 60)
  423.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  424.  
  425. def print_elapsed_time(stop_event):
  426.     start_time = time.time()
  427.     while not stop_event.is_set():
  428.         elapsed_time = time.time() - start_time
  429.         formatted_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
  430.         print(f"Uplynulý čas: {formatted_time}", end='\r')
  431.         time.sleep(1)
  432.  
  433. def calculate_optimal_moves(start_fen: str) -> Dict[str, int]:
  434.     board = CustomBoard(start_fen)
  435.     AR = {simplify_fen_string(start_fen): 0}
  436.     queue = deque([(simplify_fen_string(start_fen), 0)])
  437.     visited = set()
  438.  
  439.     start_time = time.time()
  440.     current_level = 0
  441.     pozice_na_urovni = 0
  442.     level_start_time = start_time
  443.  
  444.     stop_event = threading.Event()
  445.     timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event,))
  446.     timer_thread.start()
  447.  
  448.     try:
  449.         while queue:
  450.             fen, hloubka = queue.popleft()
  451.  
  452.             if hloubka > current_level:
  453.                 level_time = time.time() - level_start_time
  454.                 print(f"\nHloubka {current_level}: {pozice_na_urovni} pozic, Čas: {format_time(level_time)}")
  455.                 current_level = hloubka
  456.                 pozice_na_urovni = 0
  457.                 level_start_time = time.time()
  458.  
  459.             if fen in visited:
  460.                 continue
  461.  
  462.             visited.add(fen)
  463.             pozice_na_urovni += 1
  464.             board.set_custom_fen(fen)
  465.  
  466.             if board.is_checkmate():
  467.                 AR[fen] = -1000 + hloubka if board.turn == chess.WHITE else 1000 - hloubka
  468.                 continue
  469.             elif board.is_stalemate() or board.is_insufficient_material():
  470.                 AR[fen] = 0
  471.                 continue
  472.  
  473.             legal_moves = list(board.legal_moves)
  474.  
  475.             for move in legal_moves:
  476.                 board.push(move)
  477.                 new_fen = simplify_fen_string(board.fen())
  478.                 if new_fen not in AR:
  479.                     AR[new_fen] = 0
  480.                     queue.append((new_fen, hloubka + 1))
  481.                 board.pop()
  482.  
  483.         level_time = time.time() - level_start_time
  484.         print(f"\nHloubka {current_level}: {pozice_na_urovni} pozic, Čas: {format_time(level_time)}")
  485.  
  486.         # Procházení a aktualizace hodnot
  487.         changed = True
  488.         while changed:
  489.             changed = False
  490.             for fen in AR:
  491.                 board.set_custom_fen(fen)
  492.                 if board.is_game_over():
  493.                     continue
  494.  
  495.                 legal_moves = list(board.legal_moves)
  496.                 if board.turn == chess.WHITE:
  497.                     best_value = max(
  498.                         (AR[simplify_fen_string(board.fen())] for move in legal_moves if board.push(move) or True and board.pop()),
  499.                         default=AR[fen]
  500.                     )
  501.                     if best_value > AR[fen]:
  502.                         AR[fen] = best_value
  503.                         changed = True
  504.                 else:
  505.                     best_value = min(
  506.                         (AR[simplify_fen_string(board.fen())] for move in legal_moves if board.push(move) or True and board.pop()),
  507.                         default=AR[fen]
  508.                     )
  509.                     if best_value < AR[fen]:
  510.                         AR[fen] = best_value
  511.                         changed = True
  512.  
  513.         celkovy_cas = time.time() - start_time
  514.         print(f"\nVýpočet dokončen za {format_time(celkovy_cas)}")
  515.  
  516.     finally:
  517.         stop_event.set()
  518.         timer_thread.join()
  519.  
  520.     return AR
  521.  
  522. if __name__ == "__main__":
  523.     start_fen = "8/3k4/8/8/8/8/A7/6K1 w - - 0 1"
  524.     AR = calculate_optimal_moves(start_fen)
  525.  
  526.     # Výpis výsledků
  527.     for fen, hodnota in AR.items():
  528.         if hodnota != None and hodnota < 982 and hondota > 500:
  529.             print(f"FEN: {fen}")
  530.             print(f"Hodnota: {hodnota}")
  531.             print()
  532.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement