示例#1
0
def rbfs_search_function(f_node, f_limit, depth, method):
    global rbfs_md_step
    global rbfs_hu_step
    if board.check_goal(f_node.n):
        print("RBFS Goal Achieved:")
        if method == "MD":
            print("Steps: {}".format(rbfs_md_step))
        else:
            print("Steps: {}".format(rbfs_hu_step))
        board.draw_board(f_node.n)
        return "SUCCESS", f_node.f
    frontier = board.gen_frontier(f_node.n)
    if len(frontier) == 0:
        return "FAILURE", infinity
    successors = []
    for i in range(1, len(frontier), 2):
        if method == "MD":
            rbfs_md_step += 1
            successors.append(F_node(max((depth + heuristic.manhattan_distance_node(frontier[i])), f_node.f), frontier[i], depth))
        else:
            rbfs_hu_step += 1
            successors.append(F_node(max((depth + heuristic.hungarian_method(frontier[i])), f_node.f), frontier[i], depth))
    while True:
        successors.sort()
        best_node = successors[0]
        if best_node.f > f_limit:
            return "FAILURE", best_node.f
        if len(successors) == 1:
            alternative = successors[0]
        else:
            alternative = successors[1]
        result, best_node.f = rbfs_search_function(best_node, min(f_limit, alternative.f),depth+1,method)
        if result != "FAILURE":
            return result, best_node.f
示例#2
0
def ida_search_function(node,g,threshold,method):
    global md_step
    global hu_step
    if method == "MD":
        f_value = g + heuristic.manhattan_distance_node(node)
        md_step += 1
    else:
        f_value = g + heuristic.hungarian_method(node)
        hu_step += 1
    if (f_value >threshold):
        return f_value
    if (board.check_goal(node)):
        print("IDA* Goal achieved:")
        if method == "MD":
            print("Steps: {}" .format(md_step))
        else:
            print("Steps: {}" .format(hu_step))
        board.draw_board(node)
        return -1

    min = float("inf")
    frontier = board.gen_frontier(node)
    for i in range(1, len(frontier), 2):
        tempvalue = ida_search_function(frontier[i], g+1, threshold, method)
        if (tempvalue == -1):
            return -1
        if (tempvalue < min):
            min = tempvalue
    return min
示例#3
0
 def draw_canvas(self):
     draw_board(self.called_no, self.last_called_no)
     self.board.delete()
     self.board.configure(width=500, height=500)
     self.original = Image.open('board.png')
     self.original = self.original.resize((500, 500))
     self.image = ImageTk.PhotoImage(self.original)
     self.board.create_image(0, 0, image=self.image, anchor=NW, tags="IMG")
     self.board.grid(row=0, sticky=W + E + N + S)
     self.pack(fill=BOTH, expand=1)
示例#4
0
def solve(board, teleports, endpoint):
    # Set of boards already dealt with (hashes of board states)
    closed_set = {}
    # Set of boards we need to deal with (priorty queue of move strings)
    open_set = []
    counter = itertools.count()
    score = score_heuristic(board, teleports, endpoint, '')
    heapq.heappush(open_set, (score, next(counter), ''))

    i = 0
    while True:
        i += 1
        # Add ourselves to the already seen states
        if len(open_set) == 0:
            raise Exception("No solution!")
        cur_score, _, cur_move = heapq.heappop(open_set)
        cur_board, _, _ = move_to_board(board, teleports, endpoint, cur_move)

        h = hash_board(cur_board)
        if h in closed_set.keys():
            #print(f"Skipping iteration #{i}. Already evaluated on seperate route.")
            if cur_move >= closed_set[h]:
                continue  # Only skip if the other move is actualy equal or better
        closed_set[h] = cur_move

        print(gameboard.draw_board(cur_board, teleports, endpoint))
        nmoves = int(len(cur_move) / 2)
        print(f"Iteration #{i}. Move #{nmoves}. Score:{cur_score}")
        print(pprint_move(cur_move))

        # First let's find all snakes and possiblem oves
        colors = []
        for y, row in enumerate(board):
            for x, elem in enumerate(row):
                is_head = re.match('^snake ... 0', elem)
                if is_head:
                    colors.append(elem[6])
        next_moves = []
        for color in colors:
            for direction in ['w', 'a', 's', 'd']:
                next_moves.append(color + direction)

        for mv in next_moves:
            move = cur_move + mv
            try:
                next_board, _, _ = make_move(cur_board, teleports, endpoint,
                                             mv)
            except game.MissionComplete:
                return move  # Done! Horray
            except (game.InvalidMove, game.IllegalMove, game.UnsafeMove):
                continue
            else:
                h = hash_board(next_board)
                if h in closed_set.keys():  # Already seen this state (a loop)
                    continue
                add_to_cache(move, next_board)
                score = score_heuristic(next_board, teleports, endpoint, move)
                heapq.heappush(open_set, (score, next(counter), move))
示例#5
0
def execute(board, moves):
    colors = {'r': 'red', 'g': 'grn', 'b': 'blu'}
    directions = {'w': 'up', 'a': 'left', 's': 'down', 'd': 'right'}
    board, teleports, endpoint = load_board(board, padding=0)
    for snake, direction in zip(moves[0::2], moves[1::2]):
        board, teleports, endpoint = move_board_state(board, teleports,
                                                      endpoint, colors[snake],
                                                      directions[direction])
    return draw_board(board, teleports, endpoint, color=False,
                      fancy=False).strip()
示例#6
0
def update(board):
    """
    periodically updates the game, calls the graphics and receives user input
    """
    # sleep to make the game 60 fps
    board.clock.tick(30)

    # make the screen white
    board.screen.fill(board.white)
    
    # draw the board
    board.draw_board()
    
    for event in pg.event.get():
        # quit if the quit button was pressed
        if event.type == pg.QUIT:
            pg.quit(); sys.exit()
    
    #update the screen
    pg.display.flip()
示例#7
0
    def init_window(self):
        self.master.title('Krogulec')
        self.pack(fill=BOTH, expand=1)
        self.columnconfigure(0, weight=6)
        #self.columnconfigure(1, weight = 1)
        self.rowconfigure(0, weight=1)

        main_f = Frame(self, bg="GREY")
        main_f.grid(column=0, row=0, sticky=(N, S, E, W))
        self.update()

        leng, wid = main_f.winfo_height(), main_f.winfo_width()
        self.leng = leng
        self.rect_h = leng / 8

        if self.state == []:
            self.initial_state()

        board_img = draw_board(state=self.state, h=leng)
        board_handle = ImageTk.PhotoImage(board_img)
        b_board = Label(main_f, image=board_handle)
        b_board.image = board_handle
        b_board.bind("<Button-1>", self.select)
        b_board.place(x=(wid - leng) / 2, y=0)
示例#8
0
if __name__ == '__main__':
    blank_color = 0xffffff
    selected_color = None
    selected_node = None
    board_config = None
    master = Tk()
    canvas = Canvas(master, width=canvas_width, height=canvas_height, bg=canvas_bg_color, borderwidth=0, highlightthickness=0)
    canvas.pack()
    master.bind('<Q>', gui_close)
    master.bind('<q>', gui_close)
    master.bind('<r>', board_reset)
    master.bind('<a>', solution_replay_previous)
    master.bind('<d>', solution_replay_next)
    master.bind('<Button-1>', mouse_button_one)
    master.bind('<Button-2>', mouse_button_two)
    master.bind('<Button-3>', mouse_button_two)
    polygons = board.draw_board(0,0,canvas)
    if len(sys.argv) > 1:
        board_config = board_put_colors(polygons, canvas, sys.argv[1])
    else:
        board_config = {}
        for row in polygons:
            for p, shape in row:
                board_config[p] = int(canvas.itemcget(p, 'fill')[1:], 16)
    nodes = create_nodes(polygons, board_config)
    starting_cell, puzzle_solution = run_solver()
    solution_index = 0
    puzzle_colors = get_color_set()
    master.mainloop()
示例#9
0
        board, d = update_end(board, endpoint)
        dirty |= d

    if not any_snakes_exist(board):
        raise MissionComplete()

    return board, teleports, endpoint


if __name__ == '__main__':
    import sys
    from board import load_file, draw_board
    from textwrap import dedent
    board = load_file(sys.argv[1])
    while True:
        print(draw_board(*board))
        move = input('Choose a move (h for help)')
        if len(move) == 2:
            colors = {
                'r': 'red',
                'g': 'grn',
                'b': 'blu'}
            directions = {
                'w': 'up',
                'a': 'left',
                's': 'down',
                'd': 'right'}
            try:
                color = colors[move[0]]
            except KeyError:
                print(f"Invalid color {color}")
示例#10
0
 def update_image(self, event):
     new_board = draw_board(self.state, self.leng)
     new_board = ImageTk.PhotoImage(new_board)
     event.widget.configure(image=new_board)
     event.widget.image = new_board
示例#11
0
def genetic_process(gen, x):
    new_gen = []
    idx_max = int(len(gen) * 9 / 10)
    for i in range(0, idx_max):
        new_gen.append(gen[i])

    maxx = gen[0]
    for aa in range(0, x):
        new_gens = []

        for temp_gen in gen:
            child1 = []
            child2 = []

            #Selection
            idx_border = randint(1, (len(temp_gen) - 1))

            num_choose = randint(0, (len(new_gen) - 1))

            for i in range(0, idx_border):
                child1.append(temp_gen[i])
                child2.append(new_gen[num_choose][i])

            for i in range(idx_border, len(temp_gen)):
                child1.append(new_gen[num_choose][i])
                child2.append(temp_gen[i])

            #Mutation
            x_temp = randint(0, 7)
            y_temp = randint(0, 7)
            pos_temp = [x_temp, y_temp]
            while (is_overlapping(child1, pos_temp)):
                x_temp = randint(0, 7)
                y_temp = randint(0, 7)
                pos_temp = [x_temp, y_temp]

            idx_mut = randint(0, (len(child1) - 1))

            temp_child = [
                child1[idx_mut][0], child1[idx_mut][1], x_temp, y_temp
            ]
            child1[idx_mut] = temp_child

            while (is_overlapping(child2, pos_temp)):
                x_temp = randint(0, 7)
                y_temp = randint(0, 7)
                pos_temp = [x_temp, y_temp]

            idx_mut = randint(0, (len(child2) - 1))

            temp_child = [
                child2[idx_mut][0], child2[idx_mut][1], x_temp, y_temp
            ]
            child2[idx_mut] = temp_child

            if (count_all_attacks(child1)[0] > count_all_attacks(child2)[0]):
                new_gens.append(child2)
                temp = child2
            elif (count_all_attacks(child1)[0] < count_all_attacks(child2)[0]):
                new_gens.append(child1)
                temp = child1
            else:
                if (count_all_attacks(child1)[1] <
                        count_all_attacks(child2)[1]):
                    new_gens.append(child2)
                    temp = child2
                else:
                    temp = child1
                    new_gens.append(child1)

            if (count_all_attacks(maxx)[0] > count_all_attacks(temp)[0]):
                maxx = temp
            elif (count_all_attacks(maxx)[0] == count_all_attacks(temp)[0]):
                if (count_all_attacks(maxx)[1] < count_all_attacks(temp)[1]):
                    maxx = temp

        gen_temp = []
        for i in range(0, len(gen)):
            gen_temp.append(new_gens[i])

        gen = sortGen(gen_temp, calcFitness(gen_temp))[0]

    print(draw_board(maxx))
    print(*count_all_attacks(maxx))
示例#12
0

def choose_move():
    global turn, playerA, playerB, gn_current
    if turn:
        gn_current = playerA.move(gn_current)
    else:
        gn_current = playerB.move(gn_current)
    turn = not (turn)


def run_game():
    choose_move()


if __name__ == '__main__':
    fptr = open('output.txt', 'w')
    chessboard.draw_board1(gn_current.board())
    while not (gn_current.board().is_checkmate()):
        run_game()
        chessboard.draw_board(gn_current.board())
        print(gn_current.board())
    if turn:
        print('Gana blanco')
    else:
        print('Gana negro')

    fptr.write(str(components) + '\n')

    fptr.close()
示例#13
0
        next_moves = []
        for color in colors:
            for direction in ['w', 'a', 's', 'd']:
                next_moves.append(color + direction)

        for mv in next_moves:
            move = cur_move + mv
            try:
                next_board, _, _ = make_move(cur_board, teleports, endpoint,
                                             mv)
            except game.MissionComplete:
                return move  # Done! Horray
            except (game.InvalidMove, game.IllegalMove, game.UnsafeMove):
                continue
            else:
                h = hash_board(next_board)
                if h in closed_set.keys():  # Already seen this state (a loop)
                    continue
                add_to_cache(move, next_board)
                score = score_heuristic(next_board, teleports, endpoint, move)
                heapq.heappush(open_set, (score, next(counter), move))


if __name__ == '__main__':
    import sys
    board = gameboard.load_file(sys.argv[1])
    print(gameboard.draw_board(*board))
    sol = solve(*board)
    print("Solution Found!")
    print(pprint_move(sol))