예제 #1
0
파일: bot_vs_bot.py 프로젝트: vadozy/go-bot
def main():
    board_size = 7
    game: GameState = GameState.new_game(board_size)
    bots = {
        # gotypes.Player.black: RandomBot(),
        # gotypes.Player.black: AlphaBetaAgent(max_depth=0, ev_fn=eval_fn2),
        # gotypes.Player.white: RandomAgent(),
        # gotypes.Player.black: RandomAgent(),
        # gotypes.Player.white: FastRandomAgent(),
        # gotypes.Player.black: FastRandomAgent(),
        # gotypes.Player.black: AlphaBetaAgent(max_depth=1, ev_fn=eval_fn),
        gotypes.Player.black:
        MCTSAgent(2500, temperature=1.4, parallel_rollouts=True),
        gotypes.Player.white:
        AlphaBetaAgent(max_depth=3, ev_fn=eval_fn2),
    }
    while not game.is_over():
        # time.sleep(0.5)
        bot_move = bots[game.next_player].select_move(game)
        game = game.apply_move(bot_move)

        print('\033c')  # clear terminal [Linux and OS X]
        print_board(game.board)
        print_move(game.next_player.opposite, bot_move)
        print(compute_game_result(game))

    print(compute_game_result(game))
예제 #2
0
def simulate_game(black_player, white_player, model_index = -1, game_index = -1):

    game_file = None
    if model_index != -1 and game_index != -1:
        directory = 'games/model_' + str(model_index) + '/'
        if not os.path.exists(directory):
            os.makedirs(directory)
        game_file = open('games/model_' + str(model_index) + '/game_' + str(game_index + 1) + '.txt', 'w')

    moves = []
    game = goboard.GameState.new_game(19)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    captures = {
        gotypes.Player.black: 0,
        gotypes.Player.white: 0,
    }
    while not game.is_over():
        # print_board(game.board)
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)

        if game_file is not None:
            print_move_file(game.next_player, next_move, game_file)

        game,numberOfCaptures = game.apply_move(next_move)
        
        if game_file is not None:
            print_board_file(game.board, game_file)

        if game.next_player == gotypes.Player.white:
            captures[gotypes.Player.black] += numberOfCaptures
        else:
            captures[gotypes.Player.white] += numberOfCaptures

        if game_file is not None:
            game_result, score = scoring.compute_game_result(game,captures)
            game_file.write(str(score));
            game_file.write('\n')
            if numberOfCaptures != 0:
                game_file.write('capture event')
                game_file.write('\n')
            game_file.write('game_result ')
            game_file.write('W: ' + str(game_result.w + game_result.komi) + '\t' + 'B: ' + str(game_result.b) )
            game_file.write('\n\n')
    if game_file is not None:
        game_file.close()

    game_result,_ = scoring.compute_game_result(game,captures)
    # print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )
예제 #3
0
def run(board_size, first, second):
    start = time.time()

    # black_agent = random.choice([first, second])
    # white_agent = first if black_agent is second else first
    black_agent = first
    white_agent = second

    agents = {
        Player.black: black_agent,
        Player.white: white_agent,
    }

    game_state = GameState.new_game(board_size)
    next_move = None

    while not game_state.is_over() and (
            next_move is None or
            not next_move.is_pass):  # random bot too stupid to stop the game
        move_timer_start = time.time()
        next_move = agents[game_state.next_player].select_move(game_state)

        if game_state.next_player is Player.black and next_move.is_pass:
            next_move = agents[game_state.next_player].select_move(game_state)

        print(
            f'{game_state.next_player} made move in {time.time() - move_timer_start} s'
        )
        print(f'{game_state.next_player} selected {next_move}')

        game_state = game_state.apply_move(next_move)

        print(chr(27) + '[2J')  # clears board
        print_board(game_state.board)

        print('Estimated result: ')
        print(scoring.compute_game_result(game_state))

    print(f'Finished game in {time.time() - start} s')
    game_result = scoring.compute_game_result(game_state)

    print(game_result)

    first_won = False

    if game_result.winner == Player.black:
        if black_agent is first:
            first_won = True
    else:
        if white_agent is first:
            first_won = True

    if first_won:
        print("First agent wins!")
    else:
        print("Second agent wins!")
def eval_simulate_game(
    black_agent,
    white_agent,
    board_size,
):
    moves = []
    game = GameState.new_game(board_size)
    agents = {
        Player.black: black_agent,
        Player.white: white_agent,
    }

    num_moves = 0
    while (not game.is_over()) & (num_moves < 2 * board_size * board_size):
        agents[game.next_player].set_temperature(0.05)
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        game = game.apply_move(next_move)
        num_moves += 1

    print('number of moves: %d' % num_moves)
    print_board(game.board)
    game_result = scoring.compute_game_result(game)
    print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )
예제 #5
0
 def winner(self):
     if not self.is_over():
         return None
     if self.last_move.is_resign:
         return self.next_player
     game_result = compute_game_result(self)
     return game_result.winner
예제 #6
0
 def should_resign(self, game_state):
     self.moves_played += 1
     if self.moves_played:
         game_result = scoring.compute_game_result(self)
         if game_result.winner != self.own_color and game_result.winning_margin >= self.margin:
             return True
     return False
예제 #7
0
 def print_game_results(self, komi):
     results = compute_game_result(self, komi)
     print("With a komi of %.1f" % komi)
     print("White Final Score: %d" % results.w)
     print("Black Final Score: %.1f" % (results.b - komi))
     winner_str = "White" if results.winner == Player.white else "Black"
     print("%s wins by %.1f!" % (winner_str, results.winning_margin))
예제 #8
0
def simulate_game(black_player, white_player, board_size):
    moves = []
    game = GameState.new_game(board_size)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    num_moves = 0
    while not game.is_over():
        if num_moves < 16:
            # Pick randomly.
            agents[game.next_player].set_temperature(1.0)
        else:
            # Favor the best-looking move.
            agents[game.next_player].set_temperature(0.05)
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        game = game.apply_move(next_move)
        num_moves += 1

    print_board(game.board)
    game_result = scoring.compute_game_result(game)
    print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )
def main():
    board_size = 0
    while not 5 <= board_size <= 19:
        board_size = int(input("Enter Board Size (5X5 - 19X19) : "))

    game_state = goboard.GameState.new_game(int(board_size))
    bots = {
        gotypes.Player.black: agent.naive.RandomBot(),
        gotypes.Player.white: agent.naive.RandomBot(),
    }
    while not game_state.is_over():
        time.sleep(0.5)  # <1>

        print(chr(40) + "[2J")  # <2>
        print_board(game_state.board)
        bot_move = bots[game_state.next_player].select_move(game_state)
        print_move(game_state.next_player, bot_move)
        game_state = game_state.apply_move(bot_move)

    game_result = compute_game_result(game_state)
    white_score = game_result.w + game_result.komi
    print("\n")
    print('white score: {}'.format(white_score))
    print('black score: {}'.format(game_result.b))
    print('{} wins with margin: {}'.format(game_result.winner,
                                           game_result.winning_margin))
예제 #10
0
 def play(self):
     while not self._stopped:
         if self.game_state.next_player == self.our_color:
             self.play_our_move()
         else:
             self.play_their_move()
         print(chr(27) + "[2J")
         print_board(self.game_state.board)
         print("Estimated result: ")
         print(compute_game_result(self.game_state))
예제 #11
0
def main():
    board_size = 7
    game: GameState = GameState.new_game(board_size)
    bots = {
        # gotypes.Player.white: MCTSAgent(4000, temperature=1.4),
        gotypes.Player.white:
        MCTSAgent(5000, temperature=1.4, parallel_rollouts=True),
        gotypes.Player.black:
        MCTSAgent(5000, temperature=1.1, parallel_rollouts=True),
    }
    while not game.is_over():
        bot_move = bots[game.next_player].select_move(game)
        game = game.apply_move(bot_move)

        print('\033c')  # clear terminal [Linux and OS X]
        print_board(game.board)
        print_move(game.next_player.opposite, bot_move)
        print(compute_game_result(game))

    print(compute_game_result(game))
예제 #12
0
def simulate_game(black_player, white_player):
    moves = []
    game = GameState.new_game(BOARD_SIZE)
    agents = {Player.black: black_player, Player.white: white_player}
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        game = game.apply_move(next_move)
    game_result = scoring.compute_game_result(game)
    print(game_result)
    return GameRecord(moves=moves, winner=game_result.winner)
예제 #13
0
파일: goboard.py 프로젝트: Go-Brainer/v0.3
 def print_game_results(self, komi):
     if self.last_move.is_resign:
         resigned = "White" if self.next_player == Player.black else "Black"
         winner = "White" if resigned == "Black" else "Black"
         print("%s resigned so %s wins!" % (resigned, winner))
     else:
         results = compute_game_result(self, komi)
         print("With a komi of %.1f" % komi)
         print("White Final Score: %d" % results.w)
         print("Black Final Score: %.1f" % (results.b - komi))
         winner_str = "White" if results.winner == Player.white else "Black"
         print("%s wins by %.1f!" % (winner_str, results.winning_margin))
예제 #14
0
def simulate():
    assert os.path.exists('agz_bot_train.h5')

    # load known best bot
    if os.path.exists('agz_bot.h5'):
        with h5py.File('agz_bot.h5', 'r') as best_bot:
            best_agent = zero.load_zero_agent(best_bot)

    else:
        return True  # learner bot wins! ... by default, since there is no best currently

    # load learner bot
    with h5py.File('agz_bot_train.h5') as learn_bot:
        learner_agent = zero.load_zero_agent(learn_bot)

    # randomly decide first move
    black_agent = random.choice([best_agent, learner_agent])
    white_agent = best_agent if black_agent is learner_agent else learner_agent

    agents = {
        Player.black: black_agent,
        Player.white: white_agent,
    }

    game = GameState.new_game(
        (learner_agent.encoder.board_size, learner_agent.encoder.board_size))

    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        game = game.apply_move(next_move)

    game_result = scoring.compute_game_result(game)
    game = None

    del black_agent.model
    del white_agent.model

    black_agent = white_agent = None

    import gc

    K.clear_session()
    gc.collect()

    if game_result.winner == Player.black:
        if black_agent is best_agent:
            return False
    else:
        if white_agent is best_agent:
            return False

    return True  # learner won this round
예제 #15
0
def simulate_game(black_player, white_player):  # 9.18
    # moves = []
    game = GameState.new_game(BOARD_SIZE)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        # moves.append(next_move)
        game = game.apply_move(next_move)

    # print_board(game.board)
    game_result = scoring.compute_game_result(game)
    return game_result.winner
예제 #16
0
def simulate_game(black_player, white_player, board_size):
    moves = []
    game = GameState.new_game(board_size)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        game = game.apply_move(next_move)

    game_result = scoring.compute_game_result(game)

    return game_result.winner
예제 #17
0
def simulate_game(black_player, white_player, board_size):
    moves = []
    game = GameState.new_game(board_size)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        game = game.apply_move(next_move)

    #print_board(game.board)    Печать доски излишня.
    game_result = scoring.compute_game_result(game)
    print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )
예제 #18
0
def main():
    board_size = 9
    komi = 3.5
    game = goboard_slow.GameState.new_game(board_size)
    bots = {
        gotypes.Player.black: naive.RandomBot(),
        gotypes.Player.white: naive.RandomBot(),
    }
    while not game.is_over():
        time.sleep(.3)

        clear()
        print_board(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)
        game = game.apply_move(bot_move)

    results = compute_game_result(game, komi)
    print("With a komi of %.1f" % komi)
    print("White Final Score: %d" % results.w)
    print("Black Final Score: %.1f" % (results.b - results.komi))
    print(results.winner, "wins by %.1f points" % results.winning_margin)
예제 #19
0
def main():
    board_size = 9
    game: GameState = GameState.new_game(board_size)
    bot: Agent = RandomAgent()

    move: Move = None
    while not game.is_over():
        print('\033c')  # clear terminal [Linux and OS X]
        if move is not None:
            print_move(game.next_player, move)
        print_board(game.board)
        if game.next_player == gotypes.Player.black:
            print(compute_game_result(game))
            human_move_str: str = input('-- ')
            try:
                point = point_from_coords(human_move_str.strip().upper())
                move = Move.play(point)
            except (ValueError, Exception):
                move = Move.pass_turn()
        else:
            move = bot.select_move(game)
        game = game.apply_move(move)
예제 #20
0
def simulate_game(board_size, black_agent, black_collector, white_agent,
                  white_collector):
    print('Starting the game!')
    game = GameState.new_game(board_size)
    agents = {
        Player.black: black_agent,
        Player.white: white_agent,
    }

    black_collector.begin_episode()
    white_collector.begin_episode()
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        game = game.apply_move(next_move)

    game_result = scoring.compute_game_result(game)
    if game_result.winner == Player.black:
        black_collector.complete_episode(1)
        white_collector.complete_episode(-1)
    else:
        black_collector.complete_episode(-1)
        white_collector.complete_episode(1)
예제 #21
0
def main():
    while True:
        print("The board size(5-19)")
        board_size = int(input())
        if 19 >= board_size >= 5:
            break
        else:
            print("Wrong size,please input 5-19")
    game = goboard.GameState.new_game(board_size)
    bot = naive.RandomBot()
    while not game.is_over():
        print(chr(27) + "[2J")
        print_board(game.board)
        if game.next_player == gotypes.Player.black:
            human_move = input('-- ')
            point = point_from_coords(human_move.strip())
            move = goboard.Move.play(point)
        else:
            move = bot.select_move(game)
        print_move(game.next_player, move)
        game = game.apply_move(move)
    print(scoring.compute_game_result(game))
예제 #22
0
def main():
    board_size = 5
    pygame.init()
    pygame.display.set_caption('Goban')

    game = GameState.new_game(board_size)
    bots = {
        gotypes.Player.black: RandomBot(),
        gotypes.Player.white: AlphaBetaAgent(2, capture_diff),
    }
    while not game.is_over():
        #time.sleep(0.3)

        print(chr(27) + "[2J")
        print_board(game.board)
        GuiBoard.draw(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)
        game = game.apply_move(game.next_player, bot_move)

    print("winner is:", game.winner())
    print("score is is:", compute_game_result(game))
    input("Press Enter to continue...")
def simulate_game(black_player, white_player):
    moves = []
    game = GameState.new_game(BOARD_SIZE)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        # if next_move.is_pass:
        #     print('%s passes' % name(game.next_player))
        game = game.apply_move(next_move)

    print_board(game.board)
    game_result = scoring.compute_game_result(game)
    print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )
예제 #24
0
def main():
    while True:
        print("The board size(5-19)")
        board_size = int(input())
        if 19 >= board_size >= 5:
            break
        else:
            print("Wrong size,please input 5-19")
    game = goboard.GameState.new_game(board_size)
    bots = {
        gotypes.Player.black: naive.RandomBot(),
        gotypes.Player.white: naive.RandomBot(),
    }
    start = timeit.default_timer()
    while not game.is_over():
        time.sleep(0.3)
        print(chr(27) + "[2J")
        print_board(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)
        game = game.apply_move(bot_move)
    stop = timeit.default_timer()
    print(scoring.compute_game_result(game))
    print('Runtime:', stop - start, 'seconds')
예제 #25
0
 def semi_winner(self,captures):
     if self.last_move.is_resign:
         return self.next_player ,0
     game_result,score = compute_game_result(self,captures)
     return game_result.winner,score
예제 #26
0
def generate_game(board_size, game_id_str, rounds_per_move=10, c=2.0):
    start = time.time()
    print(f'Generating {game_id_str}...')

    game = GameState.new_game(board_size)
    encoder = zero.ZeroEncoder(board_size)

    # load current best agent, if any
    # has to be able to pass through cPickle which is why we don't just reuse it

    if os.path.exists('agz_bot.h5'):

        with h5py.File('agz_bot.h5') as bot_file:
            black_agent = zero.load_zero_agent(bot_file)
            white_agent = zero.load_zero_agent(bot_file)

    else:
        print(f'WARN: using default model to generate {game_id_str}')

        model = zero_model(board_size)

        black_agent = zero.ZeroAgent(model, encoder, rounds_per_move=rounds_per_move, c=c)
        white_agent = zero.ZeroAgent(model, encoder, rounds_per_move=rounds_per_move, c=c)

    agents = {
        Player.black: black_agent,
        Player.white: white_agent,
    }

    c1 = zero.ZeroExperienceCollector()
    c2 = zero.ZeroExperienceCollector()

    black_agent.set_collector(c1)
    white_agent.set_collector(c2)

    c1.begin_episode()
    c2.begin_episode()

    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        game = game.apply_move(next_move)

    game_result = scoring.compute_game_result(game)

    if game_result.winner == Player.black:
        c1.complete_episode(1)
        c2.complete_episode(-1)
    else:
        c1.complete_episode(-1)
        c2.complete_episode(1)

    combined = zero.combine_experience([c1, c2], board_size)

    c1 = c2 = game_result = None
    model = encoder = None
    game = None

    del black_agent.model
    del white_agent.model

    black_agent = white_agent = None

    import gc

    K.clear_session()
    gc.collect()

    return combined, game_id_str, time.time() - start
예제 #27
0
파일: goboard.py 프로젝트: gonanda/GameOfGo
 def margin(self):
     if not self.is_over():
         return None
     game_result = compute_game_result(self)
     return game_result.winning_margin