Advertisement
max2201111

rychle a spravny pocet pozic

Jul 12th, 2024
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.85 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.  
  30.     def clear_square(self, square):
  31.         super()._remove_piece_at(square)
  32.         self.amazons_white &= ~chess.BB_SQUARES[square]
  33.         self.amazons_black &= ~chess.BB_SQUARES[square]
  34.         self.cyrils_white &= ~chess.BB_SQUARES[square]
  35.         self.cyrils_black &= ~chess.BB_SQUARES[square]
  36.         self.eves_white &= ~chess.BB_SQUARES[square]
  37.         self.eves_black &= ~chess.BB_SQUARES[square]
  38.  
  39.     def set_custom_fen(self, fen):
  40.         parts = fen.split()
  41.         board_part = parts[0]
  42.  
  43.         self.clear()
  44.         self.amazons_white = chess.BB_EMPTY
  45.         self.amazons_black = chess.BB_EMPTY
  46.         self.cyrils_white = chess.BB_EMPTY
  47.         self.cyrils_black = chess.BB_EMPTY
  48.         self.eves_white = chess.BB_EMPTY
  49.         self.eves_black = chess.BB_EMPTY
  50.  
  51.         square = 56
  52.         for c in board_part:
  53.             if c == '/':
  54.                 square -= 16
  55.             elif c.isdigit():
  56.                 square += int(c)
  57.             else:
  58.                 color = chess.WHITE if c.isupper() else chess.BLACK
  59.                 if c.upper() == 'A':
  60.                     if color == chess.WHITE:
  61.                         self.amazons_white |= chess.BB_SQUARES[square]
  62.                     else:
  63.                         self.amazons_black |= chess.BB_SQUARES[square]
  64.                     piece_type = AMAZON
  65.                 elif c.upper() == 'C':
  66.                     if color == chess.WHITE:
  67.                         self.cyrils_white |= chess.BB_SQUARES[square]
  68.                     else:
  69.                         self.cyrils_black |= chess.BB_SQUARES[square]
  70.                     piece_type = CYRIL
  71.                 elif c.upper() == 'E':
  72.                     if color == chess.WHITE:
  73.                         self.eves_white |= chess.BB_SQUARES[square]
  74.                     else:
  75.                         self.eves_black |= chess.BB_SQUARES[square]
  76.                     piece_type = EVE
  77.                 else:
  78.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  79.                 self._set_piece_at(square, piece_type, color)
  80.                 square += 1
  81.  
  82.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  83.         self.castling_rights = chess.BB_EMPTY
  84.         if '-' not in parts[2]:
  85.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  86.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  87.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  88.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  89.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  90.  
  91.     def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
  92.         self.clear_square(square)
  93.         super()._set_piece_at(square, piece_type, color)
  94.         if piece_type == AMAZON:
  95.             if color == chess.WHITE:
  96.                 self.amazons_white |= chess.BB_SQUARES[square]
  97.             else:
  98.                 self.amazons_black |= chess.BB_SQUARES[square]
  99.         elif piece_type == CYRIL:
  100.             if color == chess.WHITE:
  101.                 self.cyrils_white |= chess.BB_SQUARES[square]
  102.             else:
  103.                 self.cyrils_black |= chess.BB_SQUARES[square]
  104.         elif piece_type == EVE:
  105.             if color == chess.WHITE:
  106.                 self.eves_white |= chess.BB_SQUARES[square]
  107.             else:
  108.                 self.eves_black |= chess.BB_SQUARES[square]
  109.  
  110.     def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
  111.         if self.amazons_white & chess.BB_SQUARES[square]:
  112.             return chess.Piece(AMAZON, chess.WHITE)
  113.         elif self.amazons_black & chess.BB_SQUARES[square]:
  114.             return chess.Piece(AMAZON, chess.BLACK)
  115.         elif self.cyrils_white & chess.BB_SQUARES[square]:
  116.             return chess.Piece(CYRIL, chess.WHITE)
  117.         elif self.cyrils_black & chess.BB_SQUARES[square]:
  118.             return chess.Piece(CYRIL, chess.BLACK)
  119.         elif self.eves_white & chess.BB_SQUARES[square]:
  120.             return chess.Piece(EVE, chess.WHITE)
  121.         elif self.eves_black & chess.BB_SQUARES[square]:
  122.             return chess.Piece(EVE, chess.BLACK)
  123.         return super().piece_at(square)
  124.  
  125.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  126.         our_pieces = self.occupied_co[self.turn]
  127.         if self.turn == chess.WHITE:
  128.             our_amazons = self.amazons_white
  129.             our_cyrils = self.cyrils_white
  130.             our_eves = self.eves_white
  131.         else:
  132.             our_amazons = self.amazons_black
  133.             our_cyrils = self.cyrils_black
  134.             our_eves = self.eves_black
  135.  
  136.         for from_square in chess.scan_forward(our_amazons & from_mask):
  137.             attacks = self.amazon_attacks(from_square)
  138.             valid_moves = attacks & ~our_pieces & to_mask
  139.             for to_square in chess.scan_forward(valid_moves):
  140.                 yield Move(from_square, to_square)
  141.  
  142.         for from_square in chess.scan_forward(our_cyrils & from_mask):
  143.             attacks = self.cyril_attacks(from_square)
  144.             valid_moves = attacks & ~our_pieces & to_mask
  145.             for to_square in chess.scan_forward(valid_moves):
  146.                 yield Move(from_square, to_square)
  147.  
  148.         for from_square in chess.scan_forward(our_eves & from_mask):
  149.             attacks = self.eve_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.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  155.             piece = self.piece_at(move.from_square)
  156.             if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
  157.                 yield move
  158.  
  159.     def queen_attacks(self, square):
  160.         return self.bishop_attacks(square) | self.rook_attacks(square)
  161.  
  162.     def bishop_attacks(self, square):
  163.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  164.  
  165.     def rook_attacks(self, square):
  166.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  167.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  168.  
  169.     def amazon_attacks(self, square):
  170.         return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  171.  
  172.     def cyril_attacks(self, square):
  173.         return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  174.  
  175.     def eve_attacks(self, square):
  176.         return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
  177.  
  178.     def is_pseudo_legal(self, move):
  179.         from_square = move.from_square
  180.         to_square = move.to_square
  181.         piece = self.piece_at(from_square)
  182.  
  183.         if not piece or piece.color != self.turn:
  184.             return False
  185.  
  186.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  187.             return False
  188.  
  189.         if self.is_castling(move):
  190.             return True
  191.  
  192.         if piece.piece_type == AMAZON:
  193.             return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
  194.         elif piece.piece_type == CYRIL:
  195.             return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
  196.         elif piece.piece_type == EVE:
  197.             return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
  198.         else:
  199.             return super().is_pseudo_legal(move)
  200.  
  201.     def is_legal(self, move):
  202.         if not self.is_pseudo_legal(move):
  203.             return False
  204.  
  205.         from_square = move.from_square
  206.         to_square = move.to_square
  207.         piece = self.piece_at(from_square)
  208.         captured_piece = self.piece_at(to_square)
  209.  
  210.         self.clear_square(from_square)
  211.         self.clear_square(to_square)
  212.         self._set_piece_at(to_square, piece.piece_type, piece.color)
  213.  
  214.         king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
  215.         is_check, attacker_square = self._is_attacked_by(not self.turn, king_square)
  216.  
  217.         self.clear_square(to_square)
  218.         self._set_piece_at(from_square, piece.piece_type, piece.color)
  219.         if captured_piece:
  220.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  221.  
  222.         return not is_check
  223.  
  224.     def _is_attacked_by(self, color, square):
  225.         attackers = self.attackers(color, square)
  226.         if attackers:
  227.             for attacker_square in chess.scan_forward(attackers):
  228.                 return True, attacker_square
  229.         return False, None
  230.  
  231.     def attackers(self, color, square):
  232.         attackers = chess.BB_EMPTY
  233.  
  234.         knights = self.knights & self.occupied_co[color]
  235.         attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
  236.  
  237.         king = self.kings & self.occupied_co[color]
  238.         attackers |= king & chess.BB_KING_ATTACKS[square]
  239.  
  240.         pawns = self.pawns & self.occupied_co[color]
  241.         if color == chess.WHITE:
  242.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.BLACK][square]
  243.         else:
  244.             attackers |= pawns & chess.BB_PAWN_ATTACKS[chess.WHITE][square]
  245.  
  246.         queens = self.queens & self.occupied_co[color]
  247.         bishops = (self.bishops | queens) & self.occupied_co[color]
  248.         rooks = (self.rooks | queens) & self.occupied_co[color]
  249.  
  250.         attackers |= chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] & bishops
  251.         attackers |= (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  252.                       chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]) & rooks
  253.  
  254.         amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
  255.         for amazon_square in chess.scan_forward(amazons):
  256.             if self.amazon_attacks(amazon_square) & chess.BB_SQUARES[square]:
  257.                 attackers |= chess.BB_SQUARES[amazon_square]
  258.  
  259.         cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
  260.         for cyril_square in chess.scan_forward(cyrils):
  261.             if self.cyril_attacks(cyril_square) & chess.BB_SQUARES[square]:
  262.                 attackers |= chess.BB_SQUARES[cyril_square]
  263.  
  264.         eves = self.eves_white if color == chess.WHITE else self.eves_black
  265.         for eve_square in chess.scan_forward(eves):
  266.             if self.eve_attacks(eve_square) & chess.BB_SQUARES[square]:
  267.                 attackers |= chess.BB_SQUARES[eve_square]
  268.  
  269.         return attackers
  270.  
  271.     def push(self, move):
  272.         if not self.is_legal(move):
  273.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  274.  
  275.         piece = self.piece_at(move.from_square)
  276.         captured_piece = self.piece_at(move.to_square)
  277.  
  278.         self.clear_square(move.from_square)
  279.         self.clear_square(move.to_square)
  280.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  281.  
  282.         self.turn = not self.turn
  283.  
  284.         self.move_stack.append((move, captured_piece))
  285.  
  286.     def pop(self):
  287.         if not self.move_stack:
  288.             return None
  289.  
  290.         move, captured_piece = self.move_stack.pop()
  291.  
  292.         piece = self.piece_at(move.to_square)
  293.        
  294.         self.clear_square(move.from_square)
  295.         self.clear_square(move.to_square)
  296.  
  297.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  298.  
  299.         if captured_piece:
  300.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  301.  
  302.         self.turn = not self.turn
  303.  
  304.         return move
  305.  
  306.     def is_check(self):
  307.         king_square = self.king(self.turn)
  308.         if king_square is None:
  309.             return False
  310.         return self._is_attacked_by(not self.turn, king_square)[0]
  311.  
  312.     def is_checkmate(self):
  313.         if not self.is_check():
  314.             return False
  315.         return not any(self.generate_legal_moves())
  316.  
  317.     def is_stalemate(self):
  318.         if self.is_check():
  319.             return False
  320.         return not any(self.generate_legal_moves())
  321.    
  322.     def is_insufficient_material(self):
  323.             return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
  324.                     self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
  325.                 chess.popcount(self.occupied) <= 3
  326.             )
  327.  
  328.     def is_game_over(self):
  329.         return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
  330.  
  331.     def piece_symbol(self, piece):
  332.         if piece is None:
  333.             return '.'
  334.         if piece.piece_type == AMAZON:
  335.             return 'A' if piece.color == chess.WHITE else 'a'
  336.         if piece.piece_type == CYRIL:
  337.             return 'C' if piece.color == chess.WHITE else 'c'
  338.         if piece.piece_type == EVE:
  339.             return 'E' if piece.color == chess.WHITE else 'e'
  340.         return piece.symbol()
  341.  
  342.     def piece_type_at(self, square):
  343.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  344.             return AMAZON
  345.         if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
  346.             return CYRIL
  347.         if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
  348.             return EVE
  349.         return super().piece_type_at(square)
  350.  
  351.     def color_at(self, square):
  352.         if self.amazons_white & chess.BB_SQUARES[square]:
  353.             return chess.WHITE
  354.         if self.amazons_black & chess.BB_SQUARES[square]:
  355.             return chess.BLACK
  356.         if self.cyrils_white & chess.BB_SQUARES[square]:
  357.             return chess.WHITE
  358.         if self.cyrils_black & chess.BB_SQUARES[square]:
  359.             return chess.BLACK
  360.         if self.eves_white & chess.BB_SQUARES[square]:
  361.             return chess.WHITE
  362.         if self.eves_black & chess.BB_SQUARES[square]:
  363.             return chess.BLACK
  364.         return super().color_at(square)
  365.  
  366.     @property
  367.     def legal_moves(self):
  368.         return [move for move in self.generate_pseudo_legal_moves() if self.is_legal(move)]
  369.  
  370.     def __str__(self):
  371.         builder = []
  372.         for square in chess.SQUARES_180:
  373.             piece = self.piece_at(square)
  374.             symbol = self.piece_symbol(piece) if piece else '.'
  375.             builder.append(symbol)
  376.             if chess.square_file(square) == 7:
  377.                 if square != chess.H1:
  378.                     builder.append('\n')
  379.         return ''.join(builder)
  380.  
  381. def simplify_fen_string(fen):
  382.     parts = fen.split(' ')
  383.     return ' '.join(parts[:4])  # Zachováváme pouze informace o pozici, barvě na tahu, rošádách a en passant
  384.  
  385.  
  386. import chess
  387. from typing import Dict
  388. from collections import deque
  389. import time
  390.  
  391. def calculate_optimal_moves(start_fen: str) -> Dict[str, int]:
  392.     board = CustomBoard(start_fen)
  393.     AR = {}
  394.     queue = deque([(start_fen, 0)])
  395.     visited = set()
  396.  
  397.     start_time = time.time()
  398.     current_level = 0
  399.     positions_at_level = 0
  400.     level_start_time = start_time
  401.  
  402.     while queue:
  403.         fen, depth = queue.popleft()
  404.  
  405.         if depth > current_level:
  406.             level_time = time.time() - level_start_time
  407.             print(f"Hloubka {current_level}: {positions_at_level} pozic, Čas: {format_time(level_time)}")
  408.             current_level = depth
  409.             positions_at_level = 0
  410.             level_start_time = time.time()
  411.  
  412.         if fen in visited:
  413.             continue
  414.  
  415.         visited.add(fen)
  416.         positions_at_level += 1
  417.         board.set_custom_fen(fen)
  418.  
  419.         if board.is_checkmate():
  420.             AR[fen] = -1000 if board.turn == chess.WHITE else 1000
  421.         elif board.is_stalemate() or board.is_insufficient_material():
  422.             AR[fen] = 1 if board.turn == chess.WHITE else -1
  423.         else:
  424.             legal_moves = list(board.legal_moves)
  425.             for move in legal_moves:
  426.                 board.push(move)
  427.                 new_fen = simplify_fen_string(board.fen())
  428.                 if new_fen not in AR:
  429.                     queue.append((new_fen, depth + 1))
  430.                 board.pop()
  431.  
  432.     # Procházení a aktualizace hodnot
  433.     changed = True
  434.     while changed:
  435.         changed = False
  436.         for fen in list(AR.keys()):
  437.             board.set_custom_fen(fen)
  438.             if board.is_game_over():
  439.                 continue
  440.  
  441.             legal_moves = list(board.legal_moves)
  442.             if not legal_moves:
  443.                 continue
  444.  
  445.             values = []
  446.             for move in legal_moves:
  447.                 board.push(move)
  448.                 new_fen = simplify_fen_string(board.fen())
  449.                 if new_fen in AR:
  450.                     values.append(AR[new_fen])
  451.                 board.pop()
  452.  
  453.             if values:
  454.                 if board.turn == chess.WHITE:
  455.                     best_value = max(values)
  456.                     if best_value < 0:
  457.                         new_value = best_value + 1
  458.                     elif best_value > 0:
  459.                         new_value = 1000 - (1000 - best_value + 1)
  460.                     else:
  461.                         new_value = 1
  462.                 else:
  463.                     best_value = min(values)
  464.                     if best_value > 0:
  465.                         new_value = best_value - 1
  466.                     elif best_value < 0:
  467.                         new_value = -1000 + (-1000 - best_value - 1)
  468.                     else:
  469.                         new_value = -1
  470.                
  471.                 if new_value != AR[fen]:
  472.                     AR[fen] = new_value
  473.                     changed = True
  474.  
  475.     total_time = time.time() - start_time
  476.     print(f"\nCelkový čas výpočtu: {format_time(total_time)}")
  477.  
  478.     return AR
  479.  
  480. def format_time(seconds):
  481.     hours, remainder = divmod(seconds, 3600)
  482.     minutes, seconds = divmod(remainder, 60)
  483.     return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
  484.  
  485. def simplify_fen_string(fen):
  486.     parts = fen.split(' ')
  487.     return ' '.join(parts[:4])
  488.  
  489. if __name__ == "__main__":
  490.     start_fen = "8/3k4/8/8/8/8/A7/6K1 w - - 0 1"
  491.     AR = calculate_optimal_moves(start_fen)
  492.  
  493.     # Výpis výsledků
  494.     for fen, hodnota in AR.items():
  495.         F = F + 1
  496.         if F < 50 or hodnota != 0:
  497.             print(f"FEN: {fen}")
  498.             print(f"Hodnota: {hodnota}")
  499.             print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement