Advertisement
max2201111

very good OKOK ACE!

Apr 9th, 2025
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 23.34 KB | Science | 0 0
  1. #!/usr/bin/env python3
  2. import time
  3. import threading
  4. import sys
  5. from math import inf
  6.  
  7. # Globální konstanty – pohyby jezdce (relativní souřadnice)
  8. knight_moves = [(2, 1), (2, -1), (-2, 1), (-2, -1),
  9.                 (1, 2), (1, -2), (-1, 2), (-1, -2)]
  10. MATE = 10000  # Velikost hodnoty pro mat
  11.  
  12. # Globální proměnné pro sledování času
  13. running = False
  14. start_time = 0
  15.  
  16. ###############################################################################
  17. # Funkce pro výpis času v samostatném vlákně
  18. ###############################################################################
  19.  
  20. def time_reporter():
  21.     """Funkce pro výpis aktuálního času každou sekundu na stejném řádku."""
  22.     global running, start_time
  23.     while running:
  24.         elapsed = time.time() - start_time
  25.         hrs = int(elapsed // 3600)
  26.         mins = int((elapsed % 3600) // 60)
  27.         secs = int(elapsed % 60)
  28.         sys.stdout.write(f"\r[INFO] Uplynulý čas: {hrs:02d}h {mins:02d}m {secs:02d}s")
  29.         sys.stdout.flush()
  30.         time.sleep(1)
  31.  
  32. ###############################################################################
  33. # Třída Board – reprezentuje šachovnici a inicializuje ji z FEN řetězce.
  34. ###############################################################################
  35.  
  36. class Board:
  37.     def __init__(self, fen=None):
  38.         """Inicializace šachovnice; pokud je zadán FEN, nastaví pozici podle něj."""
  39.         self.grid = [[' ' for _ in range(8)] for _ in range(8)]
  40.         self.to_move = 'w'
  41.         self.castling_rights = set()  # např. {'K','Q','k','q'}
  42.         self.en_passant = None       # (row, col) nebo None
  43.         self.halfmove_clock = 0
  44.         self.fullmove_number = 1
  45.         if fen:
  46.             self.set_fen(fen)
  47.    
  48.     def set_fen(self, fen):
  49.         """Nastaví šachovnici podle FEN řetězce."""
  50.         parts = fen.split()
  51.         while len(parts) < 6:
  52.             parts.append('0')
  53.         board_part, turn_part = parts[0], parts[1]
  54.         castling_part = parts[2] if len(parts) > 2 else '-'
  55.         en_passant_part = parts[3] if len(parts) > 3 else '-'
  56.         halfmove = parts[4] if len(parts) > 4 else '0'
  57.         fullmove = parts[5] if len(parts) > 5 else '1'
  58.         self.grid = [['.' for _ in range(8)] for _ in range(8)]
  59.         ranks = board_part.split('/')
  60.         # FEN řady začínají od horní (8.) a jdou dolů
  61.         for rank_idx, rank_str in enumerate(ranks):
  62.             file_idx = 0
  63.             for ch in rank_str:
  64.                 if ch.isdigit():
  65.                     file_idx += int(ch)
  66.                 else:
  67.                     self.grid[rank_idx][file_idx] = ch
  68.                     file_idx += 1
  69.         self.to_move = 'w' if turn_part == 'w' else 'b'
  70.         self.castling_rights = set() if castling_part == '-' else set(castling_part)
  71.         self.en_passant = None
  72.         if en_passant_part != '-' and en_passant_part != '':
  73.             file = ord(en_passant_part[0]) - ord('a')
  74.             rank = int(en_passant_part[1])
  75.             ri = 8 - rank
  76.             fi = file
  77.             if 0 <= ri < 8 and 0 <= fi < 8:
  78.                 self.en_passant = (ri, fi)
  79.         try:
  80.             self.halfmove_clock = int(halfmove)
  81.         except:
  82.             self.halfmove_clock = 0
  83.         try:
  84.             self.fullmove_number = int(fullmove)
  85.         except:
  86.             self.fullmove_number = 1
  87.    
  88.     def copy(self):
  89.         """Vytvoří hlubokou kopii šachovnice."""
  90.         new_board = Board()
  91.         new_board.grid = [row.copy() for row in self.grid]
  92.         new_board.to_move = self.to_move
  93.         new_board.castling_rights = set(self.castling_rights)
  94.         new_board.en_passant = None if self.en_passant is None else (self.en_passant[0], self.en_passant[1])
  95.         new_board.halfmove_clock = self.halfmove_clock
  96.         new_board.fullmove_number = self.fullmove_number
  97.         return new_board
  98.  
  99.     def display(self):
  100.         """Vrátí textovou reprezentaci šachovnice."""
  101.         lines = []
  102.         lines.append("  a b c d e f g h")
  103.         lines.append("  ---------------")
  104.         for ri in range(8):
  105.             line = f"{8-ri}|"
  106.             for fi in range(8):
  107.                 line += self.grid[ri][fi] + " "
  108.             lines.append(line + f"|{8-ri}")
  109.         lines.append("  ---------------")
  110.         lines.append("  a b c d e f g h")
  111.         lines.append(f"Na tahu: {'Bílý' if self.to_move == 'w' else 'Černý'}")
  112.         return "\n".join(lines)
  113.  
  114. ###############################################################################
  115. # Funkce pro převod tahu do notace
  116. ###############################################################################
  117.  
  118. def move_to_notation(move):
  119.     """Převede interní formát tahu (r1, c1, r2, c2, promo, special) na šachovou notaci."""
  120.     r1, c1, r2, c2, promo, special = move
  121.     from_square = chr(c1 + ord('a')) + str(8 - r1)
  122.     to_square = chr(c2 + ord('a')) + str(8 - r2)
  123.     if special == 'castle':
  124.         if c2 > c1:
  125.             return "O-O"
  126.         else:
  127.             return "O-O-O"
  128.     notation = from_square + to_square
  129.     if promo:
  130.         notation += promo.lower()
  131.     return notation
  132.  
  133. ###############################################################################
  134. # Funkce pro detekci šachu, generování tahů a jejich provádění
  135. ###############################################################################
  136.  
  137. def find_king(board, side):
  138.     """Najde pozici krále pro stranu 'w' nebo 'b'."""
  139.     target = 'K' if side=='w' else 'k'
  140.     for r in range(8):
  141.         for c in range(8):
  142.             if board.grid[r][c] == target:
  143.                 return (r, c)
  144.     return None
  145.  
  146. def is_square_attacked(board, r, c, by_side):
  147.     """Zjistí, zda je pole (r,c) napadeno stranou by_side."""
  148.     # Útoky pěšcem
  149.     if by_side == 'b':
  150.         if r+1 < 8 and c-1 >= 0 and board.grid[r+1][c-1] == 'p': return True
  151.         if r+1 < 8 and c+1 < 8 and board.grid[r+1][c+1] == 'p': return True
  152.     else:
  153.         if r-1 >= 0 and c-1 >= 0 and board.grid[r-1][c-1] == 'P': return True
  154.         if r-1 >= 0 and c+1 < 8 and board.grid[r-1][c+1] == 'P': return True
  155.     # Útoky jezdcem (a dalšími s jezdcovým pohybem)
  156.     enemy_knights = ['n','a','c','e'] if by_side=='b' else ['N','A','C','E']
  157.     for dr, dc in knight_moves:
  158.         nr, nc = r+dr, c+dc
  159.         if 0<=nr<8 and 0<=nc<8 and board.grid[nr][nc] in enemy_knights:
  160.             return True
  161.     # Útoky po řadách/sloupcích (věž, dáma, případně i Cyril = R+N či další kombinace)
  162.     enemy_rook_like = ['r','q','e','a'] if by_side=='b' else ['R','Q','E','A']
  163.     for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
  164.         nr, nc = r+dr, c+dc
  165.         while 0<=nr<8 and 0<=nc<8:
  166.             if board.grid[nr][nc] != '.':
  167.                 if board.grid[nr][nc] in enemy_rook_like:
  168.                     return True
  169.                 break
  170.             nr += dr; nc += dc
  171.     # Útoky diagonálně (střelec, dáma, případně i Eve = B+N)
  172.     enemy_bishop_like = ['b','q','c','a'] if by_side=='b' else ['B','Q','C','A']
  173.     for dr, dc in [(1,1),(1,-1),(-1,1),(-1,-1)]:
  174.         nr, nc = r+dr, c+dc
  175.         while 0<=nr<8 and 0<=nc<8:
  176.             if board.grid[nr][nc] != '.':
  177.                 if board.grid[nr][nc] in enemy_bishop_like:
  178.                     return True
  179.                 break
  180.             nr += dr; nc += dc
  181.     # Sousední král
  182.     enemy_king = 'k' if by_side=='b' else 'K'
  183.     for dr in [-1,0,1]:
  184.         for dc in [-1,0,1]:
  185.             if dr==0 and dc==0: continue
  186.             nr, nc = r+dr, c+dc
  187.             if 0<=nr<8 and 0<=nc<8 and board.grid[nr][nc] == enemy_king:
  188.                 return True
  189.     return False
  190.  
  191. def is_in_check(board, side):
  192.     """Zjistí, zda je král strany side ('w' nebo 'b') v šachu."""
  193.     king_pos = find_king(board, side)
  194.     if not king_pos:
  195.         return False
  196.     kr, kc = king_pos
  197.     enemy_side = 'b' if side=='w' else 'w'
  198.     return is_square_attacked(board, kr, kc, enemy_side)
  199.  
  200. def generate_pseudo_moves(board, side):
  201.     """Generuje všechny pseudolegální tahy pro stranu side ('w' nebo 'b')."""
  202.     moves = []
  203.     enemy = 'b' if side=='w' else 'w'
  204.     is_white = (side=='w')
  205.     pawn_dir = -1 if is_white else 1
  206.     start_rank = 6 if is_white else 1
  207.     promote_rank = 0 if is_white else 7
  208.     for r in range(8):
  209.         for c in range(8):
  210.             piece = board.grid[r][c]
  211.             if piece == '.': continue
  212.             if is_white and not piece.isupper(): continue
  213.             if not is_white and not piece.islower(): continue
  214.             pt = piece.upper()
  215.             if pt == 'P':
  216.                 nr = r + pawn_dir
  217.                 if 0<=nr<8 and board.grid[nr][c]=='.':
  218.                     if nr==promote_rank:
  219.                         for promo in ['Q','R','B','N','A','E','C']:
  220.                             moves.append((r, c, nr, c, promo if is_white else promo.lower(), None))
  221.                     else:
  222.                         moves.append((r, c, nr, c, None, None))
  223.                     if r==start_rank and board.grid[r+pawn_dir*2][c]=='.' and board.grid[r+pawn_dir][c]=='.':
  224.                         moves.append((r, c, r+pawn_dir*2, c, None, 'double'))
  225.                 for dc in [-1,1]:
  226.                     nc = c + dc
  227.                     if 0<=nc<8 and 0<=nr<8:
  228.                         if board.grid[nr][nc] != '.' and ((is_white and board.grid[nr][nc].islower()) or (not is_white and board.grid[nr][nc].isupper())):
  229.                             if nr==promote_rank:
  230.                                 for promo in ['Q','R','B','N','A','E','C']:
  231.                                     moves.append((r, c, nr, nc, promo if is_white else promo.lower(), None))
  232.                             else:
  233.                                 moves.append((r, c, nr, nc, None, None))
  234.                         if board.en_passant == (nr, nc):
  235.                             moves.append((r, c, nr, nc, None, 'enpassant'))
  236.             elif pt == 'K':
  237.                 for dr in [-1,0,1]:
  238.                     for dc in [-1,0,1]:
  239.                         if dr==0 and dc==0: continue
  240.                         nr, nc = r+dr, c+dc
  241.                         if 0<=nr<8 and 0<=nc<8:
  242.                             if board.grid[nr][nc]=='.' or ((is_white and board.grid[nr][nc].islower()) or (not is_white and board.grid[nr][nc].isupper())):
  243.                                 moves.append((r, c, nr, nc, None, None))
  244.                 # Rošády (základní verze)
  245.                 if is_white and r==7 and c==4:
  246.                     if 'K' in board.castling_rights and board.grid[7][5]=='.' and board.grid[7][6]=='.':
  247.                         moves.append((7,4,7,6,None,'castle'))
  248.                     if 'Q' in board.castling_rights and board.grid[7][3]=='.' and board.grid[7][2]=='.' and board.grid[7][1]=='.':
  249.                         moves.append((7,4,7,2,None,'castle'))
  250.                 if not is_white and r==0 and c==4:
  251.                     if 'k' in board.castling_rights and board.grid[0][5]=='.' and board.grid[0][6]=='.':
  252.                         moves.append((0,4,0,6,None,'castle'))
  253.                     if 'q' in board.castling_rights and board.grid[0][3]=='.' and board.grid[0][2]=='.' and board.grid[0][1]=='.':
  254.                         moves.append((0,4,0,2,None,'castle'))
  255.             else:
  256.                 # Tahy pro figury s jezdcovým pohybem (N, A, C, E)
  257.                 if pt in ['N','A','C','E']:
  258.                     for dr, dc in knight_moves:
  259.                         nr, nc = r+dr, c+dc
  260.                         if 0<=nr<8 and 0<=nc<8:
  261.                             if board.grid[nr][nc]=='.' or ((is_white and board.grid[nr][nc].islower()) or (not is_white and board.grid[nr][nc].isupper())):
  262.                                 moves.append((r, c, nr, nc, None, None))
  263.                 # Klouzavé tahy – pro R, Q, E, A
  264.                 if pt in ['R','Q','E','A']:
  265.                     for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
  266.                         nr, nc = r+dr, c+dc
  267.                         while 0<=nr<8 and 0<=nc<8:
  268.                             if board.grid[nr][nc]=='.':
  269.                                 moves.append((r, c, nr, nc, None, None))
  270.                             else:
  271.                                 if ((is_white and board.grid[nr][nc].islower()) or (not is_white and board.grid[nr][nc].isupper())):
  272.                                     moves.append((r, c, nr, nc, None, None))
  273.                                 break
  274.                             nr += dr; nc += dc
  275.                 if pt in ['B','Q','C','A']:
  276.                     for dr, dc in [(1,1),(1,-1),(-1,1),(-1,-1)]:
  277.                         nr, nc = r+dr, c+dc
  278.                         while 0<=nr<8 and 0<=nc<8:
  279.                             if board.grid[nr][nc]=='.':
  280.                                 moves.append((r, c, nr, nc, None, None))
  281.                             else:
  282.                                 if ((is_white and board.grid[nr][nc].islower()) or (not is_white and board.grid[nr][nc].isupper())):
  283.                                     moves.append((r, c, nr, nc, None, None))
  284.                                 break
  285.                             nr += dr; nc += dc
  286.     return moves
  287.  
  288. def get_legal_moves(board, side):
  289.     """Vrátí seznam legálních tahů pro danou stranu."""
  290.     moves = generate_pseudo_moves(board, side)
  291.     legal_moves = []
  292.     for move in moves:
  293.         make_move(move, board)
  294.         if not is_in_check(board, side):
  295.             legal_moves.append(move)
  296.         undo_move(board)
  297.     return legal_moves
  298.  
  299. # Zásobník pro tahy (pro undo)
  300. move_stack = []
  301.  
  302. def make_move(move, board):
  303.     """Provede tah na šachovnici a uloží stav pro možnost undo.
  304.       move: (r1, c1, r2, c2, promo, special)"""
  305.     r1, c1, r2, c2, promo, special = move
  306.     piece = board.grid[r1][c1]
  307.     captured = board.grid[r2][c2] if special != 'enpassant' else ('p' if piece=='P' else 'P')
  308.     prev_state = (set(board.castling_rights), board.en_passant)
  309.     move_stack.append((r1, c1, r2, c2, promo, special, piece, captured, prev_state))
  310.     board.grid[r1][c1] = '.'
  311.     if special == 'castle':
  312.         board.grid[r2][c2] = piece
  313.         if piece == 'K':
  314.             if c2 == 6:
  315.                 board.grid[7][5] = 'R'; board.grid[7][7] = '.'
  316.             else:
  317.                 board.grid[7][3] = 'R'; board.grid[7][0] = '.'
  318.         else:
  319.             if c2 == 6:
  320.                 board.grid[0][5] = 'r'; board.grid[0][7] = '.'
  321.             else:
  322.                 board.grid[0][3] = 'r'; board.grid[0][0] = '.'
  323.     elif special == 'enpassant':
  324.         board.grid[r2][c2] = piece
  325.         if piece == 'P':
  326.             board.grid[r2+1][c2] = '.'
  327.         else:
  328.             board.grid[r2-1][c2] = '.'
  329.     else:
  330.         board.grid[r2][c2] = promo if promo else piece
  331.     if piece == 'K':
  332.         board.castling_rights.discard('K'); board.castling_rights.discard('Q')
  333.     if piece == 'k':
  334.         board.castling_rights.discard('k'); board.castling_rights.discard('q')
  335.     if piece == 'R' and (r1, c1)==(7,7):
  336.         board.castling_rights.discard('K')
  337.     if piece == 'R' and (r1, c1)==(7,0):
  338.         board.castling_rights.discard('Q')
  339.     if piece == 'r' and (r1, c1)==(0,7):
  340.         board.castling_rights.discard('k')
  341.     if piece == 'r' and (r1, c1)==(0,0):
  342.         board.castling_rights.discard('q')
  343.     if special == 'double':
  344.         board.en_passant = (r1 + (-1 if board.to_move=='w' else 1), c1)
  345.     else:
  346.         board.en_passant = None
  347.     board.to_move = 'b' if board.to_move=='w' else 'w'
  348.  
  349. def undo_move(board):
  350.     """Vrátí poslední provedený tah."""
  351.     r1, c1, r2, c2, promo, special, piece, captured, prev_state = move_stack.pop()
  352.     board.grid[r1][c1] = piece
  353.     if special == 'castle':
  354.         board.grid[r2][c2] = '.'
  355.         if piece == 'K':
  356.             if c2 == 6:
  357.                 board.grid[7][7] = 'R'; board.grid[7][5] = '.'
  358.             else:
  359.                 board.grid[7][0] = 'R'; board.grid[7][3] = '.'
  360.         else:
  361.             if c2 == 6:
  362.                 board.grid[0][7] = 'r'; board.grid[0][5] = '.'
  363.             else:
  364.                 board.grid[0][0] = 'r'; board.grid[0][3] = '.'
  365.     elif special == 'enpassant':
  366.         board.grid[r2][c2] = '.'
  367.         if piece == 'P':
  368.             board.grid[r2+1][c2] = 'p'
  369.         else:
  370.             board.grid[r2-1][c2] = 'P'
  371.     else:
  372.         board.grid[r2][c2] = captured
  373.     board.castling_rights, board.en_passant = prev_state
  374.     board.to_move = 'b' if board.to_move=='w' else 'w'
  375.  
  376. def analyze_position(board):
  377.     """Analyzuje pozici a vrátí textový popis."""
  378.     white_legal = get_legal_moves(board, 'w')
  379.     black_legal = get_legal_moves(board, 'b')
  380.     white_in_check = is_in_check(board, 'w')
  381.     black_in_check = is_in_check(board, 'b')
  382.     if not white_legal and white_in_check:
  383.         return "Mat – černý vyhrává"
  384.     if not black_legal and black_in_check:
  385.         return "Mat – bílý vyhrává"
  386.     if (not white_legal and not white_in_check) or (not black_legal and not black_in_check):
  387.         return "Pat – remíza"
  388.     return "Pozice je hratelná"
  389.  
  390. ###############################################################################
  391. # Čistý negamax bez heuristik – hledáme pouze mate (terminální stavy)
  392. ###############################################################################
  393. MATE = 10000  # Hodnota pro mate
  394.  
  395. # --- Ostatní funkce (time_reporter, Board, move_to_notation, find_king, is_square_attacked, is_in_check,
  396. # generate_pseudo_moves, get_legal_moves, make_move, undo_move, analyze_position) zůstávají beze změny --- #
  397.  
  398. ###############################################################################
  399. # Upravený čistý negamax s check extension (a omezením počtu extenzí)
  400. ###############################################################################
  401.  
  402. def negamax(board, alpha, beta, depth, max_depth, ext=0, max_ext=1):
  403.     legal_moves = get_legal_moves(board, board.to_move)
  404.     if not legal_moves:
  405.         # Terminální uzel: pokud je strana v šachu, je to mate, jinak pat.
  406.         if is_in_check(board, board.to_move):
  407.             return -(MATE - depth), []
  408.         else:
  409.             return 0, []
  410.    
  411.     # Pokud jsme dosáhli cutoff hloubky, zkusíme prodloužit hledání, když je hráč v šachu.
  412.     if depth == max_depth:
  413.         if is_in_check(board, board.to_move) and ext < max_ext:
  414.             # Prodloužíme hledání o jeden ply a zvýšíme počet extenzí
  415.             return negamax(board, alpha, beta, depth, max_depth + 1, ext + 1, max_ext)
  416.         else:
  417.             return 0, []
  418.  
  419.     best_value = -inf
  420.     best_line = []
  421.     for move in legal_moves:
  422.         make_move(move, board)
  423.         child_score, child_line = negamax(board, -beta, -alpha, depth + 1, max_depth, ext, max_ext)
  424.         score = -child_score
  425.         undo_move(board)
  426.         if score > best_value:
  427.             best_value = score
  428.             best_line = [move] + child_line
  429.         alpha = max(alpha, score)
  430.         if alpha >= beta:
  431.             break
  432.     return best_value, best_line
  433.  
  434. ###############################################################################
  435. # Iterativní prohlubování s negamax – hledáme mate s “neomezenou” hloubkou
  436. ###############################################################################
  437.  
  438. def iterative_deepening_negamax(board, max_time=300):
  439.     global running, start_time
  440.     running = True
  441.     start_time = time.time()
  442.     timer_thread = threading.Thread(target=time_reporter)
  443.     timer_thread.daemon = True
  444.     timer_thread.start()
  445.  
  446.     best_value = -inf
  447.     best_moves = []
  448.     current_depth = 1
  449.  
  450.     try:
  451.         while True:
  452.             if time.time() - start_time > max_time:
  453.                 print(f"\nČasový limit vypršel po {max_time} sekundách")
  454.                 break
  455.  
  456.             t0 = time.time()
  457.             value, moves = negamax(board, -inf, inf, 0, current_depth)
  458.             t1 = time.time()
  459.  
  460.             elapsed = time.time() - start_time
  461.             hrs = int(elapsed // 3600)
  462.             mins = int((elapsed % 3600) // 60)
  463.             secs = int(elapsed % 60)
  464.             print(f"\nHloubka {current_depth} – čas: {hrs:02d}h {mins:02d}m {secs:02d}s (krok: {t1 - t0:.2f}s)")
  465.             if moves:
  466.                 print(f"Nejlepší sekvence: {' '.join([move_to_notation(m) for m in moves])}")
  467.             else:
  468.                 print("Žádná platná sekvence nalezena.")
  469.  
  470.             # Pokud bylo nalezeno mate (skóre v řádu MATE minus aktuální ply), ukončíme vyhledávání.
  471.             if abs(value) >= MATE - current_depth:
  472.                 print(f"NALEZEN MAT v {len(moves)} tazích!")
  473.                 best_value, best_moves = value, moves
  474.                 break
  475.  
  476.             best_value = value
  477.             best_moves = moves
  478.             current_depth += 1
  479.  
  480.         return best_value, best_moves, time.time() - start_time
  481.  
  482.     finally:
  483.         running = False
  484.         timer_thread.join(timeout=1.0)
  485.         sys.stdout.write("\n")
  486.        
  487.  
  488.  
  489. ###############################################################################
  490. # Iterativní prohlubování s negamax – hledáme mate s “neomezenou” hloubkou
  491. ###############################################################################
  492.  
  493. ###############################################################################
  494. # Hlavní funkce
  495. ###############################################################################
  496.  
  497. def main():
  498.     # Příklad FEN – např. pozice s černou dámou proti bílému králi,
  499.     # případně upravte dle potřeby:
  500.     # fen = "8/6q1/8/8/8/k1K5/8/8 w - - 0 1"   # Bílý na tahu, v šachu od černé dámy
  501.     fen = "6k1/8/3K4/5C2/8/8/8/8 w - - 0 1"
  502.     # Další možné testovací pozice:
  503.     # fen = "8/6q1/8/8/8/k1K5/8/8 b - - 0 1"    # Černý na tahu
  504.     # fen = "8/6A1/8/8/8/k1K5/8/8 w - - 0 1"     # Bílý král a amazonka proti černému králi
  505.     # fen = "8/8/8/8/8/kq2K3/8/8 w - - 0 1"      # Bílý král proti černému králi a dámě
  506.  
  507.     board = Board(fen)
  508.  
  509.     print("\n" + "="*60)
  510.     print("ŠACHOVÝ ENDGAME ENGINE S PODPOROU SPECIÁLNÍCH FIGUR")
  511.     print("="*60)
  512.     print("\nPočáteční pozice:")
  513.     print(board.display())
  514.  
  515.     if is_in_check(board, 'w'):
  516.         print("UPOZORNĚNÍ: Bílý je v šachu!")
  517.     if is_in_check(board, 'b'):
  518.         print("UPOZORNĚNÍ: Černý je v šachu!")
  519.  
  520.     print("\nVyhledávání mate – čistý negamax bez heuristik...\n")
  521.     value, moves, elapsed = iterative_deepening_negamax(board, max_time=300)
  522.  
  523.     hrs = int(elapsed // 3600)
  524.     mins = int((elapsed % 3600) // 60)
  525.     secs = int(elapsed % 60)
  526.  
  527.     print("\n" + "="*60)
  528.     print("NALEZENÁ OPTIMÁLNÍ SEKVENCE")
  529.     print("="*60)
  530.     if not moves:
  531.         print("Nebyla nalezena žádná platná sekvence tahů.")
  532.     else:
  533.         temp_board = board.copy()
  534.         print("Začátek:")
  535.         print(temp_board.display())
  536.         print("-" * 40)
  537.         for i, move in enumerate(moves, 1):
  538.             make_move(move, temp_board)
  539.             print(f"Tah {i}: {move_to_notation(move)}")
  540.             print(temp_board.display())
  541.             print("-" * 40)
  542.         if abs(value) >= MATE - len(moves):
  543.             result = "Mat pro " + ("bílého" if value > 0 else "černého")
  544.         else:
  545.             result = analyze_position(temp_board)
  546.         print(f"Kompletní sekvence: {' '.join([move_to_notation(m) for m in moves])}")
  547.         print(f"Výsledek: {result}")
  548.  
  549.     print(f"Celkový čas: {hrs:02d}h {mins:02d}m {secs:02d}s")
  550.  
  551. if __name__ == '__main__':
  552.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement