You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python-Chess输出最优走法与次优走法?

Python-Chess 获取最优与次优走法解决方案

要获取次优走法,不能仅用engine.play()(它只返回引擎认定的最优走法),需要改用engine.analyse()方法——该方法会返回包含多候选走法、对应评分的完整分析数据。以下是修改后的完整代码及关键说明:

核心修改点

  • 替换engine.play()为engine.analyse(),获取包含候选走法的详细分析结果
  • 从分析结果的pv字段提取最优走法,从variations字段提取次优走法及对应评分
  • 优化棋局读取逻辑,保留完整棋局对象以便准确还原每一步局面

修改后的代码

import chess
import chess.engine
import chess.pgn

# 初始化引擎与文件
engine = chess.engine.SimpleEngine.popen_uci("filelocation")
pgn_file = open("filelocation")
game_list = []

# 读取所有棋局(存储完整game对象,而非仅主变走法)
temp_game = chess.pgn.read_game(pgn_file)
while temp_game is not None:
    game_list.append(temp_game)
    temp_game = chess.pgn.read_game(pgn_file)

# 分析第一局棋(可扩展为遍历所有棋局)
current_game = game_list[0]
board = current_game.board()  # 从棋局初始局面开始
analysis_results = []

for move in current_game.mainline_moves():
    # 分析当前局面,获取详细数据
    info = engine.analyse(board, chess.engine.Limit(time=0.3))
    
    # 提取最优走法及评分
    best_move = info["pv"][0]
    best_score = info["score"].relative.score()  # 相对当前方的评分,正数为优势
    
    # 提取次优走法及评分(若引擎返回variations)
    second_best_move = None
    second_best_score = None
    if "variations" in info and len(info["variations"]) > 0:
        # variations中每个元素是(走法序列, 评分),取第一个次优变例
        second_best_move = info["variations"][0][0]
        second_best_score = info["variations"][0][1].relative.score()
    
    # 存储分析结果
    analysis_results.append({
        "current_fen": board.fen(),
        "best_move": str(best_move),
        "best_score": best_score,
        "second_best_move": str(second_best_move) if second_best_move else None,
        "second_best_score": second_best_score
    })
    
    # 推进棋局到下一步
    board.push(move)

# 输出分析结果
for idx, res in enumerate(analysis_results, 1):
    print(f"第{idx}步分析结果:")
    print(f"最优走法: {res['best_move']} (评分: {res['best_score']})")
    if res['second_best_move']:
        print(f"次优走法: {res['second_best_move']} (评分: {res['second_best_score']})")
    print("---")

# 清理资源
engine.quit()
pgn_file.close()

关键说明

  • engine.analyse()返回的info字典中,pv是引擎认定的最优走法序列(第一个元素为当前最优走法),variations是其他候选变例列表,每个元素包含走法序列和对应评分
  • score.relative.score()将评分转换为相对于当前行棋方的数值:正数表示当前方占优,负数表示对方占优,数值越大优势越明显
  • 若引擎未返回variations,次优走法会显示为None,可通过调整引擎参数(如增加分析时间、设置multipv=3)让引擎返回更多候选走法(例如engine.analyse(..., multipv=3)可返回前3优走法)

内容的提问来源于stack exchange,提问作者Oscar Oak Soe Aung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:15:41