Advertisement
max2201111

funkcni wrong plies better output Better evaluate_position

Apr 18th, 2024
758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.01 KB | Science | 0 0
  1. import chess
  2.  
  3. def simplify_fen_string(fen):
  4.     parts = fen.split(' ')
  5.     simplified_fen = ' '.join(parts[:4])  # Zachováváme pouze informace o pozici
  6.     return simplified_fen
  7.  
  8. # def evaluate_position(board):
  9. #     #print(f"Position: {board.fen()}")
  10. #     if board.is_checkmate():
  11. #      ###   print(f"Position: {board.fen()}, return -1000")
  12. #         return -1000  # Mat protihráči
  13. #     elif board.is_stalemate() or board.is_insufficient_material() or board.can_claim_draw():
  14. #      ###   print(f"Position: {board.fen()}, return 0")
  15.  
  16. #         return 0  # Remíza
  17. #     else:
  18. #         #print(f"Position: {board.fen()}, return None")
  19. #         return None  # Hra pokračuje
  20.  
  21. import chess
  22.  
  23. def evaluate_position(board):
  24.     if board.is_checkmate():
  25.         # Hráč na tahu je v matu, vracíme -1000
  26.         return -1000
  27.     elif board.is_stalemate() or board.is_insufficient_material() or board.can_claim_draw():
  28.         # Situace vedoucí k remíze
  29.         return 0
  30.     else:
  31.         # Zkoumáme, zda existuje tah, který by v dalším tahu vedl k matu
  32.         mate_in_one_found = False
  33.         for move in board.legal_moves:
  34.             board.push(move)
  35.             if board.is_checkmate():
  36.                 # Mat byl dosažen tímto tahem
  37.                 board.pop()
  38.                 mate_in_one_found = True
  39.                 break
  40.             board.pop()
  41.        
  42.         if mate_in_one_found:
  43.             # Existuje tah, který vede k matu v dalším tahu
  44.             return 999
  45.         else:
  46.             # Žádný mat v dohlednu
  47.             return None
  48.  
  49.  
  50.  
  51. def create_AR_entry(result, children, last_move):
  52.     return {"result": result, "children": children, "last_move": last_move, "best_child": None}
  53.  
  54.  
  55. def update_best_case(best_case):
  56.     if best_case == 0:
  57.         return best_case
  58.     if best_case > 0:
  59.         return best_case - 1
  60.     else:
  61.         return best_case + 1
  62.  
  63.  
  64. def update_AR_for_mate_in_k(board, AR, simplified_initial_fen, max_k=1000):
  65.    
  66.     evaluated_list = []
  67.     #print(f"")
  68.    
  69.     for k in range(1, max_k + 1):
  70.         print(f"K = {k}")
  71.         changed = False
  72.      #   for _t in range(2):  # Zajistíme, že pro každé k proběhne aktualizace dvakrát
  73.      #   print(f"_t = {_t}")
  74.         for fen in list(AR.keys()):
  75.  
  76.  
  77.             #print(f"Fen = {fen}, looking for {simplified_initial_fen}, same = {fen == simplified_initial_fen}")
  78.             board.set_fen(fen)
  79.  
  80.             if AR[fen]['result'] is not None:
  81.                 if fen == simplified_initial_fen:
  82.                     print(f"Finally we found a mate! {AR[fen]['result']}")
  83.                     return
  84.                 continue  # Pokud již máme hodnocení, přeskočíme
  85.  
  86.             # Získáme výchozí hodnoty pro nejlepší a nejhorší scénář
  87.             best_case = float("-inf")
  88.             #worst_case = float("inf")
  89.             nones_present = False
  90.             best_child = None
  91.  
  92.  
  93.             for move in board.legal_moves:
  94.                 #print(f"Move = {move}")
  95.                 board.push(move)
  96.                 next_fen = simplify_fen_string(board.fen())
  97.                 #AR[fen]['children'].append(next_fen)
  98.  
  99.                 if next_fen not in AR:
  100.                     AR[next_fen] = create_AR_entry(evaluate_position(board), None, move)
  101.                     evaluated_list.append(next_fen)
  102.                     if ((len(evaluated_list)) % 100000 == 0):
  103.                         print(f"Evaluated: {len(evaluated_list)}")
  104.  
  105.                 board.pop()
  106.  
  107.                 #for child in AR[fen]['children']:
  108.                 next_eval = AR[next_fen]['result']
  109.                 if next_eval is not None:
  110.                     if (-next_eval > best_case):
  111.                         best_case = max(best_case, -next_eval)
  112.                         best_child = next_fen
  113.  
  114.                     #worst_case = min(worst_case, -next_eval)
  115.                 else:
  116.                     nones_present = True
  117.  
  118.  
  119.  
  120.             if nones_present:
  121.                 if best_case > 0:
  122.                     AR[fen]['result'] = update_best_case(best_case)
  123.                     AR[fen]['best_child'] = best_child
  124.                     changed = True
  125.             else:
  126.                 # Aktualizace hodnocení podle nejlepšího a nejhoršího scénáře
  127.                 #if worst_case == -1000:
  128.                     # Pokud všechny tahy vedou k matu, hráč na tahu může být matován v k tazích
  129.                 #    AR[fen] = -1000 + k
  130.                 #    changed = True
  131.                 #elif best_case <= 0:
  132.                     # Pokud nejlepší scénář není lepší než remíza, znamená to remízu nebo prohru
  133.                 #    AR[fen] = max(best_case, 0)  # Zabráníme nastavení hodnoty méně než 0, pokud je remíza možná
  134.                 #    changed = True
  135.                 #elif best_case == 1000:
  136.                     # Pokud existuje alespoň jeden tah, který vede k matu protihráče, hráč na tahu může vynutit mat v k tazích
  137.                 #    AR[fen] = 1000 - k
  138.                 #    changed = True
  139.                 AR[fen]['result'] = update_best_case(best_case)
  140.                 AR[fen]['best_child'] = best_child
  141.                 changed = True
  142.  
  143.          ###   print(f"Position = {fen}, results = {best_case} {nones_present} => {AR[fen]['result']}")
  144.             if (fen == "8/8/3R4/8/8/5K2/8/4k3 b - -" or fen == "8/8/3R4/8/8/5K2/8/5k2 w - -"):
  145.                 print("^^^^^^^^")
  146.  
  147.            
  148.             # remove here
  149.             #break
  150.            
  151.             #if not changed:
  152.                 #break  # Pokud nedošlo k žádné změně, ukončíme smyčku
  153.  
  154.         #if not changed:
  155.             #break  # Ukončíme hlavní smyčku, pokud nedošlo ke změně v poslední iteraci
  156.    
  157.  
  158.  
  159. def print_draw_positions(AR):
  160.     """
  161.    Vytiskne všechny remízové pozice (hodnota 0) zaznamenané v slovníku AR.
  162.    """
  163.     print("Remízové pozice:")
  164.     for fen, value in AR.items():
  165.         if True or (value > 990 and value < 1000):
  166.             print(f"FEN>: {fen}, Hodnota: {value}","\n",chess.Board(fen),"<\n")
  167.  
  168. def find_path_to_end(AR, fen):
  169.     if AR[fen]['result'] is None:
  170.         print(f"Unfortunately, there is no path that is known to be the best")
  171.    
  172.     fen_i = fen
  173.     print(chess.Board(fen_i),"\n<")
  174.     path = fen
  175.     while AR[fen_i]['best_child'] is not None:
  176.         fen_i = AR[fen_i]['best_child']
  177.         print(chess.Board(fen_i),fen_i,AR[fen_i],"\n\n<<<")
  178.        
  179.         path = path + ", " + fen_i
  180.    
  181.     print(f"Path is: {path}")
  182.    
  183.  
  184.            
  185. def main():
  186.  
  187.     initial_fen = "1k6/5P2/2K5/8/8/8/8/8 w - - 0 1"
  188.     initial_fen_original = "8/8/8/8/3Q4/5K2/8/4k3 w - - 0 1"
  189.     initial_fen_mate_in_one_aka_one_ply = "3r1k2/5r1p/5Q1K/2p3p1/1p4P1/8/8/8 w - - 2 56"
  190.     initial_fen_mate_in_two_aka_three_plies = "r5k1/2r3p1/pb6/1p2P1N1/3PbB1P/3pP3/PP1K1P2/3R2R1 b - - 4 28"
  191.     initial_fen_mated_in_two_plies = "r5k1/2r3p1/p7/bp2P1N1/3PbB1P/3pP3/PP1K1P2/3R2R1 w - - 5 29"
  192.    
  193.     mate_in_two_aka_three_plies_simple = "8/8/8/8/3R4/5K2/8/4k3 w - - 0 1"
  194.     mated_in_one_aka_two_plies_simple = "8/8/3R4/8/8/5K2/8/4k3 b - - 1 1"
  195.     mate_in_one_aka_one_ply_simple = "8/8/3R4/8/8/5K2/8/5k2 w - - 2 2"
  196.  
  197.     initial_fen = mate_in_two_aka_three_plies_simple
  198.    
  199.    
  200.     initial_fen = "1k6/5P2/2K5/8/8/8/8/8 w - - 0 1"
  201.     initial_fen = "1k6/8/2K5/8/8/8/8/8 w - - 0 1"
  202.     initial_fen = "8/8/8/8/8/7N/1k5K/6B1 w - - 0 1"
  203.     initial_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  204.     initial_fen = "8/3k4/8/2K2R2/8/8/8/8 w - - 0 1"
  205.     initial_fen = "8/8/8/4k3/2K4R/8/8/8 w - - 0 1"
  206.    
  207.     simplified_fen = simplify_fen_string(initial_fen)
  208.    
  209.     board = chess.Board(initial_fen)
  210.     AR = {simplified_fen: {"result": None, "last_move": None, "children": None, "best_child": None}}  # Inicializace AR s počáteční pozicí
  211.    
  212.     update_AR_for_mate_in_k(board, AR, simplified_fen, max_k=58)  # Aktualizace AR
  213.    
  214.     #print_draw_positions(AR)
  215.     print(f"AR for initial fen is = {AR[simplified_fen]}")
  216.     find_path_to_end(AR, simplified_fen)
  217.    
  218.  
  219. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement