from six.moves import input

from dlgo import goboard_fast as goboard
from dlgo import gotypes
from dlgo import minimax
from dlgo.utils import print_board, print_move, point_from_coords

BOARD_SIZE = 5


def capture_diff(game_state):
    black_stones = 0
    white_stones = 0
    for r in range(1, game_state.board.num_rows + 1):
        for c in range(1, game_state.board.num_cols + 1):
            p = gotypes.Point(r, c)
            color = game_state.board.get(p)
            if color == gotypes.Player.black:
                black_stones += 1
            elif color == gotypes.Player.white:
                white_stones += 1
    # 盤上の黒石と白石の数の差を計算する
    # プレイヤーがあ早々にパスしない限り、これはとった石の数の差と等しい
    diff = black_stones - white_stones                    # <1>

    # 黒の手番の場合、(黒石 - 白石)を返す
    if game_state.next_player == gotypes.Player.black:    # <2>
        return diff                                       # <2>
    # 白の手番の場合、(白石 - 黒石)を返す
    return -1 * diff                                      # <3>


def main():
    game = goboard.GameState.new_game(BOARD_SIZE)
    bot = minimax.AlphaBetaAgent(3, capture_diff)

    while not game.is_over():
        print_board(game.board)
        if game.next_player == gotypes.Player.white:
            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)


if __name__ == '__main__':
    main()
