Advertisement
max2201111

konecne stavi vlastniho krale k do sachu very good

Jul 9th, 2024
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.80 KB | Science | 0 0
  1. import chess
  2. from typing import Iterator
  3. from chess import Move, BB_ALL, Bitboard
  4.  
  5. AMAZON = 7
  6.  
  7. class CustomBoard(chess.Board):
  8.     def __init__(self, fen=None):
  9.         self.amazons_white = chess.BB_EMPTY
  10.         self.amazons_black = chess.BB_EMPTY
  11.         self.custom_bishops_white = chess.BB_EMPTY
  12.         self.custom_bishops_black = chess.BB_EMPTY
  13.         super().__init__(None)
  14.         if fen:
  15.             self.set_custom_fen(fen)
  16.         print("Šachovnice inicializována")
  17.         self.debug_amazons()
  18.         self.debug_custom_bishops()
  19.  
  20.     def set_custom_fen(self, fen):
  21.         print(f"Nastavování FEN: {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.         print(f"FEN nastaven: {self.fen()}")
  67.  
  68.     def _set_piece_at(self, square, piece_type, color):
  69.         super()._set_piece_at(square, piece_type, color)
  70.         if piece_type is not None:
  71.             if piece_type == AMAZON:
  72.                 if color == chess.WHITE:
  73.                     self.amazons_white |= chess.BB_SQUARES[square]
  74.                 else:
  75.                     self.amazons_black |= chess.BB_SQUARES[square]
  76.                 print(f"Nastavena {'bílá' if color == chess.WHITE else 'černá'} amazonka na {chess.SQUARE_NAMES[square]}")
  77.             elif piece_type == chess.BISHOP:
  78.                 if color == chess.WHITE:
  79.                     self.custom_bishops_white |= chess.BB_SQUARES[square]
  80.                 else:
  81.                     self.custom_bishops_black |= chess.BB_SQUARES[square]
  82.                 print(f"Nastaven {'bílý' if color == chess.WHITE else 'černý'} vlastní střelec na {chess.SQUARE_NAMES[square]}")
  83.         else:
  84.             self.amazons_white &= ~chess.BB_SQUARES[square]
  85.             self.amazons_black &= ~chess.BB_SQUARES[square]
  86.             self.custom_bishops_white &= ~chess.BB_SQUARES[square]
  87.             self.custom_bishops_black &= ~chess.BB_SQUARES[square]
  88.  
  89.     def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
  90.         print("Generování pseudo-legálních tahů...")
  91.         for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
  92.             if self.piece_type_at(move.from_square) not in [AMAZON, chess.BISHOP]:
  93.                 print(f"Standardní pseudo-legální tah: {move}")
  94.                 yield move
  95.  
  96.         our_custom_pieces = (self.custom_bishops_white | self.amazons_white) if self.turn == chess.WHITE else (self.custom_bishops_black | self.amazons_black)
  97.         our_custom_pieces &= from_mask
  98.         for from_square in chess.scan_forward(our_custom_pieces):
  99.             piece_type = self.piece_type_at(from_square)
  100.             if piece_type == AMAZON:
  101.                 attacks = self.amazon_attacks(from_square)
  102.                 piece_name = "amazonky"
  103.             else:
  104.                 attacks = self.bishop_attacks(from_square)
  105.                 piece_name = "vlastního střelce"
  106.            
  107.             print(f"Generování tahů pro {piece_name} na {chess.SQUARE_NAMES[from_square]}")
  108.             valid_moves = attacks & ~self.occupied & to_mask
  109.             for to_square in chess.scan_forward(valid_moves):
  110.                 move = Move(from_square, to_square)
  111.                 print(f"Pseudo-legální tah {piece_name}: {move}")
  112.                 yield move
  113.  
  114.     def amazon_attacks(self, square):
  115.         return self.queen_attacks(square) | self.knight_attacks(square)
  116.  
  117.     def queen_attacks(self, square):
  118.         return self.bishop_attacks(square) | self.rook_attacks(square)
  119.  
  120.     def bishop_attacks(self, square):
  121.         return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
  122.  
  123.     def rook_attacks(self, square):
  124.         return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
  125.                 chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
  126.  
  127.     def knight_attacks(self, square):
  128.         return chess.BB_KNIGHT_ATTACKS[square]
  129.  
  130.     def is_pseudo_legal(self, move):
  131.         print(f"Kontrola pseudo-legality tahu: {move}")
  132.         piece = self.piece_at(move.from_square)
  133.         if not piece or piece.color != self.turn:
  134.             print(f"Tah {move} není pseudo-legální: žádná figura nebo špatná barva")
  135.             return False
  136.        
  137.         if self.is_castling(move):
  138.             print(f"Tah {move} je rošáda")
  139.             return True
  140.  
  141.         if piece.piece_type == AMAZON:
  142.             is_legal = bool(self.amazon_attacks(move.from_square) & chess.BB_SQUARES[move.to_square])
  143.         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])):
  144.             is_legal = bool(self.bishop_attacks(move.from_square) & chess.BB_SQUARES[move.to_square])
  145.         else:
  146.             is_legal = super().is_pseudo_legal(move)
  147.        
  148.         print(f"Tah {move} {'je' if is_legal else 'není'} pseudo-legální")
  149.         return is_legal
  150.  
  151.     def is_legal(self, move):
  152.         print(f"Kontrola legality tahu: {move}")
  153.         if not self.is_pseudo_legal(move):
  154.             print(f"Tah {move} není pseudo-legální")
  155.             return False
  156.        
  157.         # Simulujeme tah bez volání push a pop
  158.         piece = self.piece_at(move.from_square)
  159.         captured_piece = self.piece_at(move.to_square)
  160.        
  161.         self._remove_piece_at(move.from_square)
  162.         self._set_piece_at(move.to_square, piece.piece_type, piece.color)
  163.        
  164.         king_square = self.king(self.turn)
  165.         is_check = self._is_attacked_by(not self.turn, king_square)
  166.        
  167.         # Vracíme pozici do původního stavu
  168.         self._remove_piece_at(move.to_square)
  169.         self._set_piece_at(move.from_square, piece.piece_type, piece.color)
  170.         if captured_piece:
  171.             self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
  172.        
  173.         if is_check:
  174.             print(f"Tah {move} staví vlastního krále do šachu")
  175.         else:
  176.             print(f"Tah {move} je legální")
  177.         return not is_check
  178.  
  179.     def _is_attacked_by(self, color, square):
  180.         if super().is_attacked_by(color, square):
  181.             return True
  182.  
  183.         attackers = self.amazons_white if color == chess.WHITE else self.amazons_black
  184.         for attacker_square in chess.scan_forward(attackers):
  185.             if self.amazon_attacks(attacker_square) & chess.BB_SQUARES[square]:
  186.                 print(f"Pole {chess.SQUARE_NAMES[square]} je napadeno amazonkou na {chess.SQUARE_NAMES[attacker_square]}")
  187.                 return True
  188.  
  189.         return False
  190.  
  191.     def debug_amazons(self):
  192.         print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
  193.         print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
  194.         for square in chess.SQUARES:
  195.             if self.amazons_white & chess.BB_SQUARES[square]:
  196.                 print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
  197.             if self.amazons_black & chess.BB_SQUARES[square]:
  198.                 print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
  199.  
  200.     def debug_custom_bishops(self):
  201.         print(f"Bitboard bílých vlastních střelců: {format(self.custom_bishops_white, '064b')}")
  202.         print(f"Bitboard černých vlastních střelců: {format(self.custom_bishops_black, '064b')}")
  203.         for square in chess.SQUARES:
  204.             if self.custom_bishops_white & chess.BB_SQUARES[square]:
  205.                 print(f"Bílý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  206.             if self.custom_bishops_black & chess.BB_SQUARES[square]:
  207.                 print(f"Černý vlastní střelec na {chess.SQUARE_NAMES[square]}")
  208.  
  209.     def piece_symbol(self, piece):
  210.         if piece is None:
  211.             return '.'
  212.         if piece.piece_type == AMAZON:
  213.             return 'A' if piece.color == chess.WHITE else 'a'
  214.         return chess.PIECE_SYMBOLS[piece.piece_type]
  215.  
  216.     @property
  217.     def legal_moves(self):
  218.         return [move for move in self.generate_pseudo_legal_moves() if self.is_legal(move)]
  219.  
  220.     def __str__(self):
  221.         builder = []
  222.         for square in chess.SQUARES_180:
  223.             piece = self.piece_at(square)
  224.             if (self.amazons_white & chess.BB_SQUARES[square]):
  225.                 symbol = 'A'
  226.             elif (self.amazons_black & chess.BB_SQUARES[square]):
  227.                 symbol = 'a'
  228.             else:
  229.                 symbol = self.piece_symbol(piece) if piece else '.'
  230.             builder.append(symbol)
  231.             if chess.square_file(square) == 7:
  232.                 if square != chess.H1:
  233.                     builder.append('\n')
  234.         return ''.join(builder)
  235.  
  236. if __name__ == "__main__":
  237.     start_fen = "a7/1k6/8/8/1B6/8/A7/6K1 b - - 0 1"
  238.    
  239.     print(f"Vytváření šachovnice s FEN: {start_fen}")
  240.     board = CustomBoard(start_fen)
  241.    
  242.     print("Současná pozice:")
  243.     print(board)
  244.    
  245.     print("Generování legálních tahů pro počáteční pozici...")
  246.     legal_moves = list(board.legal_moves)
  247.     print(f"Počet legálních tahů: {len(legal_moves)}")
  248.    
  249.     print("Legální tahy:")
  250.     for move in legal_moves:
  251.         from_square = chess.SQUARE_NAMES[move.from_square]
  252.         to_square = chess.SQUARE_NAMES[move.to_square]
  253.         piece = board.piece_at(move.from_square)
  254.         print(f"{board.piece_symbol(piece)}: {from_square}-{to_square}")
  255.  
  256.     # Změna tahu na bílého a generování tahů
  257.     board.turn = chess.WHITE
  258.     print("\nGenerování legálních tahů pro bílého:")
  259.     white_legal_moves = list(board.legal_moves)
  260.     print(f"Počet legálních tahů pro bílého: {len(white_legal_moves)}")
  261.    
  262.     print("Legální tahy pro bílého:")
  263.     for move in white_legal_moves:
  264.         from_square = chess.SQUARE_NAMES[move.from_square]
  265.         to_square = chess.SQUARE_NAMES[move.to_square]
  266.         piece = board.piece_at(move.from_square)
  267.         print(f"{board.piece_symbol(piece)}: {from_square}-{to_square}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement