예제 #1
0
파일: agent.py 프로젝트: mrbermell/ffai
class SearchAgent(Agent):
    tree: SearchTree

    def __init__(self, name):
        super().__init__(name)
        self.tree = None

    def act(self, game: Game):
        if self.tree is None:
            self.tree = SearchTree(deepcopy(game))
        else:
            self.tree.set_new_root(game)

        time_left = game.get_seconds_left()
        if time_left < 10:
            assert False

        # expand the tree
        start_time = perf_counter()
        while perf_counter() - start_time < 10:
            pass

        # pick action to return

    def new_game(self, game, team):
        self.tree = None

    def end_game(self, game):
        pass
예제 #2
0
파일: testing.py 프로젝트: ayrtonreis/AI
def main2():
    # my_node = Node(Grid(),0)
    # my_node.grid.setCellValue((3,3), 1)
    # my_node.print_grid()

    grid1 = Grid()
    grid1.setCellValue((0, 0), 1)
    grid2 = grid1.clone()
    grid2.setCellValue((0, 1), 1)  # child of node1
    grid3 = grid1.clone()
    grid3.setCellValue((0, 1), 2)  # child of node1
    grid4 = grid2.clone()
    grid4.setCellValue((0, 2), 1)  # child of node2
    grid5 = grid3.clone()
    grid5.setCellValue((0, 2), 1)  # child of node3

    node1 = Node(grid1, 0)
    node2 = Node(grid2, 0)
    node3 = Node(grid3, 0)
    node4 = Node(grid4, 0)
    node5 = Node(grid5, 0)

    node1.push_children(node2)
    node1.push_children(node3)
    node2.push_children(node4)
    node3.push_children(node5)

    my_tree = SearchTree(node1)

    my_tree.print_tree()
예제 #3
0
    def getMove(self, grid):
        node1 = Node(grid, 0)
        my_tree = SearchTree(node1)
        my_tree.build_tree(3)
        strategy = MiniMax(node1)
        alpha_beta = strategy.alpha_beta(3)

        return alpha_beta
예제 #4
0
파일: agent.py 프로젝트: mrbermell/ffai
    def act(self, game: Game):
        if self.tree is None:
            self.tree = SearchTree(deepcopy(game))
        else:
            self.tree.set_new_root(game)

        time_left = game.get_seconds_left()
        if time_left < 10:
            assert False

        # expand the tree
        start_time = perf_counter()
        while perf_counter() - start_time < 10:
            pass
예제 #5
0
 def __init__(self, inputPlayerId):
     super(AIPlayer, self).__init__(inputPlayerId, "Prunity")
     self.searchTree = SearchTree()
     self.searchTree.depthLimit = 1
     self.myTunnel = None
     self.myFood = None
     self.playerIndex = None
예제 #6
0
def test_console_input():
    search_tree = SearchTree()
    vocabulary = ReadData(DATA_PATH, VOCABULARY_FILENAME)
    print('vocabulary size: %d'% len(vocabulary))

    search_tree.construct(vocabulary);
    while True:
        input_word = raw_input("input (input 'q' to quit):")
        if input_word == 'q':
            break

        word_list = input_word.split(' ')
        for word in word_list:
            word = word.lower()
            print(word)
            candidate = search_tree.Candidate(word)
            print(candidate)
예제 #7
0
파일: testing.py 프로젝트: ayrtonreis/AI
def main4():
    grid1 = Grid()
    node1 = Node(grid1, 0)
    grid1.map[0][0] = 64
    grid1.map[1][0] = 2
    grid1.map[3][0] = 4

    grid1.map[0][1] = 0
    grid1.map[1][1] = 0
    grid1.map[3][1] = 0
    grid1.map[2][1] = 0
    grid1.map[2][2] = 0

    my_tree = SearchTree(node1)
    my_tree.build_tree(4)

    strategy = MiniMax(node1)
    alpha_beta = strategy.alpha_beta(5)

    print("\nMiniMax: ", node1.h_value, "\nDirection: ", alpha_beta)
예제 #8
0
파일: testing.py 프로젝트: ayrtonreis/AI
def main3():
    grid1 = Grid()
    node1 = Node(grid1, 0)
    grid1.map[0][0] = 2
    grid1.map[1][0] = 2
    grid1.map[3][0] = 4

    grid1.map[0][1] = 0
    grid1.map[1][1] = 0
    grid1.map[3][1] = 0
    grid1.map[2][1] = 0
    grid1.map[2][2] = 0

    my_tree = SearchTree(node1)
    my_tree.build_tree(4)
    my_tree.print_tree()

    strategy = MiniMax(node1)
    alpha_beta = strategy.alpha_beta(4)

    print("\nMiniMax: {0:.4f}".format(alpha_beta))

    print("---------> ", node1.h_value)
예제 #9
0
        return

    # b. rolling out (building the tree/adding the childs)
    for a in actions:
        new_state = cur_node.state.move(a)
        if new_state is not None:
            child = cur_node.add_child_state(new_state)
            dfs_expansion(child, max_depth, actions)


#####
# CROSSING PROBLEM
#####
# 1. Initialising the search tree
start_node = Node(START_STATE)
search_tree = SearchTree(start_node, sys.argv[1])

# 2. Building the entire tree (with restrictions)
dfs_expansion(search_tree.root, search_tree.max_depth, ACTIONS)

# 3. Searching for solutions
# a. depth-first search
print('Depth-First Search - DFS')
for i in range(N_EXPERIMENTS):
    search_tree.dfs(search_tree.root, TERMINAL_STATE)

# b. breadth-first search
print('Breadth-First Search - BFS')
for i in range(N_EXPERIMENTS):
    search_tree.bfs(search_tree.root, TERMINAL_STATE)
예제 #10
0

def dfs_expansion(cur_node, max_depth, actions):
    # a. checking the stop conditions
    if cur_node.depth == max_depth:
        return
    if is_terminal(cur_node.state):
        return

    # b. rolling out (building the tree/adding the childs)
    for a in actions:
        new_state = cur_node.state.move(a)
        if new_state is not None:
            child = cur_node.add_child_state(new_state)
            dfs_expansion(child, max_depth, actions)


#####
# CROSSING PROBLEM
#####
# 1. Initialising the search tree
search_tree = SearchTree(root=Node(START_STATE), max_depth=3)

# 2. Building the entire tree (with restrictions)
dfs_expansion(search_tree.root, search_tree.max_depth, ACTIONS)

# 3. Searching for solutions
#search_tree.show(search_tree.root)
result_node = search_tree.dfs(search_tree.root, TERMINAL_STATE)
print result_node
예제 #11
0
def test_doc(filename, max_word = 10000):

    f_log = open('test_doc.log','wb')

    print('test doc:%s start'%filename)
    vocabulary = ReadData(DATA_PATH, VOCABULARY_FILENAME)
    print('vocabulary size: %d'% len(vocabulary))

    save_out = sys.stdout;

    sys.stdout = f_log

    with open(filename, 'rb') as doc:
        data = doc.read()

    words = []
    for space_separated_fragment in data.strip().split():
        words.extend(_WORD_SPLIT.split(space_separated_fragment))
    search_tree = SearchTree()
    search_tree.construct(vocabulary)

    test_size = 0;
    top_true_num = [0, 0, 0]
    top_true_num_delete = [0,0,0]
    test_size_delete = 0;
    top_true_num_insert = [0,0,0]
    test_size_insert = 0
    top_true_num_replace = [0,0,0]
    test_size_replace = 0
    top_true_num_trans = [0,0,0]
    test_size_trans = 0

    for word in words:
        if not word.isalpha():
            continue
        if test_size>=max_word:
            break

        test_size = test_size + 1
        word_mis, misspell_type = rand_misspell(word)
        predict_pair_list = search_tree.Candidate(word_mis) #[str, edit_dis]
        predict_list = [x[0] for x in predict_pair_list]
        match = top_n_is_true(word, predict_list, 3)
        top_true_num = [a+b for (a, b) in zip(top_true_num, match)]
        if misspell_type == 'deletion':
            test_size_delete  = test_size_delete + 1
            top_true_num_delete = [a+b for (a, b) in zip(top_true_num_delete, match)]
        elif misspell_type == 'insertion':
            test_size_insert = test_size_insert + 1
            top_true_num_insert = [a+b for (a, b) in zip(top_true_num_insert, match)]
        elif misspell_type == 'replacement':
            test_size_replace = test_size_replace + 1
            top_true_num_replace = [a+b for (a, b) in zip(top_true_num_replace, match)]
        elif misspell_type == 'transposition':
            test_size_trans = test_size_trans + 1
            top_true_num_trans = [a+b for (a, b) in zip(top_true_num_trans, match)]
        else:
            print('pass')
            pass
        print('word: %s ->%s'% (word, word_mis))
        print predict_list
        print match

    accu = [float(x)/test_size for x in top_true_num]
    accu_delete = [float(x)/test_size_delete for x in top_true_num_delete]
    accu_insert = [float(x)/test_size_insert for x in top_true_num_insert]
    accu_replace = [float(x)/test_size_replace for x in top_true_num_replace]
    accu_trans = [float(x)/test_size_trans for x in top_true_num_trans]

    #print('accu:%f \t delete:%f \t insert:%f \t replace:%f \t trans:%f'%(accu, accu_delete, accu_insert, \
    #                                                                     accu_replace, accu_trans))

    print accu
    print accu_delete
    print accu_insert
    print accu_replace
    print accu_trans
    sys.stdout = save_out
    print('test doc end')
예제 #12
0
def test_vocabulary(test_size = 1000):
    f_log = open('test_doc.log','wb')

    print('test vocabulary...')
    vocabulary = ReadData(DATA_PATH, VOCABULARY_FILENAME)
    print('vocabulary size: %d'% len(vocabulary))

    save_out = sys.stdout;

    sys.stdout = f_log

    if test_size>vocabulary:
        test_size = vocabulary

    search_tree = SearchTree()
    search_tree.construct(vocabulary)

    top_true_num = [0, 0, 0]
    top_true_num_delete = [0,0,0]
    test_size_delete = 0;
    top_true_num_insert = [0,0,0]
    test_size_insert = 0
    top_true_num_replace = [0,0,0]
    test_size_replace = 0
    top_true_num_trans = [0,0,0]
    test_size_trans = 0

    for idx in range(0, test_size):
        word = random.choice(vocabulary)
        word_mis, misspell_type = rand_misspell(word)
        predict_pair_list = search_tree.Candidate(word_mis) #[str, edit_dis]
        predict_list = [x[0] for x in predict_pair_list]
        match = top_n_is_true(word, predict_list, 3)
        top_true_num = [a+b for (a, b) in zip(top_true_num, match)]
        if misspell_type == 'deletion':
            test_size_delete  = test_size_delete+1
            top_true_num_delete = [a+b for (a, b) in zip(top_true_num_delete, match)]
        elif misspell_type == 'insertion':
            test_size_insert = test_size_insert + 1
            top_true_num_insert = [a+b for (a, b) in zip(top_true_num_insert, match)]
        elif misspell_type == 'replacement':
            test_size_replace = test_size_replace + 1
            top_true_num_replace = [a+b for (a, b) in zip(top_true_num_replace, match)]
        elif misspell_type == 'transposition':
            test_size_trans = test_size_trans + 1
            top_true_num_trans = [a+b for (a, b) in zip(top_true_num_trans, match)]
        else:
            print('pass')
            pass
        print('word: %s ->%s'% (word, word_mis))
        print predict_list
        print match

    accu = [float(x)/test_size for x in top_true_num]
    accu_delete = [float(x)/test_size_delete for x in top_true_num_delete]
    accu_insert = [float(x)/test_size_insert for x in top_true_num_insert]
    accu_replace = [float(x)/test_size_replace for x in top_true_num_replace]
    accu_trans = [float(x)/test_size_trans for x in top_true_num_trans]

    #print('accu:%f \t delete:%f \t insert:%f \t replace:%f \t trans:%f'%(accu, accu_delete, accu_insert, \
    #                                                                     accu_replace, accu_trans))

    print accu
    print accu_delete
    print accu_insert
    print accu_replace
    print accu_trans
    sys.stdout = save_out

    print('test vocabulary end')
예제 #13
0
파일: Main.py 프로젝트: iamty7/VGo
def main():
    flag = 0
    lasx = 0
    lasy = 0
    NumofEnmy = 3
    NumofTurn = 1
    pygame.init()
    global Mps
    for i in range(len(Mps)):
        Mps[i] = list(Mps[i])

    screen = pygame.display.set_mode((xSiz * 50, ySiz * 50), 0, 32)

    for i in range(len(Mps)):
        for j in range(len(Mps[0])):
            block = pygame.image.load(dic1[Mps[i][j]]).convert()
            screen.blit(block, cor(j, i))

    pygame.display.update()

    while True:
        for event in pygame.event.get():
            if event == QUIT:
                exit()
            elif event.type == MOUSEBUTTONDOWN:
                localtion_keys = list(event.pos)
                localtion_keys[0] = localtion_keys[0] / 50 * 50
                localtion_keys[1] = localtion_keys[1] / 50 * 50
                if flag == 0:  # chose one to move
                    if Mps[localtion_keys[1] /
                           50][localtion_keys[0] / 50] == 'A' and (
                               localtion_keys[0] / 50,
                               localtion_keys[1] / 50) not in locked:
                        # making the enmy and enmy's rounding get red
                        block = pygame.image.load('pic/red_enmy.png').convert()
                        screen.blit(block, localtion_keys)
                        for i in range(4):
                            nexx = localtion_keys[0] / 50 + dx[i]
                            nexy = localtion_keys[1] / 50 + dy[i]
                            if nexx >= 0 and nexx < xSiz and nexy >= 0 and nexy < ySiz and Mps[
                                    nexy][nexx] != 'x':
                                block = pygame.image.load(
                                    dic2[Mps[nexy][nexx]]).convert()
                                screen.blit(block, [nexx * 50, nexy * 50])
                        flag = 1
                        lasx = localtion_keys[0] / 50
                        lasy = localtion_keys[1] / 50
                elif flag == 1:  # chose the coordinate to move
                    for i in range(4):  # back to normal arrounding the enmy
                        nexx = lasx + dx[i]
                        nexy = lasy + dy[i]
                        if nexx >= 0 and nexx < xSiz and nexy >= 0 and nexy < ySiz:
                            block = pygame.image.load(
                                dic1[Mps[nexy][nexx]]).convert()
                            screen.blit(block, [nexx * 50, nexy * 50])
                    if localtion_keys[0] / 50 == lasx and localtion_keys[
                            1] / 50 == lasy:  # don't move
                        block = pygame.image.load('pic/enmy.png').convert()
                        screen.blit(block, localtion_keys)
                        locked[(localtion_keys[0] / 50, localtion_keys[1] /
                                50)] = 1  # lock it until next turn
                        flag = 0
                        continue
                    move_success = 0
                    if Mps[localtion_keys[1] /
                           50][localtion_keys[0] / 50] != 'x' and Mps[
                               localtion_keys[1] / 50][localtion_keys[0] /
                                                       50] != 'A':
                        # move to a new coordinate and check if can move
                        for i in range(4):
                            nexx = localtion_keys[0] / 50 + dx[i]
                            nexy = localtion_keys[1] / 50 + dy[i]
                            if nexx == lasx and nexy == lasy:
                                if Mps[localtion_keys[1] /
                                       50][localtion_keys[0] /
                                           50] == '.':  # normal move
                                    #print nexx, nexy, localtion_keys
                                    block = pygame.image.load(
                                        'pic/none.png').convert()  #'A' -> '.'
                                    screen.blit(block, [lasx * 50, lasy * 50])
                                    Mps[lasy][lasx] = '.'
                                    block = pygame.image.load(
                                        'pic/enmy.png').convert()  #'.' -> 'A'
                                    screen.blit(block, localtion_keys)
                                    Mps[localtion_keys[1] /
                                        50][localtion_keys[0] / 50] = 'A'
                                    locked[(localtion_keys[0] / 50,
                                            localtion_keys[1] / 50)] = 1
                                elif Mps[localtion_keys[1] /
                                         50][localtion_keys[0] /
                                             50] == '$':  # destory a source
                                    block = pygame.image.load(
                                        'pic/none.png').convert()
                                    screen.blit(block, [lasx * 50, lasy * 50])
                                    Mps[lasy][lasx] = '.'
                                    block = pygame.image.load(
                                        'pic/enmy.png').convert()
                                    screen.blit(block, localtion_keys)
                                    Mps[localtion_keys[1] /
                                        50][localtion_keys[0] / 50] = 'A'
                                    locked[(localtion_keys[0] / 50,
                                            localtion_keys[1] / 50)] = 1
                                elif Mps[localtion_keys[1] /
                                         50][localtion_keys[0] /
                                             50] == 'D':  # attack
                                    block = pygame.image.load(
                                        'pic/none.png').convert()
                                    screen.blit(block, [lasx * 50, lasy * 50])
                                    Mps[lasy][lasx] = '.'
                                    block = pygame.image.load(
                                        'pic/none.png').convert()
                                    screen.blit(block, localtion_keys)
                                    Mps[localtion_keys[1] /
                                        50][localtion_keys[0] / 50] = '.'
                                    NumofEnmy -= 1
                                elif Mps[localtion_keys[1] / 50][
                                        localtion_keys[0] /
                                        50] == '@':  # attack enmy in source
                                    block = pygame.image.load(
                                        'pic/none.png').convert()
                                    screen.blit(block, [lasx * 50, lasy * 50])
                                    Mps[lasy][lasx] = '.'
                                    block = pygame.image.load(
                                        'pic/sor.png').convert()
                                    screen.blit(block, localtion_keys)
                                    Mps[localtion_keys[1] /
                                        50][localtion_keys[0] / 50] = '$'
                                    NumofEnmy -= 1
                                move_success = 1
                    if move_success == 0:  # return the begining states if unsuccessful move
                        block = pygame.image.load('pic/enmy.png').convert()
                        screen.blit(block, [lasx * 50, lasy * 50])
                    flag = 0  # chose next enmy to move
        pygame.display.update()
        if len(locked) == NumofEnmy:  # finished move
            if NumofEnmy == 0:
                print 'Game over !'
                break
            print 'computer turn(' + str(NumofTurn) + ')...'
            NumofTurn += 1
            locked.clear()

            #	using mcts searching way
            var = SearchTree(Mps)
            Mps = var.Get_Nex(len(var.root.son) * 5)
            #Mps = var.Get_Nex(1)

            #	debug output
            var.PrintTree(var.root)
            #var.PrintTree(var.root.son[0])

            # check the number of enmys and redraw the map
            NumofEnmy = 0
            for i in range(len(Mps)):
                for j in range(len(Mps[0])):
                    if Mps[i][j] == 'A':
                        NumofEnmy += 1
                    block = pygame.image.load(dic1[Mps[i][j]]).convert()
                    screen.blit(block, cor(j, i))
            Wp = var.root.W
            Np = var.root.N
            print 'rate of wining: ', (Np + Wp) / (2.0 * Np) * 100.0, '%'
            print 'your turn...'

            pygame.display.update()