Advertisement
max2201111

last 11 == 11 with time

Mar 5th, 2024
673
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.32 KB | Science | 0 0
  1. import chess
  2. import time
  3. import threading
  4. import psutil  # Pro monitorování paměti
  5.  
  6. def format_time(seconds):
  7.     """Formats time in hours, minutes, and seconds."""
  8.     return f"{int(seconds // 3600)}h {(int(seconds) % 3600) // 60}m {seconds % 60:.2f}s"
  9.  
  10. def time_and_memory_tracker(start_time, stop_event):
  11.     """Tracks elapsed time and memory usage, printing both every second."""
  12.     while not stop_event.is_set():
  13.         elapsed_time = time.time() - start_time
  14.         memory_usage = psutil.Process().memory_info().rss / (1024 * 1024)  # Převod na MB
  15.         print(f"\rElapsed time: {format_time(elapsed_time)}, Memory usage: {memory_usage:.2f} MB", end='', flush=True)
  16.         time.sleep(1)
  17.  
  18. def simplify_fen(fen):
  19.     """Simplifies a FEN string to only include position, turn, castling availability, and en passant target."""
  20.     return ' '.join(fen.split(' ')[:4])
  21.  
  22. # Definice funkce add_descendants_iteratively, initialize_game_tree, update_game_outcomes zůstávají stejné
  23.  
  24. import chess
  25.  
  26. def simplify_fen(fen):
  27.     """Simplifies a FEN string to only include position, turn, castling availability, and en passant target."""
  28.     return ' '.join(fen.split(' ')[:4])
  29.  
  30. def add_descendants_iteratively(game_tree, fen_to_node_id):
  31.     """Expands the game tree by iteratively adding legal move descendants of each game state."""
  32.     queue = [(1, 0)]
  33.     while queue:
  34.         node_id, _ = queue.pop(0)
  35.         if not node_id % 1000000:
  36.             print("H")
  37.           #  break
  38.         board = chess.Board(game_tree[node_id]['fen'] + " 0 1")
  39.         for move in board.legal_moves:
  40.             move = chess.Move(move.from_square, move.to_square, promotion=chess.QUEEN) if move.promotion else move
  41.             board.push(move)
  42.             simplified_fen = simplify_fen(board.fen())
  43.             if simplified_fen not in fen_to_node_id:
  44.                 new_node_id = len(game_tree) + 1
  45.                 game_tree[new_node_id] = {
  46.                     'fen': simplified_fen,
  47.                     'moves_to_mate': None,
  48.                     'parent': node_id,
  49.                     'color': chess.WHITE if board.turn else chess.BLACK,
  50.                     'result': None,
  51.                     'processed': False,
  52.                     'sequence': [],
  53.                     'children': [],
  54.                     'to_end': None,
  55.                 }
  56.                 fen_to_node_id[simplified_fen] = new_node_id
  57.                 game_tree[node_id]['children'].append(new_node_id)
  58.                 queue.append((new_node_id, 0))
  59.             board.pop()
  60.  
  61. def initialize_game_tree(initial_fen):
  62.     """Initializes the game tree with the root node based on the initial FEN."""
  63.     simplified_fen = simplify_fen(initial_fen)
  64.     game_tree = {1: {'fen': simplified_fen, 'moves_to_mate': None, 'parent': 0,
  65.                      'color': chess.WHITE if 'b' in initial_fen else chess.BLACK,
  66.                      'result': None, 'processed': False, 'sequence': [], 'children': [], 'to_end': None}}
  67.     fen_to_node_id = {simplified_fen: 1}
  68.     return game_tree, fen_to_node_id
  69.  
  70. def update_game_outcomes(game_tree):
  71.     """Updates game outcomes based on the current board state for each node."""
  72.     for node in game_tree.values():
  73.         board = chess.Board(node['fen'] + " 0 1")
  74.         if board.is_game_over():
  75.             outcome = board.outcome()
  76.             node['processed'] = True
  77.             node['result'] = 1 if outcome and outcome.winner == chess.WHITE else -1 if outcome and outcome.winner == chess.BLACK else 0
  78.             node['moves_to_mate'] = 0 if node['result'] != 0 else None
  79.             node['to_end'] = 0
  80.  
  81.  
  82.  
  83.  
  84. def update_parent_preferences(node_id, game_tree, stronger):
  85.     """Update parent preferences in the game tree based on minimizing or maximizing strategy."""
  86.     node = game_tree[node_id]
  87.     if node['processed']:
  88.         return node['to_end'], node['moves_to_mate'], node['result']
  89.  
  90.     is_maximizing = node['color'] == stronger
  91.     best_path_length = None
  92.     best_child_id = None
  93.  
  94.     for child_id in node['children']:
  95.         child_to_end, child_moves_to_mate, child_result = update_parent_preferences(child_id, game_tree, stronger)
  96.        
  97.         if child_moves_to_mate is None:
  98.             continue
  99.  
  100.         if (is_maximizing and (best_path_length is None or child_moves_to_mate < best_path_length) and child_result == 1) or \
  101.            (not is_maximizing and (best_path_length is None or child_moves_to_mate > best_path_length) and child_result == -1):
  102.             best_path_length = child_moves_to_mate
  103.             best_child_id = child_id
  104.  
  105.     if best_child_id is not None:
  106.         node['sequence'] = [best_child_id]
  107.         node['to_end'] = best_path_length + 1
  108.         node['moves_to_mate'] = best_path_length + 1
  109.         node['result'] = 1 if is_maximizing else -1
  110.     else:
  111.         node['sequence'] = []
  112.  
  113.     node['processed'] = True
  114.     return node['to_end'], node['moves_to_mate'], node['result']            
  115.            
  116. def main():
  117.     start_time = time.time()
  118.     stop_event = threading.Event()
  119.    
  120.     # Start time tracking thread
  121.     time_thread = threading.Thread(target=time_and_memory_tracker, args=(start_time, stop_event))
  122.     time_thread.start()
  123.  
  124.     initial_fen = "8/2k5/8/5Q2/8/8/2K5/8 w - - 0 1"
  125.     initial_fen = "8/2k5/8/3Q4/8/8/2K5/8 b - - 1 1"
  126.     initial_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
  127.     #cil: 8/6K1/k1P5/7p/8/8/8/8 b - - 1 1
  128.     game_tree, fen_to_node_id = initialize_game_tree(initial_fen)
  129.     add_descendants_iteratively(game_tree, fen_to_node_id)
  130.     update_game_outcomes(game_tree)
  131.     update_parent_preferences(1, game_tree, chess.WHITE)
  132.    
  133.     # Zde začleníme logiku pro tisk výsledků, která byla dříve mimo funkci main
  134.     for key in range(1, len(game_tree) + 1):  # Upraveno pro iteraci skrze definované klíče
  135.         if game_tree[key]['to_end'] > 8: #is not None:
  136.             print(f"{key}:: {game_tree[key]['to_end']} {game_tree[key]}\n{chess.Board(game_tree[key]['fen'])}<\n")
  137.  
  138.     stop_event.set()
  139.     time_thread.join()
  140.  
  141.     print("\nFinal Output:")
  142.     print(game_tree[1])
  143.  
  144. #     for key in range(1,60000):
  145. #         if game_tree[key]['to_end'] != None: # and A[key]['to_end'] > 9:
  146. #             print(f"{key}:: {game_tree[key]['to_end']} {game_tree[key]}\n{chess.Board(game_tree[key]['fen'])}<\n")
  147.  
  148.    
  149.  
  150. if __name__ == "__main__":
  151.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement