Advertisement
max2201111

OK vlastni kral v sachu aAbBkK ale bez legal moves A

Jul 9th, 2024
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.80 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.         our_custom_pieces = (self.custom_bishops_white | self.amazons_white) if self.turn == chess.WHITE else (self.custom_bishops_black | self.amazons_black)
  89.         our_custom_pieces &= from_mask & our_pieces
  90.         for from_square in chess.scan_forward(our_custom_pieces):
  91.             piece_type = self.piece_type_at(from_square)
  92.             if piece_type == AMAZON:
  93.                 attacks = self.amazon_attacks(from_square)
  94.                 print(f"Cílová pole {'bílé' if self.turn == chess.WHITE else 'černé'} amazonky: {attacks:064b}")
  95.             else:
  96.                 attacks = self.bishop_attacks(from_square)
  97.  
  98.             valid_moves = attacks & ~self.occupied & 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 vlastní figury: {move}")
  102.                 yield move
  103.  
  104.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  105.             if self.piece_type_at(move.from_square) not in [AMAZON, chess.BISHOP]:
  106.                 print(f"Standardní pseudo-legální tah: {move}")
  107.                 yield move
  108.  
  109.     def amazon_attacks(self, square):
  110.         return self.queen_attacks(square) | self.knight_attacks(square)
  111.  
  112.     def queen_attacks(self, square):
  113.         return self.bishop_attacks(square) | self.rook_attacks(square)
  114.  
  115.     def bishop_attacks(self, square):
  116.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  117.  
  118.     def rook_attacks(self, square):
  119.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  120.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  121.  
  122.     def knight_attacks(self, square):
  123.         return chess.BB_KNIGHT_ATTACKS[square]
  124.  
  125.     def is_pseudo_legal(self, move):
  126.         piece = self.piece_at(move.from_square)
  127.         if not piece or piece.color != self.turn:
  128.             return False
  129.  
  130.         if self.is_castling(move):
  131.             return True
  132.  
  133.         if piece.piece_type == AMAZON:
  134.             return bool(self.amazon_attacks(move.from_square) & chess.BB_SQUARES[move.to_square])
  135.         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])):
  136.             return bool(self.bishop_attacks(move.from_square) & chess.BB_SQUARES[move.to_square])
  137.         else:
  138.             return super().is_pseudo_legal(move)
  139.  
  140.     def is_legal(self, move):
  141.         print(f"Kontrola legality tahu: {move}")
  142.         if not self.is_pseudo_legal(move):
  143.             print(f"Tah {move} není pseudo-legální")
  144.             return False
  145.  
  146.         # Simulujeme tah bez volání push a pop
  147.         piece = self.piece_at(move.from_square)
  148.         captured_piece = self.piece_at(move.to_square)
  149.  
  150.         self._remove_piece_at(move.from_square)
  151.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  152.  
  153.         king_square = self.king(self.turn)
  154.         is_check = self._is_attacked_by(not self.turn, king_square)
  155.  
  156.         # Vracíme pozici do původního stavu
  157.         self._remove_piece_at(move.to_square)
  158.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  159.         if captured_piece:
  160.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  161.  
  162.         print(f"Tah {move} {'staví' if is_check else 'nestaví'} vlastního krále do šachu")
  163.         return not is_check
  164.  
  165.     def push(self, move):
  166.         print(f"Provádím tah: {move}")
  167.         if not self.is_legal(move):
  168.             raise ValueError(f"Move {move} is not legal in position {self.fen()}")
  169.  
  170.         piece = self.piece_at(move.from_square)
  171.         captured_piece = self.piece_at(move.to_square)
  172.  
  173.         # Odstranění figury z původní pozice
  174.         self._remove_piece_at(move.from_square)
  175.  
  176.         # Přesunutí figury na novou pozici
  177.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  178.  
  179.         # Aktualizace bitboardů pro vlastní figury
  180.         if piece.piece_type == AMAZON:
  181.             if piece.color == chess.WHITE:
  182.                 self.amazons_white &= ~chess.BB_SQUARES[move.from_square]
  183.                 self.amazons_white |= chess.BB_SQUARES[move.to_square]
  184.             else:
  185.                 self.amazons_black &= ~chess.BB_SQUARES[move.from_square]
  186.                 self.amazons_black |= chess.BB_SQUARES[move.to_square]
  187.         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])):
  188.             if piece.color == chess.WHITE:
  189.                 self.custom_bishops_white &= ~chess.BB_SQUARES[move.from_square]
  190.                 self.custom_bishops_white |= chess.BB_SQUARES[move.to_square]
  191.             else:
  192.                 self.custom_bishops_black &= ~chess.BB_SQUARES[move.from_square]
  193.                 self.custom_bishops_black |= chess.BB_SQUARES[move.to_square]
  194.  
  195.         # Aktualizace turn, fullmove_number a halfmove_clock
  196.         self.turn = not self.turn
  197.         self.fullmove_number += 1 if self.turn == chess.WHITE else 0
  198.         self.halfmove_clock += 1
  199.  
  200.         if captured_piece or piece.piece_type == chess.PAWN:
  201.             self.halfmove_clock = 0
  202.  
  203.         # Uložení tahu do historie
  204.         self.move_stack.append(move)
  205.  
  206.     def pop(self):
  207.         if not self.move_stack:
  208.             print("The move stack is empty.")
  209.             return None
  210.  
  211.         move = self.move_stack.pop()
  212.  
  213.         # Vrácení figury na původní pozici
  214.         piece = self.piece_at(move.to_square)
  215.         self._remove_piece_at(move.to_square)
  216.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  217.  
  218.         # Aktualizace bitboardů pro vlastní figury
  219.         if piece.piece_type == AMAZON:
  220.             if piece.color == chess.WHITE:
  221.                 self.amazons_white &= ~chess.BB_SQUARES[move.to_square]
  222.                 self.amazons_white |= chess.BB_SQUARES[move.from_square]
  223.             else:
  224.                 self.amazons_black &= ~chess.BB_SQUARES[move.to_square]
  225.                 self.amazons_black |= chess.BB_SQUARES[move.from_square]
  226.         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])):
  227.             if piece.color == chess.WHITE:
  228.                 self.custom_bishops_white &= ~chess.BB_SQUARES[move.to_square]
  229.                 self.custom_bishops_white |= chess.BB_SQUARES[move.from_square]
  230.             else:
  231.                 self.custom_bishops_black &= ~chess.BB_SQUARES[move.to_square]
  232.                 self.custom_bishops_black |= chess.BB_SQUARES[move.from_square]
  233.  
  234.         # Obnovení zabrané figury, pokud existovala
  235.         if captured_piece:
  236.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  237.  
  238.         # Aktualizace turn, fullmove_number a halfmove_clock
  239.         self.turn = not self.turn
  240.         self.fullmove_number -= 1 if self.turn == chess.BLACK else 0
  241.  
  242.         return move
  243.  
  244.     def is_check(self):
  245.         king_square = self.king(self.turn)
  246.         if king_square is None:
  247.             return False
  248.  
  249.         return self._is_attacked_by(not self.turn, king_square)
  250.  
  251.     def _is_attacked_by(self, color, square):
  252.         if super().is_attacked_by(color, square):
  253.             return True
  254.  
  255.         attackers = self.amazons_white if color == chess.WHITE else self.amazons_black
  256.         for attacker_square in chess.scan_forward(attackers):
  257.             if self.amazon_attacks(attacker_square) & chess.BB_SQUARES[square]:
  258.                 return True
  259.  
  260.         return False
  261.  
  262.     def debug_amazons(self):
  263.         print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  264.         print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  265.         for square in chess.SQUARES:
  266.             if self.amazons_white & chess.BB_SQUARES[square]:
  267.                 print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  268.             if self.amazons_black & chess.BB_SQUARES[square]:
  269.                 print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  270.  
  271.     def debug_custom_bishops(self):
  272.         print(f"Bitboard bílých vlastních střelců: {format(self.custom_bishops_white, '064b')}")
  273.         print(f"Bitboard černých vlastních střelců: {format(self.custom_bishops_black, '064b')}")
  274.         for square in chess.SQUARES:
  275.             if self.custom_bishops_white & chess.BB_SQUARES[square]:
  276.                 print(f"Bílý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  277.             if self.custom_bishops_black & chess.BB_SQUARES[square]:
  278.                 print(f"Černý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  279.  
  280.     def piece_symbol(self, piece):
  281.         if piece is None:
  282.             return '.'
  283.         if piece.piece_type == AMAZON:
  284.             return 'A' if piece.color == chess.WHITE else 'a'
  285.         return piece.symbol()
  286.  
  287.     def piece_type_at(self, square):
  288.         if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
  289.             return AMAZON
  290.         return super().piece_type_at(square)
  291.  
  292.     def color_at(self, square):
  293.         if self.amazons_white & chess.BB_SQUARES[square]:
  294.             return chess.WHITE
  295.         if self.amazons_black & chess.BB_SQUARES[square]:
  296.             return chess.BLACK
  297.         return super().color_at(square)
  298.  
  299.     @property
  300.     def legal_moves(self):
  301.         legal_moves = [move for move in self.generate_pseudo_legal_moves() if self.is_legal(move)]
  302.         for move in legal_moves:
  303.             piece = self.piece_at(move.from_square)
  304.             print(f"Legální tah: {move}")
  305.             if piece.piece_type == AMAZON:
  306.                 print(f"Legální tah amazonky {'A' if piece.color == chess.WHITE else 'a'}: {move}")
  307.         return legal_moves
  308.  
  309.     def __str__(self):
  310.         builder = []
  311.         for square in chess.SQUARES_180:
  312.             piece = self.piece_at(square)
  313.             if (self.amazons_white & chess.BB_SQUARES[square]):
  314.                 symbol = 'A'
  315.             elif (self.amazons_black & chess.BB_SQUARES[square]):
  316.                 symbol = 'a'
  317.             else:
  318.                 symbol = self.piece_symbol(piece) if piece else '.'
  319.             builder.append(symbol)
  320.             if chess.square_file(square) == 7:
  321.                 if square != chess.H1:
  322.                     builder.append('\n')
  323.         return ''.join(builder)
  324.  
  325. if __name__ == "__main__":
  326.     start_fen = "a7/3k4/8/8/1B6/8/A7/6K1 w - - 0 1"
  327.  
  328.     print(f"Vytváření šachovnice s FEN: {start_fen}")
  329.     board = CustomBoard(start_fen)
  330.  
  331.     print("Současná pozice:")
  332.     print(board)
  333.  
  334.     print("Generování legálních tahů pro počáteční pozici...")
  335.     legal_moves = list(board.legal_moves)
  336.     print(f"Počet legálních tahů: {len(legal_moves)}")
  337.  
  338.     print("Legální tahy:")
  339.     for move in legal_moves:
  340.         from_square = chess.SQUARE_NAMES[move.from_square]
  341.         to_square = chess.SQUARE_NAMES[move.to_square]
  342.         piece = board.piece_at(move.from_square)
  343.         print(f"{board.piece_symbol(piece)}: {from_square}-{to_square}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement