Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chess
- import time
- import threading
- import psutil # Pro monitorování paměti
- def format_time(seconds):
- """Formats time in hours, minutes, and seconds."""
- return f"{int(seconds // 3600)}h {(int(seconds) % 3600) // 60}m {seconds % 60:.2f}s"
- def time_and_memory_tracker(start_time, stop_event):
- """Tracks elapsed time and memory usage, printing both every second."""
- while not stop_event.is_set():
- elapsed_time = time.time() - start_time
- memory_usage = psutil.Process().memory_info().rss / (1024 * 1024) # Převod na MB
- print(f"\rElapsed time: {format_time(elapsed_time)}, Memory usage: {memory_usage:.2f} MB", end='', flush=True)
- time.sleep(1)
- def simplify_fen(fen):
- """Simplifies a FEN string to only include position, turn, castling availability, and en passant target."""
- return ' '.join(fen.split(' ')[:4])
- # Definice funkce add_descendants_iteratively, initialize_game_tree, update_game_outcomes zůstávají stejné
- import chess
- def simplify_fen(fen):
- """Simplifies a FEN string to only include position, turn, castling availability, and en passant target."""
- return ' '.join(fen.split(' ')[:4])
- def add_descendants_iteratively(game_tree, fen_to_node_id):
- """Expands the game tree by iteratively adding legal move descendants of each game state."""
- queue = [(1, 0)]
- while queue:
- node_id, _ = queue.pop(0)
- if not node_id % 1000000:
- print("H")
- # break
- board = chess.Board(game_tree[node_id]['fen'] + " 0 1")
- for move in board.legal_moves:
- move = chess.Move(move.from_square, move.to_square, promotion=chess.QUEEN) if move.promotion else move
- board.push(move)
- simplified_fen = simplify_fen(board.fen())
- if simplified_fen not in fen_to_node_id:
- new_node_id = len(game_tree) + 1
- game_tree[new_node_id] = {
- 'fen': simplified_fen,
- 'moves_to_mate': None,
- 'parent': node_id,
- 'color': chess.WHITE if board.turn else chess.BLACK,
- 'result': None,
- 'processed': False,
- 'sequence': [],
- 'children': [],
- 'to_end': None,
- }
- fen_to_node_id[simplified_fen] = new_node_id
- game_tree[node_id]['children'].append(new_node_id)
- queue.append((new_node_id, 0))
- board.pop()
- def initialize_game_tree(initial_fen):
- """Initializes the game tree with the root node based on the initial FEN."""
- simplified_fen = simplify_fen(initial_fen)
- game_tree = {1: {'fen': simplified_fen, 'moves_to_mate': None, 'parent': 0,
- 'color': chess.WHITE if 'b' in initial_fen else chess.BLACK,
- 'result': None, 'processed': False, 'sequence': [], 'children': [], 'to_end': None}}
- fen_to_node_id = {simplified_fen: 1}
- return game_tree, fen_to_node_id
- def update_game_outcomes(game_tree):
- """Updates game outcomes based on the current board state for each node."""
- for node in game_tree.values():
- board = chess.Board(node['fen'] + " 0 1")
- if board.is_game_over():
- outcome = board.outcome()
- node['processed'] = True
- node['result'] = 1 if outcome and outcome.winner == chess.WHITE else -1 if outcome and outcome.winner == chess.BLACK else 0
- node['moves_to_mate'] = 0 if node['result'] != 0 else None
- node['to_end'] = 0
- def update_parent_preferences(node_id, game_tree, stronger):
- """Update parent preferences in the game tree based on minimizing or maximizing strategy."""
- node = game_tree[node_id]
- if node['processed']:
- return node['to_end'], node['moves_to_mate'], node['result']
- is_maximizing = node['color'] == stronger
- best_path_length = None
- best_child_id = None
- for child_id in node['children']:
- child_to_end, child_moves_to_mate, child_result = update_parent_preferences(child_id, game_tree, stronger)
- if child_moves_to_mate is None:
- continue
- if (is_maximizing and (best_path_length is None or child_moves_to_mate < best_path_length) and child_result == 1) or \
- (not is_maximizing and (best_path_length is None or child_moves_to_mate > best_path_length) and child_result == -1):
- best_path_length = child_moves_to_mate
- best_child_id = child_id
- if best_child_id is not None:
- node['sequence'] = [best_child_id]
- node['to_end'] = best_path_length + 1
- node['moves_to_mate'] = best_path_length + 1
- node['result'] = 1 if is_maximizing else -1
- else:
- node['sequence'] = []
- node['processed'] = True
- return node['to_end'], node['moves_to_mate'], node['result']
- def main():
- start_time = time.time()
- stop_event = threading.Event()
- # Start time tracking thread
- time_thread = threading.Thread(target=time_and_memory_tracker, args=(start_time, stop_event))
- time_thread.start()
- initial_fen = "8/2k5/8/5Q2/8/8/2K5/8 w - - 0 1"
- initial_fen = "8/2k5/8/3Q4/8/8/2K5/8 b - - 1 1"
- initial_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
- #cil: 8/6K1/k1P5/7p/8/8/8/8 b - - 1 1
- game_tree, fen_to_node_id = initialize_game_tree(initial_fen)
- add_descendants_iteratively(game_tree, fen_to_node_id)
- update_game_outcomes(game_tree)
- update_parent_preferences(1, game_tree, chess.WHITE)
- # Zde začleníme logiku pro tisk výsledků, která byla dříve mimo funkci main
- for key in range(1, len(game_tree) + 1): # Upraveno pro iteraci skrze definované klíče
- if game_tree[key]['to_end'] > 8: #is not None:
- print(f"{key}:: {game_tree[key]['to_end']} {game_tree[key]}\n{chess.Board(game_tree[key]['fen'])}<\n")
- stop_event.set()
- time_thread.join()
- print("\nFinal Output:")
- print(game_tree[1])
- # for key in range(1,60000):
- # if game_tree[key]['to_end'] != None: # and A[key]['to_end'] > 9:
- # print(f"{key}:: {game_tree[key]['to_end']} {game_tree[key]}\n{chess.Board(game_tree[key]['fen'])}<\n")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement