Advertisement
max2201111

vice kralu K v legal tazich Dobre

Jul 9th, 2024
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.74 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.         from_square = move.from_square
  137.         to_square = move.to_square
  138.         piece = self.piece_at(from_square)
  139.        
  140.         print(f"Kontrola pseudo-legality tahu: {move}")
  141.         print(f"Figura na {chess.SQUARE_NAMES[from_square]}: {self.piece_symbol(piece)}")
  142.         print(f"Barva na tahu: {'bílá' if self.turn == chess.WHITE else 'černá'}")
  143.        
  144.         if not piece:
  145.             print("Na výchozím poli není žádná figura")
  146.             return False
  147.  
  148.         piece_color = self.color_at(from_square)
  149.  
  150.         if piece_color != self.turn:
  151.             print("Figura není barvy hráče na tahu")
  152.             return False
  153.  
  154.         if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
  155.             print("Cílové pole je obsazeno vlastní figurou")
  156.             return False
  157.  
  158.         if self.is_castling(move):
  159.             print("Tah je rošáda")
  160.             return True
  161.  
  162.         if piece.piece_type == AMAZON:
  163.             print("Figura je amazonka")
  164.             attacks = self.amazon_attacks(from_square)
  165.             is_valid = bool(attacks & chess.BB_SQUARES[to_square])
  166.             print(f"Cílové pole {chess.SQUARE_NAMES[to_square]}: {'platné' if is_valid else 'neplatné'}")
  167.             return is_valid
  168.         elif piece.piece_type == chess.BISHOP and ((self.custom_bishops_white & chess.BB_SQUARES[from_square]) or (self.custom_bishops_black & chess.BB_SQUARES[from_square])):
  169.             print("Figura je vlastní střelec")
  170.             return bool(self.bishop_attacks(from_square) & chess.BB_SQUARES[to_square])
  171.         else:
  172.             print("Kontrola standardní pseudo-legality")
  173.             return super().is_pseudo_legal(move)
  174.  
  175.     def is_legal(self, move):
  176.         print(f"Kontrola legality tahu: {move}")
  177.         if not self.is_pseudo_legal(move):
  178.             print(f"Tah {move} není pseudo-legální")
  179.             return False
  180.  
  181.         # Simulujeme tah bez volání push a pop
  182.         from_square = move.from_square
  183.         to_square = move.to_square
  184.         piece = self.piece_at(from_square)
  185.         captured_piece = self.piece_at(to_square)
  186.  
  187.         # Speciální kontrola pro amazonku
  188.         if piece.piece_type == AMAZON:
  189.             if self.amazons_white & chess.BB_SQUARES[from_square]:
  190.                 piece_color = chess.WHITE
  191.             elif self.amazons_black & chess.BB_SQUARES[from_square]:
  192.                 piece_color = chess.BLACK
  193.             else:
  194.                 piece_color = piece.color
  195.         else:
  196.             piece_color = piece.color
  197.  
  198.         self._remove_piece_at(from_square)
  199.         self._set_piece_at(to_square, piece.piece_type, piece_color)
  200.  
  201.         king_square = self.king(self.turn)
  202.         is_check, attacker_square = self._is_attacked_by(not self.turn, king_square)
  203.  
  204.         # Vracíme pozici do původního stavu
  205.         self._remove_piece_at(to_square)
  206.         self._set_piece_at(from_square, piece.piece_type, piece_color)
  207.         if captured_piece:
  208.             self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
  209.  
  210.         if is_check:
  211.             attacking_piece = self.piece_at(attacker_square)
  212.             print(f"Tah {move} staví vlastního krále do šachu od figury {self.piece_symbol(attacking_piece)} na {chess.SQUARE_NAMES[attacker_square]}")
  213.         else:
  214.             print(f"Tah {move} nestaví vlastního krále do šachu")
  215.         return not is_check
  216.  
  217.  
  218.    
  219.     def push(self, move):
  220.         print(f"Provádím tah: {move}")
  221.         if not self.is_legal(move):
  222.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  223.  
  224.         piece = self.piece_at(move.from_square)
  225.         captured_piece = self.piece_at(move.to_square)
  226.  
  227.         # Odstranění figury z původní pozice
  228.         self._remove_piece_at(move.from_square)
  229.  
  230.         # Přesunutí figury na novou pozici
  231.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  232.  
  233.         # Aktualizace bitboardů pro vlastní figury
  234.         if piece.piece_type == AMAZON:
  235.             if piece.color == chess.WHITE:
  236.                 self.amazons_white &= ~chess.BB_SQUARES[move.from_square]
  237.                 self.amazons_white |= chess.BB_SQUARES[move.to_square]
  238.             else:
  239.                 self.amazons_black &= ~chess.BB_SQUARES[move.from_square]
  240.                 self.amazons_black |= chess.BB_SQUARES[move.to_square]
  241.         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])):
  242.             if piece.color == chess.WHITE:
  243.                 self.custom_bishops_white &= ~chess.BB_SQUARES[move.from_square]
  244.                 self.custom_bishops_white |= chess.BB_SQUARES[move.to_square]
  245.             else:
  246.                 self.custom_bishops_black &= ~chess.BB_SQUARES[move.from_square]
  247.                 self.custom_bishops_black |= chess.BB_SQUARES[move.to_square]
  248.  
  249.         # Aktualizace turn, fullmove_number a halfmove_clock
  250.         self.turn = not self.turn
  251.         self.fullmove_number += 1 if self.turn == chess.WHITE else 0
  252.         self.halfmove_clock += 1
  253.  
  254.         if captured_piece or piece.piece_type == chess.PAWN:
  255.             self.halfmove_clock = 0
  256.  
  257.         # Uložení tahu do historie
  258.         self.move_stack.append(move)
  259.  
  260.     def pop(self):
  261.         if not self.move_stack:
  262.             print("The move stack is empty.")
  263.             return None
  264.  
  265.         move = self.move_stack.pop()
  266.  
  267.         # Vrácení figury na původní pozici
  268.         piece = self.piece_at(move.to_square)
  269.         self._remove_piece_at(move.to_square)
  270.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  271.  
  272.         # Aktualizace bitboardů pro vlastní figury
  273.         if piece.piece_type == AMAZON:
  274.             if piece.color == chess.WHITE:
  275.                 self.amazons_white &= ~chess.BB_SQUARES[move.to_square]
  276.                 self.amazons_white |= chess.BB_SQUARES[move.from_square]
  277.             else:
  278.                 self.amazons_black &= ~chess.BB_SQUARES[move.to_square]
  279.                 self.amazons_black |= chess.BB_SQUARES[move.from_square]
  280.         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])):
  281.             if piece.color == chess.WHITE:
  282.                 self.custom_bishops_white &= ~chess.BB_SQUARES[move.to_square]
  283.                 self.custom_bishops_white |= chess.BB_SQUARES[move.from_square]
  284.             else:
  285.                 self.custom_bishops_black &= ~chess.BB_SQUARES[move.to_square]
  286.                 self.custom_bishops_black |= chess.BB_SQUARES[move.from_square]
  287.  
  288.         # Obnovení zabrané figury, pokud existovala
  289.         if captured_piece:
  290.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  291.  
  292.         # Aktualizace turn, fullmove_number a halfmove_clock
  293.         self.turn = not self.turn
  294.         self.fullmove_number -= 1 if self.turn == chess.BLACK else 0
  295.  
  296.         return move
  297.  
  298.     def is_check(self):
  299.         king_square = self.king(self.turn)
  300.         if king_square is None:
  301.             return False
  302.  
  303.         is_check, _ = self._is_attacked_by(not self.turn, king_square)
  304.         return is_check
  305.  
  306.     def _is_attacked_by(self, color, square):
  307.         if self.is_attacked_by(color, square):
  308.             attackers = self.attackers(color, square)
  309.             attacking_square = attackers.pop() if attackers else None
  310.             return True, attacking_square
  311.         return False, None
  312.  
  313.  
  314.     def debug_amazons(self):
  315.         print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  316.         print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  317.         for square in chess.SQUARES:
  318.             if self.amazons_white & chess.BB_SQUARES[square]:
  319.                 print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  320.             if self.amazons_black & chess.BB_SQUARES[square]:
  321.                 print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  322.  
  323.     def debug_custom_bishops(self):
  324.         print(f"Bitboard bílých vlastních střelců: {format(self.custom_bishops_white, '064b')}")
  325.         print(f"Bitboard černých vlastních střelců: {format(self.custom_bishops_black, '064b')}")
  326.         for square in chess.SQUARES:
  327.             if self.custom_bishops_white & chess.BB_SQUARES[square]:
  328.                 print(f"Bílý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  329.             if self.custom_bishops_black & chess.BB_SQUARES[square]:
  330.                 print(f"Černý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  331.  
  332.     def piece_symbol(self, piece):
  333.         if piece is None:
  334.             return '.'
  335.         if piece.piece_type == AMAZON:
  336.             return 'A' if piece.color == chess.WHITE else 'a'
  337.         return piece.symbol()
  338.  
  339.     def piece_type_at(self, square):
  340.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  341.             return AMAZON
  342.         return super().piece_type_at(square)
  343.  
  344.     def color_at(self, square):
  345.         if self.amazons_white & chess.BB_SQUARES[square]:
  346.             return chess.WHITE
  347.         if self.amazons_black & chess.BB_SQUARES[square]:
  348.             return chess.BLACK
  349.         return super().color_at(square)
  350.  
  351.     @property
  352.     def legal_moves(self):
  353.         legal_moves = [move for move in self.generate_pseudo_legal_moves() if self.is_legal(move)]
  354.         for move in legal_moves:
  355.             piece = self.piece_at(move.from_square)
  356.             print(f"Legální tah: {move}")
  357.             if piece.piece_type == AMAZON:
  358.                 print(f"Legální tah amazonky {'A' if piece.color == chess.WHITE else 'a'}: {move}")
  359.         return legal_moves
  360.  
  361.     def __str__(self):
  362.         builder = []
  363.         for square in chess.SQUARES_180:
  364.             piece = self.piece_at(square)
  365.             if (self.amazons_white & chess.BB_SQUARES[square]):
  366.                 symbol = 'A'
  367.             elif (self.amazons_black & chess.BB_SQUARES[square]):
  368.                 symbol = 'a'
  369.             else:
  370.                 symbol = self.piece_symbol(piece) if piece else '.'
  371.             builder.append(symbol)
  372.             if chess.square_file(square) == 7:
  373.                 if square != chess.H1:
  374.                     builder.append('\n')
  375.         return ''.join(builder)
  376.  
  377. if __name__ == "__main__":
  378.     start_fen = "a7/3k4/8/8/1B6/8/A7/6K1 w - - 0 1"
  379.  
  380.     print(f"Vytváření šachovnice s FEN: {start_fen}")
  381.     board = CustomBoard(start_fen)
  382.  
  383.     print("Současná pozice:")
  384.     print(board)
  385.  
  386.     print("Generování legálních tahů pro počáteční pozici...")
  387.     legal_moves = list(board.legal_moves)
  388.     print(f"Počet legálních tahů: {len(legal_moves)}")
  389.  
  390.     print("Legální tahy:")
  391.     for move in legal_moves:
  392.         from_square = chess.SQUARE_NAMES[move.from_square]
  393.         to_square = chess.SQUARE_NAMES[move.to_square]
  394.         piece = board.piece_at(move.from_square)
  395.         print(f"{board.piece_symbol(piece)}: {from_square}-{to_square}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement