예제 #1
0
def AI_match_forData():  #Tree based AI vs Tree based AI for data generating
    for problem_size in [1, 2, 3, 4, 5]:
        winners = []
        net_data = []  #The data to be stored, one for each problem size
        for game_num in range(10):
            if (problem_size == 1):
                mini_select = 'False'  #8*8 game
            else:
                mini_select = 'True'  #4*4 game
            new_game = ms1.chess_state(mini=mini_select, minitype=problem_size)
            player1 = treebased_AI_data(new_game, 'W')
            player2 = treebased_AI_data(new_game, 'B')
            turn = 0
            while (turn >= 0):
                print(problem_size, turn, winners)
                print('So far collected: ', len(net_data))
                if (turn % 2 == 0):
                    databatch = player1.make_option()
                    new_state = player1.AI.chessstate
                    player2.renew(
                        new_state
                    )  #We have to update game state for each AI once per turn
                else:
                    databatch = player2.make_option()
                    new_state = player2.AI.chessstate
                    player1.renew(new_state)
                net_data.extend(databatch)  #Update the data
                new_state.show_state()
                turn += 1
                if (player1.checkmate('B') == 1):  #White wins
                    winners.append('W')
                    break
                if (player2.checkmate('W') == 1):  #Black wins
                    winners.append('B')
                    break
                if (turn == 50):  #Time limit
                    current_state = player1.AI.chessstate
                    if (current_state.get_score('W') >
                            current_state.get_score('B')):
                        winners.append('W')
                    elif (current_state.get_score('W') <
                          current_state.get_score('B')):
                        winners.append('B')
                    else:
                        winners.append('Draw')
                    break
        print(winners)
        with open(
                'C:/Users/28529/Desktop/SU/Courses/AI/project/new code/netdata_'
                + str(problem_size) + '.pkl', 'wb') as fp:
            pickle.dump(net_data, fp,
                        pickle.HIGHEST_PROTOCOL)  #Store data into pickle files
        del net_data
예제 #2
0
def AI_match():  #Tree based AI vs Baseline AI
    White_count = [0, 0, 0, 0, 0]
    Black_count = [0, 0, 0, 0, 0]
    Draw_count = [0, 0, 0, 0, 0]
    for problem_size in [1, 2, 3, 4, 5]:
        winners = []
        for game_num in range(100):
            if (problem_size == 1):
                mini_select = 'False'  #8*8 game
            else:
                mini_select = 'True'  #4*4 game
            new_game = ms1.chess_state(mini=mini_select, minitype=problem_size)
            player1 = random_AI(new_game, 'W')
            player2 = treebased_AI(new_game, 'B')
            turn = 0
            while (turn >= 0):
                print(problem_size, turn, winners)
                if (turn % 2 == 0):
                    player1.make_option()
                    new_state = player1.AI.chessstate
                    player2.renew(
                        new_state
                    )  #We have to update game state for each AI once per turn
                else:
                    player2.make_option()
                    new_state = player2.AI.chessstate
                    player1.renew(new_state)
                new_state.show_state()
                turn += 1
                if (player1.checkmate('B') == 1):  #White wins
                    winners.append('W')
                    White_count[problem_size - 1] += 1
                    break
                if (player2.checkmate('W') == 1):  #Black wins
                    winners.append('B')
                    Black_count[problem_size - 1] += 1
                    break
                if (turn == 50):  #Time limit
                    current_state = player1.AI.chessstate
                    if (current_state.get_score('W') >
                            current_state.get_score('B')):
                        winners.append('W')
                        White_count[problem_size - 1] += 1
                    elif (current_state.get_score('W') <
                          current_state.get_score('B')):
                        winners.append('B')
                        Black_count[problem_size - 1] += 1
                    else:
                        winners.append('Draw')
                        Draw_count[problem_size - 1] += 1
                    break
        print(winners)
    label_list = [
        'Problem 1', 'Problem 2', 'Problem 3', 'Problem 4', 'Problem 5'
    ]  #Draw a figure to show results
    x = range(5)
    bar_width = 0.2
    index_1 = np.arange(len(White_count))
    index_2 = index_1 + bar_width
    index_3 = index_2 + bar_width
    plt.bar(index_1,
            height=White_count,
            width=bar_width,
            color='red',
            label='Baseline Wins')
    plt.bar(index_2,
            height=Black_count,
            width=bar_width,
            color='blue',
            label='Tree Wins')
    plt.bar(index_3,
            height=Draw_count,
            width=bar_width,
            color='green',
            label='Draw')
    plt.ylim(0, 100)
    plt.ylabel('Winning numbers')
    plt.xlabel('Problem sizes')
    plt.legend()
    plt.xticks(index_2, label_list)
    plt.show()
예제 #3
0
def AI_based_game(Mini, number, side):  #Human vs AI
    color = ''
    if (side == '1'):
        color = 'B'  #Because you have entered your side, then we pass AI the opposite side.
    elif (side == '2'):
        color = 'W'
    while (1):
        AI_select = input('AI: 1.Tree Based, 2.Random Choice'
                          )  #Choose the type of AI to fight
        if (AI_select == '1'):
            new_game = ms1.chess_state(mini=Mini, minitype=number)
            Game_AI = treebased_AI(new_game, color)
            break
        elif (AI_select == '2'):
            new_game = ms1.chess_state(mini=Mini, minitype=number)
            Game_AI = random_AI(new_game, color)
            break
        else:
            print('Invalid operation. ')

    turn = 0
    turnmod = ['B', 'W']
    moving_player = ['Black', 'White']
    AI_role = int(side) - 1
    #Player_role = abs(int(side) - 3) - 1
    while (turn < 50):
        turn += 1
        print('####### TURN ' + str(turn) + ' #######')
        Game_AI.show_state()
        print('>>>>>>>>>' + moving_player[turn % 2] + ' Moving')
        if (moving_player[turn % 2] == moving_player[AI_role]):
            Game_AI.make_option()
            valid = 1
        else:
            valid = 0
        while (valid == 0):
            print(
                'Please give command: 1.Make a move, 2.Swap two pieces, 3.Quit'
            )  # Select operation
            choice = input('Your Choice: ')
            if (choice == '3'):
                print('####### Game Over #######')  # Quit the game
                return 0
            elif (choice == '1'):  # Make a move
                piece = input('Type the name of piece you want to move: ')
                if (Game_AI.find_chess(piece) == 0
                    ):  # No such piece in the current list of pieces
                    print('Inoperable piece. ')
                    continue
                elif (Game_AI.find_chess(piece).side !=
                      turnmod[turn % 2]):  # The piece belongs to the opponent
                    print('Inoperable piece. ')
                    continue
                else:
                    goal = input(
                        'Type the destination where you want to move this piece: '
                    )
                    if (len(goal) != 2):  # Incorrect format
                        print('Invalid destination. ')
                        continue
                    elif ((goal[0] not in Game_AI.AI.chessstate.cols)
                          or (goal[1] not in Game_AI.AI.chessstate.rows)
                          ):  # No such position on chessboard
                        print('Invalid destination. ')
                        continue
                    else:
                        successful = Game_AI.AI.chessstate.one_move(
                            piece, goal)  # Try to move the chess
                        if (successful == 0):  # Move cannot be done
                            print('Invalid operation. ')
                            continue
                        else:
                            valid = 1  # One turn is accomplished

            elif (choice == '2'):
                piece1 = input(
                    'Type the name of the first piece you want to swap: ')
                if (Game_AI.find_chess(piece1) == 0):
                    print('Inoperable piece. ')
                    continue
                elif (Game_AI.find_chess(piece1).side != turnmod[turn % 2]):
                    print('Inoperable piece. ')
                    continue
                else:
                    piece2 = input(
                        'Type the name of the second piece you want to swap: ')
                    if (Game_AI.find_chess(piece2) == 0):
                        print('Inoperable piece. ')
                        continue
                    elif (Game_AI.find_chess(piece2).side !=
                          turnmod[turn % 2]):
                        print('Inoperable piece. ')
                        continue
                    elif (piece1 == piece2):
                        print('Please enter two different pieces. ')
                        continue
                    else:
                        Game_AI.AI.chessstate.one_swap(
                            piece1, piece2)  # Try to swap two pieces
                        valid = 1  # One turn is accomplished
            else:
                print('Invalid operation. ')
                continue
        if (Game_AI.checkmate(
                turnmod[(turn + 1) %
                        2]) == 1):  # Check if there is a checkmate
            print('>>>>>>>>>' + moving_player[turn % 2] + ' Wins! ')
            break
    print('####### Game Over #######')
    return 0
예제 #4
0
def AI_based_game(Mini, number):  #Initiate a real game
    color = 'W'  #For convenience, AIs always move first
    while (1):
        print('Please select two players in the game: ')
        print(
            ' 1.Tree Based AI, 2.Baseline AI, 3.Neural Network AI, 4.Manually')
        select1 = input('Player one: ')
        select2 = input('Player two: ')
        if ((select1 in ['1', '2', '3', '4'])
                and (select2 in ['1', '2', '3', '4'])):
            select1 = int(select1)
            select2 = int(select2)
            if ((select1 == select2) and (select1 == 4)):  #Completely Manual
                ms1.game_starts(Mini, number)
                return 0
            elif ((select1 != 4) and (select2 != 4)):  #AI match
                AI_match_forReal(number, select1, select2)
                return 0
            else:  #Human vs AI
                NN_flag = 0
                for selection in [select1, select2]:
                    if (selection != 4):
                        AI_select = selection
                        break
                if (AI_select == 1):
                    new_game = ms1.chess_state(mini=Mini, minitype=number)
                    Game_AI = ms2.treebased_AI(new_game, color)
                elif (AI_select == 2):
                    new_game = ms1.chess_state(mini=Mini, minitype=number)
                    Game_AI = ms2.random_AI(new_game, color)
                elif (AI_select == 3):
                    new_game = ms1.chess_state(mini=Mini, minitype=number)
                    Game_AI = NNbased_AI(new_game, color)
                    if (number == 1):
                        code = 'N'
                    else:
                        code = 'M' + str(number - 2)
                    net = chess_net(code)
                    net.load_state_dict(
                        tr.load(
                            'C:/Users/28529/Desktop/SU/Courses/AI/project/new code/model_'
                            + code + '.pth'))  # Load the network
                    NN_flag = 1
            break
        else:
            print('Invalid operation. ')

    turn = 0
    turnmod = ['B', 'W']
    moving_player = ['Black', 'White']
    AI_role = 1
    while (turn < 50):
        turn += 1
        print('####### TURN ' + str(turn) + ' #######')
        Game_AI.show_state()
        print('>>>>>>>>>' + moving_player[turn % 2] + ' Moving')
        if (moving_player[turn % 2] == moving_player[AI_role]):
            if (NN_flag == 1):
                Game_AI.make_option(net)
            else:
                Game_AI.make_option()
            valid = 1
        else:
            valid = 0
        while (valid == 0):
            print(
                'Please give command: 1.Make a move, 2.Swap two pieces, 3.Quit'
            )  # Select operation
            choice = input('Your Choice: ')
            if (choice == '3'):
                print('####### Game Over #######')  # Quit the game
                return 0
            elif (choice == '1'):  # Make a move
                piece = input('Type the name of piece you want to move: ')
                if (Game_AI.find_chess(piece) == 0
                    ):  # No such piece in the current list of pieces
                    print('Inoperable piece. ')
                    continue
                elif (Game_AI.find_chess(piece).side !=
                      turnmod[turn % 2]):  # The piece belongs to the opponent
                    print('Inoperable piece. ')
                    continue
                else:
                    goal = input(
                        'Type the destination where you want to move this piece: '
                    )
                    if (len(goal) != 2):  # Incorrect format
                        print('Invalid destination. ')
                        continue
                    elif ((goal[0] not in Game_AI.AI.chessstate.cols)
                          or (goal[1] not in Game_AI.AI.chessstate.rows)
                          ):  # No such position on chessboard
                        print('Invalid destination. ')
                        continue
                    else:
                        successful = Game_AI.AI.chessstate.one_move(
                            piece, goal)  # Try to move the chess
                        if (successful == 0):  # Move cannot be done
                            print('Invalid operation. ')
                            continue
                        else:
                            valid = 1  # One turn is accomplished

            elif (choice == '2'):
                piece1 = input(
                    'Type the name of the first piece you want to swap: ')
                if (Game_AI.find_chess(piece1) == 0):
                    print('Inoperable piece. ')
                    continue
                elif (Game_AI.find_chess(piece1).side != turnmod[turn % 2]):
                    print('Inoperable piece. ')
                    continue
                else:
                    piece2 = input(
                        'Type the name of the second piece you want to swap: ')
                    if (Game_AI.find_chess(piece2) == 0):
                        print('Inoperable piece. ')
                        continue
                    elif (Game_AI.find_chess(piece2).side !=
                          turnmod[turn % 2]):
                        print('Inoperable piece. ')
                        continue
                    elif (piece1 == piece2):
                        print('Please enter two different pieces. ')
                        continue
                    else:
                        Game_AI.AI.chessstate.one_swap(
                            piece1, piece2)  # Try to swap two pieces
                        valid = 1  # One turn is accomplished
            else:
                print('Invalid operation. ')
                continue
        if (Game_AI.checkmate(
                turnmod[(turn + 1) %
                        2]) == 1):  # Check if there is a checkmate
            print('>>>>>>>>>' + moving_player[turn % 2] + ' Wins! ')
            break
    print('####### Game Over #######')
    return 0
예제 #5
0
def AI_match_forReal(problem_size, AI1, AI2):  #Game for any two kinds of AI
    if (problem_size == 1):
        code = 'N'
    else:
        code = 'M' + str(problem_size - 2)
    if (problem_size == 1):
        mini_select = 'False'  # 8*8 game
    else:
        mini_select = 'True'  # 4*4 game
    new_game = ms1.chess_state(mini=mini_select, minitype=problem_size)
    netflags = [0, 0]
    if ((AI1 == 3) or (AI2 == 3)):  #We need a network
        net = chess_net(code)
        net.load_state_dict(
            tr.load(
                'C:/Users/28529/Desktop/SU/Courses/AI/project/new code/model_'
                + code + '.pth'))  # Load the network
        player1 = NNbased_AI(new_game, 'W')
        print('White: NN')
        netflags[0] = 1
        if (AI1 == AI2):  #Two NN-AIs
            player2 = NNbased_AI(new_game, 'B')
            print('Black: NN')
            netflags[1] = 1
        else:
            for item in [AI1, AI2]:
                if (item != 3):
                    another_select = item
                    break
            if (another_select == 1):
                player2 = ms2.treebased_AI(new_game, 'B')
                print('Black: Tree')
            else:
                player2 = ms2.random_AI(new_game, 'B')
                print('Black: Baseline')
    else:
        if (AI1 == 1):
            player1 = ms2.treebased_AI(new_game, 'W')
            print('White: Tree')
        else:
            player1 = ms2.random_AI(new_game, 'W')
            print('White: Baseline')
        if (AI2 == 1):
            player2 = ms2.treebased_AI(new_game, 'B')
            print('Black: Tree')
        else:
            player2 = ms2.random_AI(new_game, 'B')
            print('Black: Baseline')
    turn = 0
    while (turn >= 0):
        print('########## Turn: ', turn, ' ##########')
        if (turn % 2 == 0):
            if (netflags[0] == 1):
                player1.make_option(net)
            else:
                player1.make_option()
            new_state = player1.AI.chessstate
            player2.renew(
                new_state
            )  # We have to update game state for each AI once per turn
        else:
            if (netflags[1] == 1):
                player2.make_option(net)
            else:
                player2.make_option()
            new_state = player2.AI.chessstate
            player1.renew(new_state)
        key = input('Enter anything to continue: '
                    )  #Wait for inputs to go to the next turn
        new_state.show_state()
        turn += 1
        if (player1.checkmate('B') == 1):  # White wins
            print('White wins! ')
            break
        if (player2.checkmate('W') == 1):  # Black wins
            print('Black wins! ')
            break
        if (turn == 50):  # Time limit
            current_state = player1.AI.chessstate
            if (current_state.get_score('W') > current_state.get_score('B')):
                print('White wins! ')
            elif (current_state.get_score('W') < current_state.get_score('B')):
                print('Black wins! ')
            else:
                print('Draw! ')
            break
예제 #6
0
def AI_match_forTest():  #Network AI vs Tree_based AI
    for problem_size in [1, 2, 3, 4, 5]:  #Five problem sizes
        if (problem_size == 1):
            code = 'N'
        else:
            code = 'M' + str(problem_size - 2)
        net = chess_net(code)
        net.load_state_dict(
            tr.load(
                'C:/Users/28529/Desktop/SU/Courses/AI/project/new code/model_'
                + code + '.pth'))  # Load the network
        winners = []
        scores = []
        for game_num in range(100):
            if (problem_size == 1):
                mini_select = 'False'  # 8*8 game
            else:
                mini_select = 'True'  # 4*4 game
            new_game = ms1.chess_state(mini=mini_select, minitype=problem_size)
            player1 = NNbased_AI(new_game, 'W')
            player2 = ms2.treebased_AI(new_game, 'B')
            turn = 0
            while (turn >= 0):
                print(problem_size, turn, winners)
                print(scores)
                if (turn % 2 == 0):
                    player1.make_option(net)
                    new_state = player1.AI.chessstate
                    player2.renew(
                        new_state
                    )  # We have to update game state for each AI once per turn
                else:
                    player2.make_option()
                    new_state = player2.AI.chessstate
                    player1.renew(new_state)
                new_state.show_state()
                turn += 1
                current_state = player1.AI.chessstate
                if (player1.checkmate('B') == 1):  # White wins
                    winners.append('W')
                    scores.append(current_state.get_score('W'))
                    break
                if (player2.checkmate('W') == 1):  # Black wins
                    winners.append('B')
                    scores.append(current_state.get_score('W'))
                    break
                if (turn == 50):  # Time limit
                    current_state = player1.AI.chessstate
                    if (current_state.get_score('W') >
                            current_state.get_score('B')):
                        winners.append('W')
                        scores.append(current_state.get_score('W'))
                    elif (current_state.get_score('W') <
                          current_state.get_score('B')):
                        winners.append('B')
                        scores.append(current_state.get_score('W'))
                    else:
                        winners.append('Draw')
                        scores.append(current_state.get_score('W'))
                    break
        print(winners)
        bar_width = 0.2
        for i in range(len(scores)):
            c = 'blue'
            plt.bar(i + 1, height=scores[i], width=bar_width, color=c)
        plt.ylabel('Final Scores')
        plt.xlabel('Game played')
        plt.title('Problem Size ' + str(problem_size))
        plt.show()