Ejemplo n.º 1
0
def run_case(args):
    C = random_cube()
    original = Cube(C)
    solver = Solver(C)

    if args % 100000 == 0:
        print(args[0])

    training_data = []
    try:
        # print("Solving\n", original)
        solver.solve()
    except Exception as e:
        print(e)

    if not C.is_solved():
        print("Failed to solve. Rerunning with DEBUG = True")
        solve.DEBUG = True
        solver = Solver(Cube(original))
        solver.solve()
    else:
        check = Cube(original)
        for move in solver.moves:
            move_string = str(check).replace("\n", "").replace(" ", "")
            training_data.append([move_string, move])
            check.sequence(move)
        # check.sequence(" ".join(solver.moves))
        assert check.is_solved()
        # solved_string = str(check).replace("\n","").replace(" ", "")
        # print(str(check))
        # print(SOLVED_CUBE_STR)
        # assert solved_string == SOLVED_CUBE_STR
    return training_data
Ejemplo n.º 2
0
def count_number_successful():
    successes = 0
    failures = 0

    # moves_made = []
    avg_opt_moves = 0
    avg_moves = 0
    avg_time = 0
    while True:
        C = random_cube()
        solver = Solver(C)
        try:
            start = time.time()
            solver.solve()
            duration = time.time() - start
        except Exception as e:
            pass

        if C.is_solved():
            opt_moves = optimize_moves(solver.moves)
            print(opt_moves[0])
            successes += 1
            avg_moves = (avg_moves * (successes - 1) +
                         len(solver.moves)) / float(successes)
            avg_time = (avg_time *
                        (successes - 1) + duration) / float(successes)
            avg_opt_moves = (avg_opt_moves * (successes - 1) +
                             len(opt_moves)) / float(successes)
            # moves_made.append(len(solver.moves))
        else:
            failures += 1
            print("Failed (%s): %s" % (successes + failures, C.flat_str()))
        total = float(successes + failures)
        if (total == 1 or total % 100 == 0) and C.is_solved():
            print(
                "%s: %s successes (%.3f%% passing)" %
                (int(total), successes, 100 * successes / total), )
            print("moves=%s avg_moves=%0.3f" %
                  (len(solver.moves), avg_moves), )
            print(
                "opt_moves=%s avg_opt_moves=%0.3f" %
                (len(opt_moves), avg_opt_moves), )
            print("time=%0.3f avg_time=%0.3f" % (duration, avg_time))
Ejemplo n.º 3
0
def run_case():
    C = random_cube()
    original = Cube(C)
    solver = Solver(C)
    try:
        print "Solving\n", original
        solver.solve()
    except Exception as e:
        print e

    if not C.is_solved():
        print "Failed to solve. Rerunning with DEBUG = True"
        solve.DEBUG = True
        solver = Solver(Cube(original))
        solver.solve()
    else:
        check = Cube(original)
        check.sequence(" ".join(solver.moves))
        assert check.is_solved()
        assert str(check) == SOLVED_CUBE_STR
Ejemplo n.º 4
0
class AutoAnnotator:
    def __init__(self, model_dir=DEFAULT_MODEL_DIR, data_dir=DEFAULT_DATA_DIR, gpu=-1):
        self.data_dir = data_dir
        self.dataset_file = os.path.join(data_dir, "dataset.json")
        self.solver = Solver(dirname=model_dir, gpu=gpu)
        self.dataset = {}
        if os.path.exists(self.dataset_file):
            with open(self.dataset_file, "r") as fp:
                self.dataset = json.load(fp)

    def run(self):
        for giffile in sorted(glob.glob(os.path.join(self.data_dir, "*.gif"))):
            key = os.path.basename(giffile)
            if key in self.dataset:
                entry = self.dataset[key]
                if 'text' in entry and len(entry['text']) != 0:
                    print("{}: annotation already exists. skip.".format(key))
                    continue
            text, bbox, score = self.solver.solve(giffile)
            self.dataset[key] = { 'file': key, 'text': text, 'bbs': bbox.tolist() }
        with open(os.path.join(self.data_dir, "dataset.json"), "w") as fp:
            json.dump(self.dataset, fp, indent=2)
    for line in gcode:
        if 'X' in line:
            xc.append(float(line.split('X')[1].split(' ')[0]))
        if 'Y' in line:
            yc.append(float(line.split('Y')[1].split(' ')[0]))

    return xc, yc


#########################

#And now to actually generate gcode

#First solve the puzzle
solver = Solver(puzzle_filename, words_filename)
paths = solver.solve()

#Generate and rotate gcode
gcode = generate_gcode(paths)
gcode = rotate_gcode(gcode)

#Write gcode file
gcode_file = open("puzzle.gcode", "w+")
for line in gcode:
    gcode_file.write(line)

gcode_file.close()

#Plot
xc, yc = get_all_coordinates(gcode)
Ejemplo n.º 6
0
def main():
    """ Main program for playing the game. """
    pg.init()
    clock = pg.time.Clock()
    fps = 60
    pg.display.set_caption('Tricky Circles')
    icon = pg.image.load('resources/icon.jpg')
    pg.display.set_icon(icon)

    # Create display
    screen = pg.display.set_mode(SCREEN_SIZE)

    # Load resources such as wallpaper and fonts
    bg = pg.image.load('resources/desert.jpg')
    font = pg.font.Font('resources/western.ttf', 30)
    font_big = pg.font.Font('resources/western.ttf', 50)

    # Create buttons
    space = 50  # Space in between action buttons: a, b, x
    button_x = pg.Rect((WIDTH / 2 - BUTTON_WIDTH / 2, 250), BUTTON_SIZE)
    button_a = pg.Rect((button_x.x - space - BUTTON_WIDTH, button_x.y),
                       BUTTON_SIZE)
    button_b = pg.Rect((button_x.x + space + BUTTON_WIDTH, button_x.y),
                       BUTTON_SIZE)

    button_solve = pg.Rect((10, 0), BUTTON_SIZE)
    button_reset = pg.Rect((BUTTON_WIDTH + 20, button_solve.y), BUTTON_SIZE)
    button_info = pg.Rect((WIDTH - BUTTON_WIDTH / 2, button_solve.y),
                          BUTTON_SMALL)

    button_difficulty = pg.Rect((WIDTH / 2 - BUTTON_WIDTH / 2, 0), BUTTON_SIZE)
    button_min = pg.Rect(button_difficulty.topleft, BUTTON_SMALL)
    button_plus = pg.Rect(button_difficulty.midtop, BUTTON_SMALL)

    buttons = {
        'A': button_a,
        'X': button_x,
        'B': button_b,
        'Solve': button_solve,
        'Reset': button_reset,
        '-': button_min,
        '+': button_plus,
        '?': button_info
    }

    # Create starting level
    difficulty = 4  # Number of circles
    level_maker = CreateLevels()
    level = level_maker.get_random(difficulty)
    solver = Solver(level)
    min_moves, _ = solver.solve()  # Minimum moves needed to solve level

    # Creates Drawer for drawing levels
    drawer = Drawer(screen, WIDTH, level)
    drawer.draw_level(font, bg, min_moves, buttons, animation=False)

    auto_solve = False

    while True:

        if level.circles == level.answer:  # Level is solved

            # Draw finish-screen, depending on how level was solved
            if auto_solve:
                new_level = drawer.draw_solved(font_big, "Try it yourself?")
                auto_solve = False
            elif level.counter == min_moves:
                new_level = drawer.draw_solved(font_big, "Perfect score!")
            else:
                new_level = drawer.draw_solved(
                    font_big, "Solved in {} moves!".format(level.counter))

            if new_level:
                # Start a new game
                print('New game')
                level = level_maker.get_random(difficulty)
                drawer.level = level
                solver = Solver(level)
                min_moves, _ = solver.solve()
            else:
                # Reset level to try again
                print('Retry level')
                level.reset()

            drawer.draw_level(font, bg, min_moves, buttons, animation=False)

        for event in pg.event.get():

            # Quit when exit-button is clicked
            if event.type == pg.QUIT:
                pg.quit()
                exit()

            if event.type == pg.MOUSEBUTTONDOWN:
                mouse_pos = event.pos  # Get mouse position

                # Checks if mouse position is over a button
                # Perform corresponding action
                if button_info.collidepoint(*mouse_pos):
                    print('Show info')
                    drawer.show_help()

                if button_a.collidepoint(*mouse_pos):
                    print('A clicked, ', level.counter + 1)
                    drawer.animate_ab(font, bg, min_moves, buttons, 'a')
                    level.click_a()
                if button_b.collidepoint(*mouse_pos):
                    print('B clicked, ', level.counter + 1)
                    drawer.animate_ab(font, bg, min_moves, buttons, 'b')
                    level.click_b()
                if button_x.collidepoint(*mouse_pos):
                    print('X clicked, ', level.counter + 1)
                    drawer.animate_x(font, bg, min_moves, buttons)
                    level.click_x()

                if button_reset.collidepoint(*mouse_pos):
                    print("Reset level")
                    level.reset()

                if button_difficulty.collidepoint(*mouse_pos):
                    changed = False

                    # Check whether - or + was clicked
                    if button_min.collidepoint(*mouse_pos):
                        if difficulty > 4:  # 4 is minimum
                            difficulty -= 1
                            changed = True
                    else:
                        if difficulty < 8:  # 8 is maximum
                            difficulty += 1
                            changed = True

                    if changed:  # When minimum/maximum was not exceeded
                        print("Set difficulty {}".format(difficulty))

                        # Create new level with new difficulty
                        level = level_maker.get_random(difficulty)
                        drawer.level = level
                        solver = Solver(level)
                        min_moves, _ = solver.solve()

                if button_solve.collidepoint(*mouse_pos):
                    print('Show solution')
                    auto_solve = True

                    # Get solution for current level-state
                    # Solution is represented by sequence of actions to perform
                    solver = Solver(level)
                    _, min_actions = solver.solve()

                    # Execute and animate each action separately
                    for action in min_actions:
                        if action == 'a':
                            drawer.animate_ab(font, bg, min_moves, buttons,
                                              'a')
                            level.click_a()
                        if action == 'b':
                            drawer.animate_ab(font, bg, min_moves, buttons,
                                              'b')
                            level.click_b()
                        if action == 'x':
                            drawer.animate_x(font, bg, min_moves, buttons)
                            level.click_x()

                        # Redraw Level after each animated action
                        drawer.draw_level(font,
                                          bg,
                                          min_moves,
                                          buttons,
                                          animation=False)
                        pg.display.update()
                        pg.time.delay(500)  # So that animation can be followed

                # Redraw Level after each event
                drawer.draw_level(font,
                                  bg,
                                  min_moves,
                                  buttons,
                                  animation=False)

        pg.display.update()
        clock.tick(fps)
Ejemplo n.º 7
0
def main():
    solver = Solver(inputs, debug=1)
    res = solver.solve(depth = 10)

    print(f"Best move: {res.best_move}")