def solve(state):
    raw = ''
    for i in state:
        for j in state[i]:
            raw += sign_conv[j]
    print("answer:", Cube.solve(raw))
    return Cube.solve(raw)
Exemple #2
0
def main():
    if len(sys.argv) == 2:
        print(solve(sys.argv[1]))
    elif len(sys.argv) == 3:
        print(solve(sys.argv[1], sys.argv[2]))
    else:
        print('Usage: kociemba <cubestring> [resulting_cubestring]\nfor example:\nkociemba DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD BBURUDBFUFFFRRFUUFLULUFUDLRRDBBDBDBLUDDFLLRRBRLLLBRDDF')
Exemple #3
0
def solve(config):
    six_face = []
    success = 0
    solution = []
    all_config = []
    for i in range(6):
        six_face.append(Counter(config[i]).most_common(1)[0][0])
    for i_1 in range(4):
        for i_2 in range(4):
            for i_3 in range(4):
                for i_4 in range(4):
                    for i_5 in range(4):
                        for i_6 in range(4):
                            problem = change(six_face[0], i_1) + change(
                                six_face[1], i_2) + change(
                                    six_face[2], i_3) + change(
                                        six_face[3], i_4) + change(
                                            six_face[4], i_5) + change(
                                                six_face[5], i_6)
                            #print(problem)
                            try:
                                solution = kociemba.solve(problem)
                                all_config.append(problem)
                                #print('adfgfd')
                                success += 1
                            except:
                                pass

    #problem=six_face[0]+six_face[1]+six_face[2]+six_face[3]+six_face[4]+six_face[5]
    try:
        solution = kociemba.solve(problem)
        success += 1
    except:
        pass
    return solution, success, all_config
Exemple #4
0
def main():
    if len(sys.argv) == 2:
        print(solve(sys.argv[1]))
    elif len(sys.argv) == 3:
        print(solve(sys.argv[1], sys.argv[2]))
    else:
        print(
            'Usage: kociemba <cubestring> [resulting_cubestring]\nfor example:\nkociemba DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD BBURUDBFUFFFRRFUUFLULUFUDLRRDBBDBDBLUDDFLLRRBRLLLBRDDF'
        )
Exemple #5
0
 def path(self, to=None):
     algorithm = solve(str(self), str(
         to)) if to is not None else solve(str(self))
     steps = []
     cube = Cube.from_iterable(str(self))
     for move in algorithm.split(' '):
         source = str(cube)
         cube(move)
         target = str(cube)
         steps.append({
             'source': source,
             'target': target,
             'move': move,
         })
     return algorithm, steps
    def solve(self):

        if not self.lock:
            if not self.safe():
                return
            else:
                clean.destroy(False,
                             [ui.solve_label,
                              ui.chrono_software,
                              ui.chrono_robot])

                timer.start()
                return_code = kociemba.solve(self.__get__())
                timer.stop()

                ui.solve_label = Label(ui.board_parent, text="» " + return_code, font=ui.mini_ui_font, bg='#000', fg='#00C000')
                ui.solve_label.place(x=24, y=870)

                text = "» The algorithm has solved the Rubik's cube in " + str(round(timer.interval, 3)) + " seconds with " + str(len(return_code.split())) + ' moves'

                ui.chrono_software = Label(ui.board_parent, text=text, font=ui.mini_ui_font, bg='#000', fg='#FFFFFF')
                ui.chrono_software.place(x=827, y=830)

                timer.start()
                # SEND_TO_ROBOT()
                timer.stop()

                ui.chrono_robot = Label(ui.board_parent, text="» The robot has solved the Rubik's cube in " + str(round(timer.interval, 3)) + " seconds", font=ui.mini_ui_font, bg="#000", fg="#FFFFFF")
                ui.chrono_robot.place(x=827, y=850)
Exemple #7
0
def solve(cube):
    solution = kociemba.solve(cube.replace(' ', ''))
    # solution = "L' B' U R' L U2 D2 F' R' B' D R2 U2 F2 L2 F2 U2 L2 U"
    lists = solution.split(' ')
    i = 0
    while i <= len(lists) - 1:
        if len(lists[i]) == 2:
            if lists[i][1] == "'":
                lists[i] = lists[i][0].lower()
            else:
                lists[i] = lists[i][0]
                lists.insert(i, lists[i])
        i += 1
    str1 = ''.join(lists)
    # str1 = str(lists).replace("'","")
    #print(str1)

    lists.reverse()
    for i in range(len(lists)):
        item = lists[i]
        if item >= 'A' and item <= 'Z':
            lists[i] = item.lower()
        else:
            lists[i] = item.upper()
    str2 = ''.join(lists)
    # str2 = str(lists).replace("'","")
    #print(str2)
    return str1, str2
Exemple #8
0
def solve_fast(cube, max_depth=24):
    assert isinstance(cube, pycuber.Cube)
    coloring = str(cube).replace("[", "").replace("]", "").replace("   ", " ")
    coloring = coloring.split("\n")
    seq = coloring[0].strip() + coloring[1].strip() + coloring[2].strip()
    seq += coloring[3][6:9]
    seq += coloring[4][6:9]
    seq += coloring[5][6:9]
    seq += coloring[3][3:6]
    seq += coloring[4][3:6]
    seq += coloring[5][3:6]
    seq += coloring[6][3:6]
    seq += coloring[7][3:6]
    seq += coloring[8][3:6]
    seq += coloring[3][:3]
    seq += coloring[4][:3]
    seq += coloring[5][:3]
    seq += coloring[3][9:12]
    seq += coloring[4][9:12]
    seq += coloring[5][9:12]
    seq = seq.replace("y", "U")
    seq = seq.replace("g", "F")
    seq = seq.replace("w", "D")
    seq = seq.replace("r", "L")
    seq = seq.replace("o", "R")
    seq = seq.replace("b", "B")
    return kociemba.solve(seq, max_depth=max_depth)
 def solve(self):
     solution = None
     try:
         solution = kociemba.solve(str(self))
     except:
         pass
     return solution
Exemple #10
0
def solve1(sequence):

    for i in range(len(sequence)):
        Frequencies(sequence[i])

    start_time = time.time()
    #rgb = Camera_Activation()
    #c = [' ']*rgb.shape[0]
    # print c ############################
    #color = [' ']*rgb.shape[0]
    #Range(rgb,c,color)
    #string = ''.join(c)
    #print string
    #string = string[:4] + 'U' + string[4:]
    #string = string[:13] + 'R' + string[13:]
    #string = string[:22] + 'F' + string[22:]
    #string = string[:31] + 'D' + string[31:]
    #string = string[:40] + 'L' + string[40:]
    #string = string[:49] + 'B' + string[49:]

    #print string

    solve_moves = kociemba.solve(
        'DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD')

    #solve_moves = solve_moves.split(' ')
    #Tkinter(color,solve_moves, 0,0)

    for i in range(len(solve_moves)):
        Frequencies(solve_moves[i])

    end_time = time.time()

    diff = (end_time - start_time)
    Tkinter1(solve_moves, ("%.2f" % diff), 1)
Exemple #11
0
    def Done(self):
        s = ["B", "U", "R", "F", "D", "L"]
        cube = "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB"
        list1 = list(cube)

        for j in range(0, 54):
            list1[j] = s[self.i[j]]

        cube = ''.join(list1)
        s = kociemba.solve(cube)
        print(s)

        i = 0
        s += ' '
        while (i < len(s)):
            if (s[i + 1] == ' '):
                arduino.write(s[i].encode('utf-8'))
                i += 2
            elif (s[i + 1] == "'"):
                arduino.write((s[i].lower()).encode('utf-8'))
                i += 3
            else:
                if (s[i] == 'R'): arduino.write(b'1')
                elif (s[i] == 'L'): arduino.write(b'2')
                elif (s[i] == 'B'): arduino.write(b'3')
                elif (s[i] == 'F'): arduino.write(b'4')
                elif (s[i] == 'U'): arduino.write(b'5')
                elif (s[i] == 'D'): arduino.write(b'6')
                i += 3

        sys.exit(app.exec_())
Exemple #12
0
def rubik_cv():
    """
    main code execution
    """

    faces = detect_faces()
    # To skip face color detection and use a preset uncoment the following lines and comment the preceding line.

    # from color_enum import Color
    # faces = [[[Color.WHITE, Color.WHITE, Color.WHITE], [Color.GREEN, Color.GREEN, Color.GREEN], [Color.GREEN, Color.GREEN, Color.GREEN]],
    #          [[Color.RED, Color.RED, Color.RED], [Color.RED, Color.RED,
    #                                               Color.RED], [Color.RED, Color.RED, Color.RED]],
    #          [[Color.YELLOW, Color.YELLOW, Color.YELLOW], [Color.BLUE,
    #                                                        Color.BLUE, Color.BLUE], [Color.BLUE, Color.BLUE, Color.BLUE]],
    #          [[Color.ORANGE, Color.ORANGE, Color.ORANGE], [Color.ORANGE, Color.ORANGE,
    #                                                        Color.ORANGE], [Color.ORANGE, Color.ORANGE, Color.ORANGE]],
    #          [[Color.BLUE, Color.BLUE, Color.BLUE], [Color.WHITE, Color.WHITE,
    #                                                  Color.WHITE], [Color.WHITE, Color.WHITE, Color.WHITE]],
    #          [[Color.GREEN, Color.GREEN, Color.GREEN], [Color.YELLOW, Color.YELLOW, Color.YELLOW], [Color.YELLOW, Color.YELLOW, Color.YELLOW]]]

    print(faces)
    cube = reconstruct(faces)
    print(cube)
    solution = kociemba.solve(cube)
    print(solution)

    gl_app = OpenGLApp(solution)
    gl_app.run()
Exemple #13
0
def solve(scanner, motors):
    """scan the cube, get a solution from kociemba, then execute it on the robot."""
    logging.info("Scanning...")
    t0 = round(time.time() * 1000)
    state_str = scanner.get_state_string(motors)
    t1 = round(time.time() * 1000)
    logging.info("Scanned state: " + state_str)

    time.sleep(1)

    logging.info("Solving...")
    t2 = round(time.time() * 1000)
    solution = kociemba.solve(state_str)
    t3 = round(time.time() * 1000)
    logging.info("Solution: " + solution)

    logging.info("Executing...\n")
    t4 = round(time.time() * 1000)
    motors.execute(solution)
    t5 = round(time.time() * 1000)

    logging.info('Scan time: {:d}ms'.format(t1 - t0))
    logging.info('Solve time: {:d}ms'.format(t3 - t2))
    logging.info('Execution time: {:d}ms'.format(t5 - t4))

    return(0)
Exemple #14
0
    def run(self):
        state = webcam.scan()
        if not state:
            print('Solver Error, you didnt scan the 6 sides of the cube.')
            print('Make sure you scan all faces of the cube please')
            print('try again')
            nelxd(1)
        unsolved = combine.sides(state)
        try:
            solution = kociemba.solve(unsolved)
            length = len(solution.split(' '))
        except Exception as err:
            print('Solver Error, you didnt scan the 6 sides of the cube.')
            print('Make sure you scan all faces of the cube please')
            print('try again')
            nelxd(1)

        print('===================   S O L U T I O N    ===================')
        print(
            'Starting position \n FRONT: GREEN MIDDLE CUBIE /n TOP: WHITE MIDDLE CUBIE'
        )
        print(solution, '({0} moves)'.format(length), '\n')

        if self.ezsolve:
            handmade = normalize.algorithm(solution, self.language)
            for index, text in enumerate(handmade):
                print('{}. {}'.format(index + 1, text))
        nelxd(0)
Exemple #15
0
def main():
    if len(sys.argv) > 1:
        print(solve(sys.argv[1]))
    else:
        print(
            'Usage: kociemba <cubestring>\nfor example:\nkociemba DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD'
        )
Exemple #16
0
    def solve(self):
        """utiliza el metodo de kociemba para obtener la solucion"""

        kociemba_sequence = self.kociemba_state()
        solution = kociemba.solve(kociemba_sequence)
        self.mov_sq(solution)
        return solution
Exemple #17
0
Fichier : qbr.py Projet : muts/qbr
    def run(self):
        state         = webcam.scan()
        if not state:
            print('\033[0;33m[QBR SCAN ERROR] Ops, you did not scan in all 6 sides.')
            print('Please try again.\033[0m')
            Die(1)

        unsolvedState = combine.sides(state)
        try:
            algorithm     = kociemba.solve(unsolvedState)
            length        = len(algorithm.split(' '))
        except Exception as err:
            print('\033[0;33m[QBR SOLVE ERROR] Ops, you did not scan in all 6 sides correctly.')
            print('Please try again.\033[0m')
            Die(1)

        print('-- SOLUTION --')
        print('Starting position:\n    front: green\n    top: white\n')
        print(algorithm, '({0} moves)'.format(length), '\n')

        if self.humanize:
            manual = normalize.algorithm(algorithm, self.language)
            for index, text in enumerate(manual):
                print('{}. {}'.format(index+1, text))
        Die(0)
Exemple #18
0
    def __generate_handwritten_solution_from_cube_state(
            self, cube_centers, rubiks_labels):
        """
        Generate movement solution for the robot's arms. This method returns the sequence of
        steps required for the robot to solve the cube.

        :param cube_centers: A 6-element list containing the numeric labels for each face's center.
        :param rubiks_labels: Flattened Rubik's cube labels in the order expected by the muodov/kociemba library.
        These labels are numeric.
        :return:
        """
        # generate dictionary to map between center labels as
        # digits to labels as a handwritten notation: URFDLB
        kociembas_input_labels = {}
        for center, label in zip(cube_centers, 'U R F D L B'.split()):
            kociembas_input_labels[center] = label

        # generate the cube's state as a list of strings of 6x9 labels
        cubestate = [kociembas_input_labels[label] for label in rubiks_labels]
        cubestate = ''.join(cubestate)

        # generate the solution for the given cube's state
        solved = kociemba.solve(cubestate)
        solved = solved.split(' ')

        return solved
Exemple #19
0
    def generateSolution(self):
        """
        Generate a solution for the current cubestring and display in the GUI
        """
        self.statusbar.showMessage("Generating Solution")
        msg = "Generating solution for cubestring: " + self.cube.cubestring
        self.addLogEntry(msg)

        timer = QElapsedTimer()
        timer.start()
        solution = "No Solution"
        try:
            solution = kociemba.solve(self.cube.cubestring)
        except Exception as err:
            print(err)
            error_dialog = QErrorMessage()
            error_dialog.showMessage(err.args[0])
            error_dialog.exec_()
            solution = err.args[0]
            self.statusbar.showMessage("Solution generation failed!")
            msg = "Solution could not be calculated: " + solution
            self.addLogEntry(msg)

        self.lineEdit_InOut.setText(solution)
        self.label_CurrentString.setText("Solution:")
        self.statusbar.showMessage("Generated Solution")
        msg = "Solution calculation took: {} ms".format(timer.nsecsElapsed() /
                                                        1000000)
        self.addLogEntry(msg)

        # self.timer1ms.stop()
        pass
Exemple #20
0
def solve(message):
    f = open('log.txt', 'a')
    f.write('\n {}: {} -> {} \n'.format(str(datetime.datetime.now()), message.chat.username, message.text))
    f.close()
    data = message.text.split()[-1].upper()
    for old, new in ((data[4], 'U'), (data[22], 'F'), (data[40], 'L'), (data[13], 'R'), (data[49], 'B'), (data[31], 'D')):
        data = data.replace(old, new)
    if 'U' and 'R' and 'F' and 'D' and 'L' and 'B' in list(data) and len(data) == 54:
        out = kociemba.solve(data)
        bot.reply_to(message, out, reply_markup=markup)
        for item in out.split():
            f = open('./kubik/{}.jpg'.format(item), 'rb')
            bot.send_photo(message.chat.id, f)
        bot.reply_to(message, str(len(out.split()))+' steps')
        botan.track(config.botan_key, message.chat.id, message, 'color-solve')
    else:
        if len(data) > 54:
            bot.reply_to(message, 'Введены неверные входные данные: Строка содержит > 54 символов',
                             reply_markup=markup)
        elif len(data) < 54:
            bot.reply_to(message, 'Введены неверные входные данные: Строка содержит < 54 символов',
                             reply_markup=markup)
        else:
            bot.reply_to(message, 'Введены неверные входные данные: Должно быть {W, B, R, O, G, Y}',
                             reply_markup=markup)
    def get_moves_to_random_state(self):
        """
        获得从魔方的初始状态到任意状态的解法步骤

        :return: 返回步骤字符串
        """
        return kociemba.solve(self.SOLVED_STATE, self.string)
Exemple #22
0
def solve_interactive(scanner, motors):
    """scan the cube, get a solution from kociemba, then execute it on the robot."""
    input("Press any key to begin scanning the cube.")
    t0 = round(time.time() * 1000)
    state_str = scanner.get_state_string(motors)
    t1 = round(time.time() * 1000)
    logging.info("Scan complete! Cube state: {0}\n".format(state_str))

    input("Press any key to generate the solution.")

    t2 = round(time.time() * 1000)
    solution = kociemba.solve(state_str)
    t3 = round(time.time() * 1000)
    logging.info("Finished solving! Solution: {0}\n".format(solution))

    input("Press any key to execute the solution.")

    t4 = round(time.time() * 1000)
    motors.execute(solution)
    t5 = round(time.time() * 1000)

    logging.info('Scan time: {:d}ms'.format(t1 - t0))
    logging.info('Solve time: {:d}ms'.format(t3 - t2))
    logging.info('Execution time: {:d}ms'.format(t5 - t4))

    return(0)
    def solve(self):
        """
        kociemba算法解魔方

        :return: 返回步骤字符串
        """
        return kociemba.solve(self.string)
Exemple #24
0
def sol(input1):
    input2 = [[[]], [[]], [[]], [[]], [[]], [[]]]

    for i in range(6):
        if (input1[i][1][1] == 'Y'):
            input2[0] = input1[i]
            break

    for i in range(6):
        if (input1[i][1][1] == 'O'):
            input2[1] = input1[i]
            break

    for i in range(6):
        if (input1[i][1][1] == 'G'):
            input2[2] = input1[i]
            break

    for i in range(6):
        if (input1[i][1][1] == 'W'):
            input2[3] = input1[i]
            break

    for i in range(6):
        if (input1[i][1][1] == 'R'):
            input2[4] = input1[i]
            break

    for i in range(6):
        if (input1[i][1][1] == 'B'):
            input2[5] = input1[i]
            break

    for i in range(6):
        for j in range(3):
            for k in range(3):
                if (input2[i][j][k] == 'Y'):
                    input2[i][j][k] = 'U'
                elif (input2[i][j][k] == 'W'):
                    input2[i][j][k] = 'D'
                elif (input2[i][j][k] == 'O'):
                    input2[i][j][k] = 'R'
                elif (input2[i][j][k] == 'R'):
                    input2[i][j][k] = 'L'
                elif (input2[i][j][k] == 'G'):
                    input2[i][j][k] = 'F'
                elif (input2[i][j][k] == 'B'):
                    input2[i][j][k] = 'B'

    b = ''
    for i in range(6):
        for j in range(3):
            for k in range(3):
                b += input2[i][j][k]

    a = kociemba.solve(b)
    a = a.replace("U", "R L F2 B2 R' L' D R L F2 B2 R' L'")
    a = a.replace("U'", "R L F2 B2 R' L' D' R L F2 B2 R' L'")
    a = a.replace("U2", "R L F2 B2 R' L' D2 R L F2 B2 R' L'")
    return a
Exemple #25
0
def main():
    cube_state.clear()

    parser = argparse.ArgumentParser()

    parser.add_argument('-i',
                        '--images',
                        default=os.getcwd() + '/images-main2/',
                        help='File path to images folder')
    args = parser.parse_args()
    image_folder = args.images

    img_number = 1

    for filename in sorted(os.listdir(image_folder)):
        if filename.endswith(".jpeg") or filename.endswith(
                ".jpg") or filename.endswith(".png"):
            path = os.path.join(image_folder, filename)
            face_state = detectColors(path, img_number)
            cube_state.extend(face_state)
            img_number += 1
    kociemba_string = getKociembaString(cube_state)

    # key = cv2.waitKey() & 0xFF
    # if key == ord('q'):
    #     cv2.destroyAllWindows()
    if (len(kociemba_string) != 54):
        print("Incorrect length for Kociemba input")
    print(kc.solve('RRBBUFBFBRLRRRFRDDURUBFBBRFLUDUDFLLFFLLLLDFBDDDUUBDLUU'))
    def run(self):
        state = webcam.scan()
        if not state:
            print(
                '\033[0;33m[QBR SCAN ERROR] Ops, you did not scan in all 6 sides.'
            )
            print('Please try again.\033[0m')
            Die(1)

        unsolvedState = combine.sides(state)
        try:
            algorithm = kociemba.solve(unsolvedState)
            length = len(algorithm.split(' '))
        except Exception as err:
            print(
                '\033[0;33m[QBR SOLVE ERROR] Ops, you did not scan in all 6 sides correctly.'
            )
            print('Please try again.\033[0m')
            Die(1)

        print('-- SOLUTION --')
        print('Starting position:\n    front: green\n    top: white\n')
        print(algorithm, '({0} moves)'.format(length), '\n')

        # if self.humanize:
        manual = normalize.algorithm(algorithm, self.language)
        for index, text in enumerate(manual):
            print('{}. {}'.format(index + 1, text))
        Die(0)
Exemple #27
0
def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('cubot', anonymous=True)
    rate = rospy.Rate(10)
    msg_str = ""
    i = 0
    while (True):
        i += 1
        if i == 20:
            i == 0
            r = requests.get(solve_url)
            # detected the file
            if r.status_code == 200:
                msg_str = str(r.content)
                # trigger to delete
                # requests.get(delete_url)
                break
            else:
                print "trying to read the file ... "
                break
    #msg_str = "DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD"
    print msg_str
    res_str = kociemba.solve(msg_str)
    list_ = res_str.split(" ")
    after_proc_str = ""
    for a in list_:
        after_proc_str += dict[a]
        #after_proc_str += ' '
    print after_proc_str
    # broadcast in ROS
    while not rospy.is_shutdown():

        rospy.loginfo(after_proc_str)
        pub.publish(after_proc_str)
        rate.sleep()
Exemple #28
0
def startSol():
    '''Inicialización de todas las variables necesarias, antiguio main del archivo. Se hizo función para llamarla desde sendSolution'''
    cube = getCube()
    stdSol = kociemba.solve(cube)
    sol = ''.join(stdSol.split())
    filteredSolve = sol
    config.fSolve = areTwoOrPrime(filteredSolve)
    config.listSol = list(config.fSolve)
Exemple #29
0
def solve(cube):
    unsolved_cube = ""
    for face in cube:
        for piece in cube[face]:
            unsolved_cube += Face_Assignment[piece]
    step_by_step_solution = kociemba.solve(unsolved_cube)
    print("Steps to Solve cube : ", step_by_step_solution)
    return step_by_step_solution
 def compute_solution(self, state, callback=None):
     if state == RubiksCube.SOLVED_STR:
         self._solution = []
     else:
         solution = kociemba.solve(state).split(" ")
         self._solution = solution
     if callback is not None:
         callback(self._solution)
Exemple #31
0
 def solve_cube(self):
     str = self.white_str + self.red_str + self.green_str + self.yellow_str + self.orange_str + self.blue_str
     self.sollution = kociemba.solve(str)
     self.sollution = self.sollution.split(" ")
     self.solve_status = True
     print(self.sollution)
     self.next = Button(self.root, text ="step",width=15,height=1, command = self.step,bg="#DCDCDC")
     self.next.place(x=770,y=510,in_=self.root)
Exemple #32
0
    def add_task(self, cube):
        if self.server is not None:
            self.display = True

        faces = self.revert_faces(cube)
        if self.display:
            self.display_task(faces)
        steps = kociemba.solve(cube)
        self.execute_steps(steps)
Exemple #33
0
def calculate(data):
        seq_raw = solve(data)
        seq_new = []
        for seq in seq_raw.split(" "):
                if len(seq)==1:
                        seq_new.append(seq)
                else:
                        if seq[1]=="'":
                                seq_new.append(seq[0].lower())
                        else:
                                seq_new.extend([seq[0],seq[0]])
        return seq_new
    return side_sequence


def calibrate():
    t = 0
    while t < 6:
        ser.write("set value")
        k = 0
        while (k == 0):
            k = input("press '0' to start motor " + str(t) + " : ")


while True:
    side_sequence = getCube()
    print "cube : ", side_sequence
    try:
        solve = kociemba.solve(side_sequence)
        break
    except:
        print "Error in cube, please re-scan"
solve = solve + " "
print solve
k = 0
calibrate()
while k == 1:
    k = input("Start solving ? :")

ser.write(solve.encode('ascii', 'ignore'))

cv2.destroyAllWindows()
Exemple #35
0
def test_solve_function(input, expected):
    assert solve(input) == expected
Exemple #36
0
def main():
    if len(sys.argv) > 1:
        print(solve(sys.argv[1]))
    else:
        print('Usage: kociemba <cubestring>\nfor example:\nkociemba DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD')
Exemple #37
0
    ],
)
def test_solve_function(input, expected):
    assert solve(input) == expected


if __name__ == "__main__":
    import sys
    import logging

    logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
    if len(sys.argv) > 1:
        fname = sys.argv[1]
        logging.info("loading tests from %s", fname)
        with open(fname, "rb") as f:
            cnt = 0
            t = f.readline()
            while t:
                logging.info("running test %d..." % (cnt + 1))
                t = t.strip()
                r = f.readline().strip()
                res = solve(t)
                if res != r:
                    logging.error("Error for %s:\n\tmust be: %s\n\tgot: %s" % (t, repr(r), repr(res)))
                    sys.exit(1)
                cnt += 1
                t = f.readline()
            logging.info("all %d tests passed" % cnt)
    else:
        logging.error("Usage: %s <testfile.txt>", sys.argv[0])
Exemple #38
0
def test_solve_pattern_function(input, pattern, expected):
    assert solve(input, pattern) == expected
Exemple #39
0
def solve(cube_str):
    return kociemba.solve(cube_str)