Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Import knihovny chess a dalších potřebných modulů
- import chess
- from typing import Iterator, Optional, Dict, Tuple
- from chess import Move, BB_ALL, Bitboard, PieceType, Color
- import time
- from collections import deque
- import threading
- # Definice nových figur
- AMAZON = 7
- CYRIL = 8
- EVE = 9
- # Rozšíření seznamu PIECE_SYMBOLS
- chess.PIECE_SYMBOLS.append('a')
- chess.PIECE_SYMBOLS.append('c')
- chess.PIECE_SYMBOLS.append('e')
- class CustomBoard(chess.Board):
- def __init__(self, fen=None):
- self.amazons_white = chess.BB_EMPTY
- self.amazons_black = chess.BB_EMPTY
- self.cyrils_white = chess.BB_EMPTY
- self.cyrils_black = chess.BB_EMPTY
- self.eves_white = chess.BB_EMPTY
- self.eves_black = chess.BB_EMPTY
- super().__init__(None)
- if fen:
- self.set_custom_fen(fen)
- # print("Šachovnice inicializována")
- self.debug_amazons()
- self.debug_cyrils()
- self.debug_eves()
- def clear_square(self, square):
- super()._remove_piece_at(square)
- self.amazons_white &= ~chess.BB_SQUARES[square]
- self.amazons_black &= ~chess.BB_SQUARES[square]
- self.cyrils_white &= ~chess.BB_SQUARES[square]
- self.cyrils_black &= ~chess.BB_SQUARES[square]
- self.eves_white &= ~chess.BB_SQUARES[square]
- self.eves_black &= ~chess.BB_SQUARES[square]
- def set_custom_fen(self, fen):
- parts = fen.split()
- board_part = parts[0]
- self.clear()
- self.amazons_white = chess.BB_EMPTY
- self.amazons_black = chess.BB_EMPTY
- self.cyrils_white = chess.BB_EMPTY
- self.cyrils_black = chess.BB_EMPTY
- self.eves_white = chess.BB_EMPTY
- self.eves_black = chess.BB_EMPTY
- square = 56
- for c in board_part:
- if c == '/':
- square -= 16
- elif c.isdigit():
- square += int(c)
- else:
- color = chess.WHITE if c.isupper() else chess.BLACK
- if c.upper() == 'A':
- if color == chess.WHITE:
- self.amazons_white |= chess.BB_SQUARES[square]
- else:
- self.amazons_black |= chess.BB_SQUARES[square]
- piece_type = AMAZON
- elif c.upper() == 'C':
- if color == chess.WHITE:
- self.cyrils_white |= chess.BB_SQUARES[square]
- else:
- self.cyrils_black |= chess.BB_SQUARES[square]
- piece_type = CYRIL
- elif c.upper() == 'E':
- if color == chess.WHITE:
- self.eves_white |= chess.BB_SQUARES[square]
- else:
- self.eves_black |= chess.BB_SQUARES[square]
- piece_type = EVE
- else:
- piece_type = chess.PIECE_SYMBOLS.index(c.lower())
- self._set_piece_at(square, piece_type, color)
- square += 1
- self.turn = chess.WHITE if parts[1] == 'w' else chess.BLACK
- self.castling_rights = chess.BB_EMPTY
- if '-' not in parts[2]:
- if 'K' in parts[2]: self.castling_rights |= chess.BB_H1
- if 'Q' in parts[2]: self.castling_rights |= chess.BB_A1
- if 'k' in parts[2]: self.castling_rights |= chess.BB_H8
- if 'q' in parts[2]: self.castling_rights |= chess.BB_A8
- self.ep_square = chess.parse_square(parts[3]) if parts[3] != '-' else None
- def _set_piece_at(self, square: chess.Square, piece_type: PieceType, color: Color) -> None:
- self.clear_square(square)
- super()._set_piece_at(square, piece_type, color)
- if piece_type == AMAZON:
- if color == chess.WHITE:
- self.amazons_white |= chess.BB_SQUARES[square]
- else:
- self.amazons_black |= chess.BB_SQUARES[square]
- elif piece_type == CYRIL:
- if color == chess.WHITE:
- self.cyrils_white |= chess.BB_SQUARES[square]
- else:
- self.cyrils_black |= chess.BB_SQUARES[square]
- elif piece_type == EVE:
- if color == chess.WHITE:
- self.eves_white |= chess.BB_SQUARES[square]
- else:
- self.eves_black |= chess.BB_SQUARES[square]
- def piece_at(self, square: chess.Square) -> Optional[chess.Piece]:
- if self.amazons_white & chess.BB_SQUARES[square]:
- return chess.Piece(AMAZON, chess.WHITE)
- elif self.amazons_black & chess.BB_SQUARES[square]:
- return chess.Piece(AMAZON, chess.BLACK)
- elif self.cyrils_white & chess.BB_SQUARES[square]:
- return chess.Piece(CYRIL, chess.WHITE)
- elif self.cyrils_black & chess.BB_SQUARES[square]:
- return chess.Piece(CYRIL, chess.BLACK)
- elif self.eves_white & chess.BB_SQUARES[square]:
- return chess.Piece(EVE, chess.WHITE)
- elif self.eves_black & chess.BB_SQUARES[square]:
- return chess.Piece(EVE, chess.BLACK)
- return super().piece_at(square)
- def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]:
- our_pieces = self.occupied_co[self.turn]
- if self.turn == chess.WHITE:
- our_amazons = self.amazons_white
- our_cyrils = self.cyrils_white
- our_eves = self.eves_white
- else:
- our_amazons = self.amazons_black
- our_cyrils = self.cyrils_black
- our_eves = self.eves_black
- # Generování tahů pro amazonky
- for from_square in chess.scan_forward(our_amazons & from_mask):
- attacks = self.amazon_attacks(from_square)
- valid_moves = attacks & ~our_pieces & to_mask
- for to_square in chess.scan_forward(valid_moves):
- yield Move(from_square, to_square)
- # Generování tahů pro Cyrily
- for from_square in chess.scan_forward(our_cyrils & from_mask):
- attacks = self.cyril_attacks(from_square)
- valid_moves = attacks & ~our_pieces & to_mask
- for to_square in chess.scan_forward(valid_moves):
- yield Move(from_square, to_square)
- # Generování tahů pro Evy
- for from_square in chess.scan_forward(our_eves & from_mask):
- attacks = self.eve_attacks(from_square)
- valid_moves = attacks & ~our_pieces & to_mask
- for to_square in chess.scan_forward(valid_moves):
- yield Move(from_square, to_square)
- # Generování tahů pro standardní figury
- for move in super().generate_pseudo_legal_moves(from_mask, to_mask):
- piece = self.piece_at(move.from_square)
- if piece and piece.piece_type not in [AMAZON, CYRIL, EVE]:
- yield move
- def queen_attacks(self, square):
- return self.bishop_attacks(square) | self.rook_attacks(square)
- def bishop_attacks(self, square):
- return chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
- def rook_attacks(self, square):
- return (chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
- chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]])
- def amazon_attacks(self, square):
- return self.queen_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
- def cyril_attacks(self, square):
- return self.rook_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
- def eve_attacks(self, square):
- return self.bishop_attacks(square) | chess.BB_KNIGHT_ATTACKS[square]
- def is_pseudo_legal(self, move):
- from_square = move.from_square
- to_square = move.to_square
- piece = self.piece_at(from_square)
- if not piece or piece.color != self.turn:
- return False
- if self.occupied_co[self.turn] & chess.BB_SQUARES[to_square]:
- return False
- if self.is_castling(move):
- return True
- if piece.piece_type == AMAZON:
- return bool(self.amazon_attacks(from_square) & chess.BB_SQUARES[to_square])
- elif piece.piece_type == CYRIL:
- return bool(self.cyril_attacks(from_square) & chess.BB_SQUARES[to_square])
- elif piece.piece_type == EVE:
- return bool(self.eve_attacks(from_square) & chess.BB_SQUARES[to_square])
- else:
- return super().is_pseudo_legal(move)
- def is_legal(self, move):
- if not self.is_pseudo_legal(move):
- return False
- from_square = move.from_square
- to_square = move.to_square
- piece = self.piece_at(from_square)
- captured_piece = self.piece_at(to_square)
- self.clear_square(from_square)
- self.clear_square(to_square)
- self._set_piece_at(to_square, piece.piece_type, piece.color)
- king_square = to_square if piece.piece_type == chess.KING else self.king(self.turn)
- is_check = self._is_attacked_by(not self.turn, king_square)
- self.clear_square(to_square)
- self._set_piece_at(from_square, piece.piece_type, piece.color)
- if captured_piece:
- self._set_piece_at(to_square, captured_piece.piece_type, captured_piece.color)
- if is_check:
- attackers = self.attackers(not self.turn, king_square)
- # print(f"[DEBUG] King at {chess.SQUARE_NAMES[king_square]} is attacked by pieces at: {[chess.SQUARE_NAMES[sq] for sq in chess.scan_forward(attackers)]}")
- return not is_check
- def _is_attacked_by(self, color, square):
- attackers = self.attackers(color, square)
- return bool(attackers)
- def attackers(self, color, square):
- attackers = chess.BB_EMPTY
- # Knights
- knights = self.knights & self.occupied_co[color]
- if chess.BB_KNIGHT_ATTACKS[square] & knights:
- attackers |= knights & chess.BB_KNIGHT_ATTACKS[square]
- # King
- king = self.kings & self.occupied_co[color]
- if chess.BB_KING_ATTACKS[square] & king:
- attackers |= king
- # Pawns
- pawns = self.pawns & self.occupied_co[color]
- pawn_attacks = chess.BB_PAWN_ATTACKS[not color][square]
- if pawn_attacks & pawns:
- attackers |= pawns & pawn_attacks
- # Queens
- queens = self.queens & self.occupied_co[color]
- queen_attacks = (
- chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]] |
- chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
- chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
- )
- if queen_attacks & queens:
- attackers |= queens & queen_attacks
- # Bishops
- bishops = self.bishops & self.occupied_co[color]
- bishop_attacks = chess.BB_DIAG_ATTACKS[square][self.occupied & chess.BB_DIAG_MASKS[square]]
- if bishop_attacks & bishops:
- attackers |= bishops & bishop_attacks
- # Rooks
- rooks = self.rooks & self.occupied_co[color]
- rook_attacks = (
- chess.BB_RANK_ATTACKS[square][self.occupied & chess.BB_RANK_MASKS[square]] |
- chess.BB_FILE_ATTACKS[square][self.occupied & chess.BB_FILE_MASKS[square]]
- )
- if rook_attacks & rooks:
- attackers |= rooks & rook_attacks
- # Amazons (Queen + Knight)
- amazons = self.amazons_white if color == chess.WHITE else self.amazons_black
- for amazon_square in chess.scan_forward(amazons):
- amazon_attacks = (
- chess.BB_DIAG_ATTACKS[amazon_square][self.occupied & chess.BB_DIAG_MASKS[amazon_square]] |
- chess.BB_RANK_ATTACKS[amazon_square][self.occupied & chess.BB_RANK_MASKS[amazon_square]] |
- chess.BB_FILE_ATTACKS[amazon_square][self.occupied & chess.BB_FILE_MASKS[amazon_square]] |
- chess.BB_KNIGHT_ATTACKS[amazon_square]
- )
- if amazon_attacks & chess.BB_SQUARES[square]:
- attackers |= chess.BB_SQUARES[amazon_square]
- # Cyrils (Rook + Knight)
- cyrils = self.cyrils_white if color == chess.WHITE else self.cyrils_black
- for cyril_square in chess.scan_forward(cyrils):
- cyril_attacks = (
- chess.BB_RANK_ATTACKS[cyril_square][self.occupied & chess.BB_RANK_MASKS[cyril_square]] |
- chess.BB_FILE_ATTACKS[cyril_square][self.occupied & chess.BB_FILE_MASKS[cyril_square]] |
- chess.BB_KNIGHT_ATTACKS[cyril_square]
- )
- if cyril_attacks & chess.BB_SQUARES[square]:
- attackers |= chess.BB_SQUARES[cyril_square]
- # Eves (Bishop + Knight)
- eves = self.eves_white if color == chess.WHITE else self.eves_black
- for eve_square in chess.scan_forward(eves):
- eve_attacks = (
- chess.BB_DIAG_ATTACKS[eve_square][self.occupied & chess.BB_DIAG_MASKS[eve_square]] |
- chess.BB_KNIGHT_ATTACKS[eve_square]
- )
- if eve_attacks & chess.BB_SQUARES[square]:
- attackers |= chess.BB_SQUARES[eve_square]
- return attackers
- def push(self, move):
- if not self.is_legal(move):
- raise ValueError(f"Move {move} is not legal in position {self.fen()}")
- piece = self.piece_at(move.from_square)
- captured_piece = self.piece_at(move.to_square)
- self.clear_square(move.from_square)
- self.clear_square(move.to_square)
- self._set_piece_at(move.to_square, piece.piece_type, piece.color)
- self.turn = not self.turn
- self.move_stack.append((move, captured_piece))
- def pop(self):
- if not self.move_stack:
- return None
- move, captured_piece = self.move_stack.pop()
- piece = self.piece_at(move.to_square)
- self.clear_square(move.from_square)
- self.clear_square(move.to_square)
- self._set_piece_at(move.from_square, piece.piece_type, piece.color)
- if captured_piece:
- self._set_piece_at(move.to_square, captured_piece.piece_type, captured_piece.color)
- self.turn = not self.turn
- return move
- def is_check(self):
- king_square = self.king(self.turn)
- if king_square is None:
- return False
- is_check = self._is_attacked_by(not self.turn, king_square)
- # print(f"[DEBUG] Checking if position is check: FEN: {self.fen()}, King at {chess.SQUARE_NAMES[king_square]}, is_check: {is_check}")
- return is_check
- def is_checkmate(self):
- if not self.is_check():
- # print(f"[DEBUG] Position is not check, hence not checkmate: FEN: {self.fen()}")
- return False
- legal_moves = list(self.generate_legal_moves())
- # print(f"[DEBUG] Checking if position is checkmate: FEN: {self.fen()}, Legal moves: {legal_moves}")
- return len(legal_moves) == 0
- def is_game_over(self):
- return self.is_checkmate() or self.is_stalemate() or self.is_insufficient_material()
- def is_stalemate(self):
- if self.is_check():
- return False
- legal_moves = list(self.generate_legal_moves())
- # print(f"[DEBUG] Checking if position is stalemate: FEN: {self.fen()}, Legal moves: {legal_moves}")
- return len(legal_moves) == 0
- def is_insufficient_material(self):
- return (self.pawns | self.rooks | self.queens | self.amazons_white | self.amazons_black |
- self.cyrils_white | self.cyrils_black | self.eves_white | self.eves_black) == 0 and (
- chess.popcount(self.occupied) <= 3
- )
- def generate_legal_moves(self, from_mask=chess.BB_ALL, to_mask=chess.BB_ALL):
- for move in self.generate_pseudo_legal_moves(from_mask, to_mask):
- if self.is_legal(move):
- # print(f"[DEBUG] Legal move: {move}")
- yield move
- # else:
- # print(f"[DEBUG] Illegal move: {move}")
- def debug_amazons(self):
- pass
- # print(f"Bitboard bílých amazonek: {format(self.amazons_white, '064b')}")
- # print(f"Bitboard černých amazonek: {format(self.amazons_black, '064b')}")
- for square in chess.SQUARES:
- pass
- # if self.amazons_white & chess.BB_SQUARES[square]:
- # print(f"Bílá amazonka na {chess.SQUARE_NAMES[square]}")
- # if self.amazons_black & chess.BB_SQUARES[square]:
- # print(f"Černá amazonka na {chess.SQUARE_NAMES[square]}")
- def debug_cyrils(self):
- pass
- # print(f"Bitboard bílých Cyrils: {format(self.cyrils_white, '064b')}")
- # print(f"Bitboard černých Cyrils: {format(self.cyrils_black, '064b')}")
- # for square in chess.SQUARES:
- # if self.cyrils_white & chess.BB_SQUARES[square]:
- # print(f"Bílý Cyril na {chess.SQUARE_NAMES[square]}")
- # if self.cyrils_black & chess.BB_SQUARES[square]:
- # print(f"Černý Cyril na {chess.SQUARE_NAMES[square]}")
- def debug_eves(self):
- pass
- # print(f"Bitboard bílých Eves: {format(self.eves_white, '064b')}")
- # print(f"Bitboard černých Eves: {format(self.eves_black, '064b')}")
- # for square in chess.SQUARES:
- # if self.eves_white & chess.BB_SQUARES[square]:
- # print(f"Bílá Eve na {chess.SQUARE_NAMES[square]}")
- # if self.eves_black & chess.BB_SQUARES[square]:
- # print(f"Černá Eve na {chess.SQUARE_NAMES[square]}")
- def piece_symbol(self, piece):
- if piece is None:
- return '.'
- if piece.piece_type == AMAZON:
- return 'A' if piece.color == chess.WHITE else 'a'
- if piece.piece_type == CYRIL:
- return 'C' if piece.color == chess.WHITE else 'c'
- if piece.piece_type == EVE:
- return 'E' if piece.color == chess.WHITE else 'e'
- return piece.symbol()
- def piece_type_at(self, square):
- if (self.amazons_white | self.amazons_black) & chess.BB_SQUARES[square]:
- return AMAZON
- if (self.cyrils_white | self.cyrils_black) & chess.BB_SQUARES[square]:
- return CYRIL
- if (self.eves_white | self.eves_black) & chess.BB_SQUARES[square]:
- return EVE
- return super().piece_type_at(square)
- def color_at(self, square):
- if self.amazons_white & chess.BB_SQUARES[square]:
- return chess.WHITE
- if self.amazons_black & chess.BB_SQUARES[square]:
- return chess.BLACK
- if self.cyrils_white & chess.BB_SQUARES[square]:
- return chess.WHITE
- if self.cyrils_black & chess.BB_SQUARES[square]:
- return chess.BLACK
- if self.eves_white & chess.BB_SQUARES[square]:
- return chess.WHITE
- if self.eves_black & chess.BB_SQUARES[square]:
- return chess.BLACK
- return super().color_at(square)
- @property
- def legal_moves(self):
- return list(self.generate_legal_moves())
- def __str__(self):
- builder = []
- for square in chess.SQUARES_180:
- piece = self.piece_at(square)
- symbol = self.piece_symbol(piece) if piece else '.'
- builder.append(symbol)
- if chess.square_file(square) == 7:
- if square != chess.H1:
- builder.append('\n')
- return ''.join(builder)
- def print_all_possible_moves(self):
- pass
- # print(f"[DEBUG] All possible moves for FEN: {self.fen()}")
- # for move in self.generate_pseudo_legal_moves():
- # print(f"Move: {move}, Is legal: {self.is_legal(move)}")
- def simplify_fen_string(fen):
- parts = fen.split(' ')
- return ' '.join(parts[:4]) # Zachováváme pouze informace o pozici, barvě na tahu, rošádách a en passant
- def format_time(seconds):
- hours, remainder = divmod(seconds, 3600)
- minutes, seconds = divmod(remainder, 60)
- return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
- def print_elapsed_time(stop_event, start_time):
- while not stop_event.is_set():
- elapsed_time = time.time() - start_time
- print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
- time.sleep(1)
- def format_time(seconds):
- hours, remainder = divmod(seconds, 3600)
- minutes, seconds = divmod(remainder, 60)
- return f"{int(hours):02d}h {int(minutes):02d}m {int(seconds):02d}s"
- def print_elapsed_time(stop_event, start_time):
- while not stop_event.is_set():
- elapsed_time = time.time() - start_time
- print(f"\rUplynulý čas: {format_time(elapsed_time)}", end="", flush=True)
- time.sleep(1)
- def simplify_fen(fen):
- return ' '.join(fen.split()[:4])
- def calculate_optimal_moves(start_fen: str) -> Dict[str, Tuple[int, str]]:
- print("Funkce calculate_optimal_moves byla zavolána")
- print(f"Počáteční FEN: {start_fen}")
- board = CustomBoard(start_fen)
- POZ = {1: simplify_fen_string(start_fen)}
- AR = {simplify_fen_string(start_fen): {'used': 0, 'to_end': 0, 'depth': 0, 'type': 'normal'}}
- N = 1
- M = 0
- start_time = time.time()
- current_depth = 0
- positions_at_depth = {0: 0}
- depth_start_time = start_time
- stop_event = threading.Event()
- timer_thread = threading.Thread(target=print_elapsed_time, args=(stop_event, start_time))
- timer_thread.start()
- try:
- print("Začínám generovat pozice...")
- # Generate all positions
- while M < N:
- M += 1
- current_fen = POZ[M]
- board.set_custom_fen(current_fen)
- simplified_current_fen = simplify_fen_string(current_fen)
- current_depth = AR[simplified_current_fen]['depth']
- if current_depth not in positions_at_depth:
- positions_at_depth[current_depth] = 0
- if current_depth > 0:
- depth_time = time.time() - depth_start_time
- total_time = time.time() - start_time
- print(f"\nHloubka {current_depth - 1}: {positions_at_depth[current_depth - 1]} pozic, "
- f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
- depth_start_time = time.time()
- positions_at_depth[current_depth] += 1
- if AR[simplified_current_fen]['used'] == 0:
- AR[simplified_current_fen]['used'] = 1
- legal_moves = list(board.legal_moves)
- for move in legal_moves:
- if board.is_pseudo_legal(move) and move.promotion:
- move.promotion = chess.QUEEN # Set promotion to queen only
- for move in legal_moves:
- board.push(move)
- POZ2 = board.fen()
- simplified_POZ2 = simplify_fen_string(POZ2)
- if simplified_POZ2 not in AR:
- N += 1
- POZ[N] = simplified_POZ2
- AR[simplified_POZ2] = {'used': 0, 'to_end': 0, 'depth': current_depth + 1, 'type': 'normal'}
- board.pop()
- # Print last depth
- depth_time = time.time() - depth_start_time
- total_time = time.time() - start_time
- print(f"\nHloubka {current_depth}: {positions_at_depth[current_depth]} pozic, "
- f"Čas hloubky: {format_time(depth_time)} / Celkový čas: {format_time(total_time)}")
- print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
- print("\nZačínám počáteční ohodnocení...")
- stalemates = 0
- checkmates = 0
- draws = 0
- checks = 0
- for i in range(1, N + 1):
- current_fen = POZ[i]
- board.set_custom_fen(current_fen)
- simplified_current_fen = simplify_fen(current_fen)
- if board.is_checkmate():
- print(f"Nalezen mat: {current_fen}")
- AR[simplified_current_fen]['to_end'] = -1000 if board.turn == chess.WHITE else 1000
- AR[simplified_current_fen]['type'] = 'mate'
- checkmates += 1
- elif board.is_stalemate():
- AR[simplified_current_fen]['to_end'] = 0
- AR[simplified_current_fen]['type'] = 'stalemate'
- stalemates += 1
- elif board.is_insufficient_material():
- AR[simplified_current_fen]['to_end'] = 0
- AR[simplified_current_fen]['type'] = 'draw'
- draws += 1
- elif board.is_check():
- print(f"Nalezen šach: {current_fen}")
- AR[simplified_current_fen]['type'] = 'check'
- checks += 1
- else:
- AR[simplified_current_fen]['to_end'] = 1 if board.turn == chess.BLACK else -1
- AR[simplified_current_fen]['type'] = 'normal'
- # Kontrola proměny pěšců
- for move in board.legal_moves:
- if move.promotion == chess.QUEEN:
- print(f"Možná proměna pěšce na dámu: {current_fen}, tah: {move}")
- if i % 10000 == 0:
- print(f"Zpracováno {i} pozic...")
- print(f"Počáteční ohodnocení: Maty: {checkmates}, Paty: {stalemates}, Remízy: {draws}, Šachy: {checks}, Normální pozice: {N - checkmates - stalemates - draws - checks}"
- # if i % 10000 == 0:
- # print(f"Zpracováno {i} pozic...")
- print(f"Počáteční ohodnocení: Maty: {checkmates}, Paty: {stalemates}, Remízy: {draws}, Šachy: {checks}, Normální pozice: {N - checkmates - stalemates - draws - checks}")
- # Iterative evaluation
- print("\nZačínám iterativní ohodnocení...")
- uroven = 0
- F = sum(1 for data in AR.values() if data['type'] == 'normal')
- while F > 0:
- uroven += 1
- level_start_time = time.time()
- print(f"Výpočet v úrovni {uroven}")
- F = 0
- current_level_positions = 0
- for i in range(1, N + 1):
- current_fen = POZ[i]
- board.set_custom_fen(current_fen)
- simplified_current_fen = simplify_fen_string(current_fen)
- if AR[simplified_current_fen]['type'] == 'normal':
- hod = -2000 if board.turn == chess.WHITE else 2000
- best_move = None
- for move in board.legal_moves:
- board.push(move)
- POZ2 = board.fen()
- simplified_POZ2 = simplify_fen_string(POZ2)
- if simplified_POZ2 in AR:
- hod2 = -AR[simplified_POZ2]['to_end']
- if board.turn == chess.WHITE and hod2 > hod:
- hod = hod2
- best_move = move
- elif board.turn == chess.BLACK and hod2 < hod:
- hod = hod2
- best_move = move
- board.pop()
- if best_move is None:
- AR[simplified_current_fen]['type'] = 'stalemate'
- AR[simplified_current_fen]['to_end'] = 0
- elif abs(hod) == 1000:
- AR[simplified_current_fen]['type'] = 'mate'
- AR[simplified_current_fen]['to_end'] = hod
- elif hod == 0:
- AR[simplified_current_fen]['type'] = 'draw'
- AR[simplified_current_fen]['to_end'] = 0
- else:
- AR[simplified_current_fen]['to_end'] = hod
- F += 1
- current_level_positions += 1
- level_end_time = time.time()
- total_elapsed_time = level_end_time - start_time
- level_elapsed_time = level_end_time - level_start_time
- print(f"Nalezeno {current_level_positions} pozic v úrovni {uroven}")
- print(f"Čas úrovně: {format_time(level_elapsed_time)} / Celkový čas: {format_time(total_elapsed_time)}")
- print(f"Zbývá ohodnotit: {F} pozic")
- print(f"Nalezeno {N - F} ohodnocených pozic celkem")
- print("\nVýpočet dokončen.")
- return {fen: (data['to_end'], data['type']) for fen, data in AR.items()}
- finally:
- stop_event.set()
- timer_thread.join()
- # Helper function to print the board
- def print_board(fen):
- board = CustomBoard(fen)
- print(board)
- # Main execution
- if __name__ == "__main__":
- start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
- AR = calculate_optimal_moves(start_fen)
- print("\nVýsledky:")
- for fen, (hodnota, typ_pozice) in AR.items():
- if hodnota == 0 or typ_pozice in ['mate', 'stalemate', 'draw']:
- print(f"FEN: {fen}")
- print(f"Hodnota: {hodnota}")
- print(f"Typ pozice: {typ_pozice}")
- temp_board = CustomBoard(fen)
- if temp_board.is_checkmate():
- print("Stav: Mat")
- elif temp_board.is_stalemate():
- print("Stav: Pat")
- elif temp_board.is_insufficient_material():
- print("Stav: Nedostatečný materiál")
- elif temp_board.is_check():
- print("Stav: Šach")
- else:
- print("Stav: Normální pozice")
- print_board(fen)
- print()
- # Print optimal moves
- current_fen = start_fen
- simplified_current_fen = simplify_fen_string(current_fen)
- optimal_moves = []
- while True:
- board = CustomBoard(current_fen)
- if board.turn == chess.WHITE:
- best_value = -float('inf')
- best_move = None
- for move in board.legal_moves:
- board.push(move)
- next_fen = board.fen()
- simplified_next_fen = simplify_fen_string(next_fen)
- if simplified_next_fen in AR:
- value = -AR[simplified_next_fen][0]
- if value > best_value or (value == best_value and value == 0):
- best_value = value
- best_move = move
- board.pop()
- else: # Black's turn
- best_value = float('inf')
- best_move = None
- for move in board.legal_moves:
- board.push(move)
- next_fen = board.fen()
- simplified_next_fen = simplify_fen_string(next_fen)
- if simplified_next_fen in AR:
- value = AR[simplified_next_fen][0]
- if value < best_value:
- best_value = value
- best_move = move
- board.pop()
- if best_move is None:
- break
- board.push(best_move)
- current_fen = board.fen()
- simplified_current_fen = simplify_fen_string(current_fen)
- optimal_moves.append((best_move, current_fen))
- if AR[simplified_current_fen][1] in ['mate', 'stalemate', 'draw']:
- break
- print("\nOptimální tahy:")
- for move, fen in optimal_moves:
- print(f"Tah: {move}")
- print_board(fen)
- print(f"Hodnocení: {AR[simplify_fen_string(fen)][0]}")
- print(f"Typ pozice: {AR[simplify_fen_string(fen)][1]}")
- print("\n")
- # print_board(simplified_current_fen1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement