Advertisement
max2201111

K bez sachu od a!!konecne

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