Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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(start_fen)}
- AR = {simplify_fen(start_fen): {'used': 0, 'to_end': None, '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...")
- print("Počáteční pozice:")
- print_board(start_fen)
- depth_1_positions = [] # Seznam pro ukládání pozic v hloubce 1
- # Generate all positions
- while M < N:
- M += 1
- current_fen = POZ[M]
- board.set_custom_fen(current_fen)
- simplified_current_fen = simplify_fen(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)}")
- if current_depth == 1:
- print("Všechny pozice v hloubce 1:")
- for pos in depth_1_positions:
- print_board(pos)
- print()
- depth_start_time = time.time()
- positions_at_depth[current_depth] += 1
- if current_depth == 1:
- depth_1_positions.append(current_fen)
- if AR[simplified_current_fen]['used'] == 0:
- AR[simplified_current_fen]['used'] = 1
- legal_moves = list(board.legal_moves)
- for move in legal_moves:
- board.push(move)
- POZ2 = board.fen()
- simplified_POZ2 = simplify_fen(POZ2)
- if simplified_POZ2 not in AR:
- N += 1
- POZ[N] = simplified_POZ2
- AR[simplified_POZ2] = {'used': 0, 'to_end': None, '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"Příklad pozice v hloubce {current_depth}:")
- print_board(current_fen)
- print(f"Generování pozic dokončeno. Celkový počet pozic: {N}")
- # Initial evaluation
- print("\nZačínám počáteční ohodnocení...")
- F_checkmate = 0
- F_stalemate = 0
- F_drawing = 0
- F_check = 0
- F_normal = 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():
- AR[simplified_current_fen]['to_end'] = -1000
- AR[simplified_current_fen]['type'] = 'checkmate'
- F_checkmate += 1
- elif board.is_stalemate():
- AR[simplified_current_fen]['to_end'] = 0
- AR[simplified_current_fen]['type'] = 'stalemate'
- F_stalemate += 1
- elif board.is_insufficient_material():
- AR[simplified_current_fen]['to_end'] = 0
- AR[simplified_current_fen]['type'] = 'drawing'
- F_drawing += 1
- elif board.is_check():
- AR[simplified_current_fen]['to_end'] = None
- AR[simplified_current_fen]['type'] = 'check'
- F_check += 1
- else:
- AR[simplified_current_fen]['to_end'] = None
- AR[simplified_current_fen]['type'] = 'normal'
- F_normal += 1
- print(f"Počet pozic v matu je {F_checkmate}")
- print(f"Počet pozic v patu je {F_stalemate}")
- print(f"Počet pozic v remíze je {F_drawing}")
- print(f"Počet pozic v šachu je {F_check}")
- print(f"Počet normálních pozic je {F_normal}")
- # Iterative evaluation
- print("\nZačínám iterativní ohodnocení...")
- uroven = 0
- while True:
- uroven += 1
- level_start_time = time.time()
- print(f"Výpočet v úrovni {uroven}")
- changed = False
- 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(current_fen)
- if AR[simplified_current_fen]['to_end'] is None or AR[simplified_current_fen]['to_end'] == 0:
- hod = -2000
- for move in board.legal_moves:
- board.push(move)
- POZ2 = board.fen()
- simplified_POZ2 = simplify_fen(POZ2)
- if simplified_POZ2 in AR and AR[simplified_POZ2]['to_end'] is not None:
- hod2 = -AR[simplified_POZ2]['to_end']
- if hod2 > hod:
- hod = hod2
- board.pop()
- if hod == 1001 - uroven:
- new_to_end = 1000 - uroven
- new_type = 'winning'
- elif hod == -1001 + uroven:
- new_to_end = -1000 + uroven
- new_type = 'losing'
- elif hod == 0:
- new_to_end = 0
- new_type = 'drawing'
- elif hod > -2000: # Pokud byl nalezen alespoň jeden platný tah
- new_to_end = hod
- new_type = 'normal'
- else:
- new_to_end = None
- new_type = None
- if new_to_end is not None and (AR[simplified_current_fen]['to_end'] != new_to_end or AR[simplified_current_fen]['type'] != new_type):
- AR[simplified_current_fen]['to_end'] = new_to_end
- AR[simplified_current_fen]['type'] = new_type
- changed = True
- 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)}")
- if not changed:
- print("Hodnocení ukončeno - žádné další změny.")
- break
- print(f"Celkem nalezeno {sum(1 for data in AR.values() if data['to_end'] is not None)} ohodnocených pozic")
- print("\nVýpočet dokončen.")
- return {fen: (data['to_end'], data['type']) for fen, data in AR.items() if data['to_end'] is not None}
- finally:
- stop_event.set()
- timer_thread.join()
- # Helper function to print the board
- def print_board(fen):
- board = CustomBoard(fen)
- print(board)
- # Najděte nejmenší kladnou hodnotu to_end ve všech FEN záznamech v AR
- def find_min_positive_value(AR):
- min_positive_value = float('inf')
- min_fen = None
- for fen, (value, type_pozice) in AR.items():
- if value is not None and value > 0 and value < min_positive_value:
- min_positive_value = value
- min_fen = fen
- if min_positive_value == float('inf'):
- print("Žádná kladná hodnota nebyla nalezena.")
- else:
- print(f"Nejmenší kladná hodnota: {min_positive_value}, FEN: {min_fen}")
- # Main execution
- # Main execution
- if __name__ == "__main__":
- start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
- start_fen = "7K/8/8/8/8/k7/8/7A w - - 0 1"
- # start_fen = "7K/8/8/2a5/8/1k6/8/7A w - - 0 1"
- start_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
- start_fen = "6K1/3E4/8/8/8/k7/8/8 w - - 0 1"
- start_fen = "8/5A2/8/8/2K5/8/ka6/8 w - - 0 1"
- start_fen = "8/8/8/2k5/8/8/1K6/3Q4 w - - 0 1"
- AR = calculate_optimal_moves(start_fen)
- find_min_positive_value(AR)
- # print("\nVýsledky:")
- # for hodnota in range(-996, -1001, -1): # Generuje hodnoty -996, -997, -998, -999, -1000
- # for fen, (fen_hodnota, typ_pozice) in AR.items():
- # if fen_hodnota == hodnota:
- # print(f"FEN: {fen}")
- # print(f"Hodnota: {fen_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
- # Print optimal moves
- current_fen = start_fen
- simplified_current_fen = simplify_fen(current_fen)
- simplified_current_fen1 = simplified_current_fen
- optimal_moves = []
- while True:
- board = CustomBoard(current_fen)
- if board.is_checkmate():
- print("Mat detekován!")
- break
- # Opravená část
- half_move_clock = current_fen.split()[-2]
- if board.is_insufficient_material() or (half_move_clock != '-' and int(half_move_clock) >= 100):
- if board.is_insufficient_material():
- print("Nedostatečný materiál detekován!")
- else:
- print("Remíza pravidlem 50 tahů detekována!")
- AR[simplified_current_fen] = (0, 'drawing') # Aktualizujeme AR pro tuto pozici
- break
- if simplified_current_fen not in AR:
- print(f"Pozice {simplified_current_fen} není v AR.")
- break
- current_value = AR[simplified_current_fen][0]
- if current_value == 0:
- print("Remíza dosažena!")
- break
- hod = -2000 if current_value > 0 else 2000
- best_fen = None
- for move in board.legal_moves:
- board.push(move)
- POZ2 = board.fen()
- simplified_POZ2 = simplify_fen(POZ2)
- if simplified_POZ2 in AR:
- hod2 = -AR[simplified_POZ2][0]
- if current_value > 0: # Silnější hráč
- if hod2 > hod:
- hod = hod2
- best_fen = simplified_POZ2
- else: # Slabší hráč
- if hod2 < hod:
- hod = hod2
- best_fen = simplified_POZ2
- board.pop()
- if best_fen is None:
- print("Žádný další tah nebyl nalezen.")
- break
- optimal_moves.append(best_fen)
- current_fen = best_fen
- simplified_current_fen = simplify_fen(current_fen)
- print("\nOptimální tahy:")
- for fen in reversed(optimal_moves):
- print_board(fen)
- hodnota, typ_pozice = AR[simplify_fen(fen)]
- print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
- print(fen)
- print("\n")
- print_board(simplified_current_fen1)
- hodnota, typ_pozice = AR[simplified_current_fen1]
- print(f"Hodnota: {hodnota}, Typ: {typ_pozice}")
- print(simplified_current_fen1)
- print("\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement