Advertisement
max2201111

konecne kontrola PSEUDO_LEGALITY aA

Jul 9th, 2024
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.10 KB | Science | 0 0
  1. import chess
  2. from typing import Iterator
  3. from chess import Move, BB_ALL, Bitboard
  4.  
  5. # Definice nových figur
  6. AMAZON = 7
  7.  
  8. class CustomBoard(chess.Board):
  9.     def __init__(self, fen=None):
  10.         self.amazons_white = chess.BB_EMPTY
  11.         self.amazons_black = chess.BB_EMPTY
  12.         self.custom_bishops_white = chess.BB_EMPTY
  13.         self.custom_bishops_black = chess.BB_EMPTY
  14.         super().__init__(None)
  15.         if fen:
  16.             self.set_custom_fen(fen)
  17.         print("Šachovnice inicializována")
  18.         self.debug_amazons()
  19.         self.debug_custom_bishops()
  20.  
  21.     def set_custom_fen(self, fen):
  22.         parts = fen.split()
  23.         board_part = parts[0]
  24.  
  25.         self.clear()
  26.         self.amazons_white = chess.BB_EMPTY
  27.         self.amazons_black = chess.BB_EMPTY
  28.         self.custom_bishops_white = chess.BB_EMPTY
  29.         self.custom_bishops_black = chess.BB_EMPTY
  30.  
  31.         square = 56
  32.         for c in board_part:
  33.             if c == '/':
  34.                 square -= 16
  35.             elif c.isdigit():
  36.                 square += int(c)
  37.             else:
  38.                 color = chess.WHITE if c.isupper() else chess.BLACK
  39.                 if c.upper() == 'A':
  40.                     if color == chess.WHITE:
  41.                         self.amazons_white |= chess.BB_SQUARES[square]
  42.                     else:
  43.                         self.amazons_black |= chess.BB_SQUARES[square]
  44.                     piece_type = AMAZON
  45.                 elif c.upper() == 'B':
  46.                     if color == chess.WHITE:
  47.                         self.custom_bishops_white |= chess.BB_SQUARES[square]
  48.                     else:
  49.                         self.custom_bishops_black |= chess.BB_SQUARES[square]
  50.                     piece_type = chess.BISHOP
  51.                 else:
  52.                     piece_type = chess.PIECE_SYMBOLS.index(c.lower())
  53.                 self._set_piece_at(square, piece_type, color)
  54.                 square += 1
  55.  
  56.         self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
  57.         self.castling_rights = chess.BB_EMPTY
  58.         if '-' not in parts[2]:
  59.             if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
  60.             if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
  61.             if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
  62.             if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
  63.         self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
  64.         self.halfmove_clock = int(parts[4])
  65.         self.fullmove_number = int(parts[5])
  66.  
  67.     def _set_piece_at(self, square, piece_type, color):
  68.         super()._set_piece_at(square, piece_type, color)
  69.         if piece_type is not None:
  70.             if piece_type == AMAZON:
  71.                 if color == chess.WHITE:
  72.                     self.amazons_white |= chess.BB_SQUARES[square]
  73.                 else:
  74.                     self.amazons_black |= chess.BB_SQUARES[square]
  75.             elif piece_type == chess.BISHOP:
  76.                 if color == chess.WHITE:
  77.                     self.custom_bishops_white |= chess.BB_SQUARES[square]
  78.                 else:
  79.                     self.custom_bishops_black |= chess.BB_SQUARES[square]
  80.         else:
  81.             self.amazons_white &= ~chess.BB_SQUARES[square]
  82.             self.amazons_black &= ~chess.BB_SQUARES[square]
  83.             self.custom_bishops_white &= ~chess.BB_SQUARES[square]
  84.             self.custom_bishops_black &= ~chess.BB_SQUARES[square]
  85.  
  86.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  87.         our_pieces = self.occupied_co[self.turn]
  88.         if self.turn == chess.WHITE:
  89.             our_amazons = self.amazons_white
  90.             our_custom_bishops = self.custom_bishops_white
  91.         else:
  92.             our_amazons = self.amazons_black
  93.             our_custom_bishops = self.custom_bishops_black
  94.  
  95.         # Generujeme tahy pro amazonky
  96.         for from_square in chess.scan_forward(our_amazons & from_mask):
  97.             attacks = self.amazon_attacks(from_square)
  98.             valid_moves = attacks & ~our_pieces & to_mask
  99.             for to_square in chess.scan_forward(valid_moves):
  100.                 move = Move(from_square, to_square)
  101.                 print(f"Pseudo-legální tah amazonky: {move}")
  102.                 yield move
  103.  
  104.         # Generujeme tahy pro vlastní střelce
  105.         for from_square in chess.scan_forward(our_custom_bishops & from_mask):
  106.             attacks = self.bishop_attacks(from_square)
  107.             valid_moves = attacks & ~our_pieces & to_mask
  108.             for to_square in chess.scan_forward(valid_moves):
  109.                 move = Move(from_square, to_square)
  110.                 print(f"Pseudo-legální tah vlastního střelce: {move}")
  111.                 yield move
  112.  
  113.         # Generujeme standardní tahy pro ostatní figury
  114.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  115.             if self.piece_type_at(move.from_square) not in [AMAZON, chess.BISHOP]:
  116.                 print(f"Standardní pseudo-legální tah: {move}")
  117.                 yield move
  118.  
  119.     def amazon_attacks(self, square):
  120.         return self.queen_attacks(square) | self.knight_attacks(square)
  121.  
  122.     def queen_attacks(self, square):
  123.         return self.bishop_attacks(square) | self.rook_attacks(square)
  124.  
  125.     def bishop_attacks(self, square):
  126.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  127.  
  128.     def rook_attacks(self, square):
  129.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  130.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  131.  
  132.     def knight_attacks(self, square):
  133.         return chess.BB_KNIGHT_ATTACKS[square]
  134.  
  135.     def is_pseudo_legal(self, move):
  136.         piece = self.piece_at(move.from_square)
  137.         if not piece or piece.color != self.turn:
  138.             return False
  139.  
  140.         if self.is_castling(move):
  141.             return True
  142.  
  143.         if piece.piece_type == AMAZON:
  144.             return bool(self.amazon_attacks(move.from_square) & chess.BB_SQUARES[move.to_square])
  145.         elif piece.piece_type == chess.BISHOP and ((self.custom_bishops_white & chess.BB_SQUARES[move.from_square]) or (self.custom_bishops_black & chess.BB_SQUARES[move.from_square])):
  146.             return bool(self.bishop_attacks(move.from_square) & chess.BB_SQUARES[move.to_square])
  147.         else:
  148.             return super().is_pseudo_legal(move)
  149.  
  150.     def is_legal(self, move):
  151.         print(f"Kontrola legality tahu: {move}")
  152.         if not self.is_pseudo_legal(move):
  153.             print(f"Tah {move} není pseudo-legální")
  154.             return False
  155.  
  156.         # Simulujeme tah bez volání push a pop
  157.         piece = self.piece_at(move.from_square)
  158.         captured_piece = self.piece_at(move.to_square)
  159.  
  160.         self._remove_piece_at(move.from_square)
  161.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  162.  
  163.         king_square = self.king(self.turn)
  164.         is_check = self._is_attacked_by(not self.turn, king_square)
  165.  
  166.         # Vracíme pozici do původního stavu
  167.         self._remove_piece_at(move.to_square)
  168.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  169.         if captured_piece:
  170.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  171.  
  172.         print(f"Tah {move} {'staví' if is_check else 'nestaví'} vlastního krále do šachu")
  173.         return not is_check
  174.  
  175.     def push(self, move):
  176.         print(f"Provádím tah: {move}")
  177.         if not self.is_legal(move):
  178.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  179.  
  180.         piece = self.piece_at(move.from_square)
  181.         captured_piece = self.piece_at(move.to_square)
  182.  
  183.         # Odstranění figury z původní pozice
  184.         self._remove_piece_at(move.from_square)
  185.  
  186.         # Přesunutí figury na novou pozici
  187.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  188.  
  189.         # Aktualizace bitboardů pro vlastní figury
  190.         if piece.piece_type == AMAZON:
  191.             if piece.color == chess.WHITE:
  192.                 self.amazons_white &= ~chess.BB_SQUARES[move.from_square]
  193.                 self.amazons_white |= chess.BB_SQUARES[move.to_square]
  194.             else:
  195.                 self.amazons_black &= ~chess.BB_SQUARES[move.from_square]
  196.                 self.amazons_black |= chess.BB_SQUARES[move.to_square]
  197.         elif piece.piece_type == chess.BISHOP and ((self.custom_bishops_white & chess.BB_SQUARES[move.from_square]) or (self.custom_bishops_black & chess.BB_SQUARES[move.from_square])):
  198.             if piece.color == chess.WHITE:
  199.                 self.custom_bishops_white &= ~chess.BB_SQUARES[move.from_square]
  200.                 self.custom_bishops_white |= chess.BB_SQUARES[move.to_square]
  201.             else:
  202.                 self.custom_bishops_black &= ~chess.BB_SQUARES[move.from_square]
  203.                 self.custom_bishops_black |= chess.BB_SQUARES[move.to_square]
  204.  
  205.         # Aktualizace turn, fullmove_number a halfmove_clock
  206.         self.turn = not self.turn
  207.         self.fullmove_number += 1 if self.turn == chess.WHITE else 0
  208.         self.halfmove_clock += 1
  209.  
  210.         if captured_piece or piece.piece_type == chess.PAWN:
  211.             self.halfmove_clock = 0
  212.  
  213.         # Uložení tahu do historie
  214.         self.move_stack.append(move)
  215.  
  216.     def pop(self):
  217.         if not self.move_stack:
  218.             print("The move stack is empty.")
  219.             return None
  220.  
  221.         move = self.move_stack.pop()
  222.  
  223.         # Vrácení figury na původní pozici
  224.         piece = self.piece_at(move.to_square)
  225.         self._remove_piece_at(move.to_square)
  226.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  227.  
  228.         # Aktualizace bitboardů pro vlastní figury
  229.         if piece.piece_type == AMAZON:
  230.             if piece.color == chess.WHITE:
  231.                 self.amazons_white &= ~chess.BB_SQUARES[move.to_square]
  232.                 self.amazons_white |= chess.BB_SQUARES[move.from_square]
  233.             else:
  234.                 self.amazons_black &= ~chess.BB_SQUARES[move.to_square]
  235.                 self.amazons_black |= chess.BB_SQUARES[move.from_square]
  236.         elif piece.piece_type == chess.BISHOP and ((self.custom_bishops_white & chess.BB_SQUARES[move.to_square]) or (self.custom_bishops_black & chess.BB_SQUARES[move.to_square])):
  237.             if piece.color == chess.WHITE:
  238.                 self.custom_bishops_white &= ~chess.BB_SQUARES[move.to_square]
  239.                 self.custom_bishops_white |= chess.BB_SQUARES[move.from_square]
  240.             else:
  241.                 self.custom_bishops_black &= ~chess.BB_SQUARES[move.to_square]
  242.                 self.custom_bishops_black |= chess.BB_SQUARES[move.from_square]
  243.  
  244.         # Obnovení zabrané figury, pokud existovala
  245.         if captured_piece:
  246.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  247.  
  248.         # Aktualizace turn, fullmove_number a halfmove_clock
  249.         self.turn = not self.turn
  250.         self.fullmove_number -= 1 if self.turn == chess.BLACK else 0
  251.  
  252.         return move
  253.  
  254.     def is_check(self):
  255.         king_square = self.king(self.turn)
  256.         if king_square is None:
  257.             return False
  258.  
  259.         return self._is_attacked_by(not self.turn, king_square)
  260.  
  261.     def _is_attacked_by(self, color, square):
  262.         if super().is_attacked_by(color, square):
  263.             return True
  264.  
  265.         attackers = self.amazons_white if color == chess.WHITE else self.amazons_black
  266.         for attacker_square in chess.scan_forward(attackers):
  267.             if self.amazon_attacks(attacker_square) & chess.BB_SQUARES[square]:
  268.                 return True
  269.  
  270.         return False
  271.  
  272.     def debug_amazons(self):
  273.         print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  274.         print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  275.         for square in chess.SQUARES:
  276.             if self.amazons_white & chess.BB_SQUARES[square]:
  277.                 print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  278.             if self.amazons_black & chess.BB_SQUARES[square]:
  279.                 print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  280.  
  281.     def debug_custom_bishops(self):
  282.         print(f"Bitboard bílých vlastních střelců: {format(self.custom_bishops_white, '064b')}")
  283.         print(f"Bitboard černých vlastních střelců: {format(self.custom_bishops_black, '064b')}")
  284.         for square in chess.SQUARES:
  285.             if self.custom_bishops_white & chess.BB_SQUARES[square]:
  286.                 print(f"Bílý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  287.             if self.custom_bishops_black & chess.BB_SQUARES[square]:
  288.                 print(f"Černý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  289.  
  290.     def piece_symbol(self, piece):
  291.         if piece is None:
  292.             return '.'
  293.         if piece.piece_type == AMAZON:
  294.             return 'A' if piece.color == chess.WHITE else 'a'
  295.         return piece.symbol()
  296.  
  297.     def piece_type_at(self, square):
  298.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  299.             return AMAZON
  300.         return super().piece_type_at(square)
  301.  
  302.     def color_at(self, square):
  303.         if self.amazons_white & chess.BB_SQUARES[square]:
  304.             return chess.WHITE
  305.         if self.amazons_black & chess.BB_SQUARES[square]:
  306.             return chess.BLACK
  307.         return super().color_at(square)
  308.  
  309.     @property
  310.     def legal_moves(self):
  311.         legal_moves = [move for move in self.generate_pseudo_legal_moves() if self.is_legal(move)]
  312.         for move in legal_moves:
  313.             piece = self.piece_at(move.from_square)
  314.             print(f"Legální tah: {move}")
  315.             if piece.piece_type == AMAZON:
  316.                 print(f"Legální tah amazonky {'A' if piece.color == chess.WHITE else 'a'}: {move}")
  317.         return legal_moves
  318.  
  319.     def __str__(self):
  320.         builder = []
  321.         for square in chess.SQUARES_180:
  322.             piece = self.piece_at(square)
  323.             if (self.amazons_white & chess.BB_SQUARES[square]):
  324.                 symbol = 'A'
  325.             elif (self.amazons_black & chess.BB_SQUARES[square]):
  326.                 symbol = 'a'
  327.             else:
  328.                 symbol = self.piece_symbol(piece) if piece else '.'
  329.             builder.append(symbol)
  330.             if chess.square_file(square) == 7:
  331.                 if square != chess.H1:
  332.                     builder.append('\n')
  333.         return ''.join(builder)
  334.  
  335. if __name__ == "__main__":
  336.     start_fen = "a7/3k4/8/8/1B6/8/A7/6K1 w - - 0 1"
  337.  
  338.     print(f"Vytváření šachovnice s FEN: {start_fen}")
  339.     board = CustomBoard(start_fen)
  340.  
  341.     print("Současná pozice:")
  342.     print(board)
  343.  
  344.     print("Generování legálních tahů pro počáteční pozici...")
  345.     legal_moves = list(board.legal_moves)
  346.     print(f"Počet legálních tahů: {len(legal_moves)}")
  347.  
  348.     print("Legální tahy:")
  349.     for move in legal_moves:
  350.         from_square = chess.SQUARE_NAMES[move.from_square]
  351.         to_square = chess.SQUARE_NAMES[move.to_square]
  352.         piece = board.piece_at(move.from_square)
  353.         print(f"{board.piece_symbol(piece)}: {from_square}-{to_square}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement