示例#1
0
 def _do_ai_move(self, node=None):
     if node is None or self.game.current_node == node:
         mode = self.next_player_info.strategy
         settings = self.config(f"ai/{mode}")
         if settings is not None:
             generate_ai_move(self.game, mode, settings)
         else:
             self.log(f"AI Mode {mode} not found!", OUTPUT_ERROR)
示例#2
0
def play_game(black: AI, white: AI):
    players = {"B": black, "W": white}
    engines = {"B": black.get_engine(), "W": white.get_engine()}
    tag = f"{black.name} vs {white.name}"
    try:
        game = Game(Logger(),
                    engines,
                    game_properties={
                        "SZ": BOARDSIZE,
                        "PW": white.strategy,
                        "PB": black.strategy
                    })
        game.root.add_list_property("PW", [white.name])
        game.root.add_list_property("PB", [black.name])
        game.root.properties["AP"] = ["kt-selfplay"]
        start_time = time.time()
        while not game.end_result and game.current_node.depth < 300:
            p = game.current_node.next_player
            move, node = generate_ai_move(game, players[p].strategy,
                                          players[p].ai_settings)
        while not game.current_node.analysis_complete:
            time.sleep(0.001)
        game.game_id += f"_{game.current_node.format_score()}"
        if OUTPUT_SGF:
            sgf_out_msg = game.write_sgf("sgf_selfplay_simple/",
                                         trainer_config={
                                             "eval_show_ai": True,
                                             "save_feedback": [True],
                                             "eval_thresholds": [0]
                                         })
        else:
            sgf_out_msg = "<not saved>"
        print(
            f"{tag}\tGame finished in {time.time()-start_time:.1f}s @ move {game.current_node.depth} {game.current_node.format_score()} -> {sgf_out_msg}",
            file=sys.stderr,
        )
        score = game.current_node.score
        if score > 0.3:
            black.elo_comp.beat(white.elo_comp)
        elif score < -0.3:
            white.elo_comp.beat(black.elo_comp)
        else:
            black.elo_comp.tied(white.elo_comp)

        results[tag].append(score)
        all_results.append((black.name, white.name, score))

    except Exception as e:
        print(f"Exception in playing {tag}: {e}")
        print(f"Exception in playing {tag}: {e}", file=sys.stderr)
        traceback.print_exc()
        traceback.print_exc(file=sys.stderr)
示例#3
0
    def test_ai_strategies(self):
        katrain = KaTrainBase(force_package_config=True, debug_level=0)
        engine = KataGoEngine(katrain, katrain.config("engine"))

        game = Game(katrain, engine)
        n_rounds = 3
        for _ in range(n_rounds):
            for strategy in AI_STRATEGIES:
                settings = katrain.config(f"ai/{strategy}")
                move, played_node = generate_ai_move(game, strategy, settings)
                katrain.log(f"Testing strategy {strategy} -> {move}", OUTPUT_INFO)
                assert move.coords is not None
                assert played_node == game.current_node

        assert game.current_node.depth == len(AI_STRATEGIES) * n_rounds

        for strategy in AI_STRATEGIES:
            game = Game(katrain, engine)
            settings = katrain.config(f"ai/{strategy}")
            move, played_node = generate_ai_move(game, strategy, settings)
            katrain.log(f"Testing strategy on first move {strategy} -> {move}", OUTPUT_INFO)
            assert game.current_node.depth == 1
示例#4
0
     ])
     bx, by = game.board_size
     if num_passes >= MAX_PASS and game.current_node.depth - 2 * MAX_PASS >= bx + by:
         logger.log(f"Forced pass as opponent is passing {MAX_PASS} times",
                    OUTPUT_ERROR)
         pol = game.current_node.policy
         if not pol:
             pol = ["??"]
         print(
             f"DISCUSSION:OK, since you passed {MAX_PASS} times after the {bx+by}th move, I will pass as well [policy {pol[-1]:.3%}].",
             file=sys.stderr,
         )
         move = game.play(Move(None,
                               player=game.current_node.next_player)).move
     else:
         move, node = generate_ai_move(game, ai_strategy, ai_settings)
         logger.log(f"Generated move {move}", OUTPUT_ERROR)
     print(f"= {move.gtp()}\n")
     sys.stdout.flush()
     malkovich_analysis(game.current_node)
     continue
 elif line.startswith("play"):
     _, player, move = line.split(" ")
     node = game.play(Move.from_gtp(move.upper(), player=player[0].upper()),
                      analyze=False)
     logger.log(f"played {player} {move}", OUTPUT_ERROR)
 elif line.startswith("final_score"):
     logger.log("line=" + line, OUTPUT_ERROR)
     if "{" in line:
         gamedata_str = line[12:]
         game.root.set_property(